text:
Q: how to use conditionalpanel() in shiny r I am trying to create a shiny app where it allows you to select an input of what operation calculate. if the user chooses "Addition" it will show the two numeric input boxes (so they can input two numbers), if the user chooses "square" it will show only one numeric input box to square.
With this, I use conditionalPanel and if the condition is satisfied, it fetches through uiOutput() the numericInputs that I want. and same thing for square.
Now when I run this app, the conditional panels do not appear. Where did I go wrong? Thanks for checking out my question.
ui <- fluidPage( theme = shinytheme("slate"),
                 titlePanel("Basic Calculator"),
                 sidebarPanel(
                          selectInput("ops","Select what Operation use",choices = c("ADDITION","SQUARE")),

                          helpText("Please input the appropriate number depending on the operations"),
                          conditionalPanel("input.ops=='ADDITION'", uiOutput("var2")),
                          conditionalPanel("input.ops=='SQUARE'", uiOutput("var1"))

                          ),#sidebar panel

)#fluidpage

server <- function(input, output) {

  output$basicmath <- renderText( ifelse(input$ops=="ADDITION",input$a+input$b,
                                  ifelse(input$ops=="SUBTRACTION",input$a-input$b,
                                  ifelse(input$ops=="SQUARE",input$a*input$a,
                                  ifelse(input$ops=="SQUARE ROOT",sqrt(input$a),
                                  ifelse(input$ops=="MULTIPLICATION",input$a*input$b,"not a valid operation"))))),

  output$var2 <- renderUI({
                            helpText("this will show to input two numerics to be added")

                          }) ,

  output$var1 <- renderUI({
                           helpText("this will show to input one numeric to square")

  })

)}

shinyApp(ui = ui, server = server)

A: The key issue you were having is that you put the uiOutputs inside the calculation output that you anticipated. It is better to separate them, since the calculation output won't run until it has the necessary prerequisite values (your input values). In addition, because you hadn't specified an output location for basicmath, the app didn't know where to put anything inside that call to renderText(). Below is working code that gets the right UI elements to appear.
One other thing you were missing in your renderUI was the use of tagList(). This helps ensure that all of your elements are packaged together, not just the last one.
Note that the math part does not work, but it looks like that was just a placeholder. When you do start to use it, be sure to use unique ids for each input. You have several instances of input$a and input$b, which probably isn't a workable approach.
library(shiny)
library(shinythemes)

ui <- fluidPage( theme = shinytheme("slate"),
                 titlePanel("Basic Calculator"),
                 sidebarPanel(
                   selectInput("ops","Select what Operation use",choices = c("ADDITION","SQUARE")),
                   helpText("Please input the appropriate number depending on the operations"),
                   conditionalPanel("input.ops=='ADDITION'", uiOutput("var2")),
                   conditionalPanel("input.ops=='SQUARE'", uiOutput("var1"))
                 ),
                 mainPanel(
                   textOutput("basicmath")
                 )
)#fluidpage

server <- function(input, output) {

  output$var2 <- renderUI({
    tagList(
      helpText("this will show to input two numerics to be added"),
      splitLayout(
        numericInput("var2a", label = "Input one number", value = NULL),
        numericInput("var2b", label = "Input another number", value = NULL)
      )
    )
  })

  output$var1 <- renderUI({
    tagList(
      helpText("this will show to input one numeric to square"),
      numericInput("var1a", label = "Input a number", value = NULL)
    )
  })

  output$basicmath <- renderText( {ifelse(input$ops=="ADDITION",input$a+input$b,
                                         ifelse(input$ops=="SUBTRACTION",input$a-input$b,
                                                ifelse(input$ops=="SQUARE",input$a*input$a,
                                                       ifelse(input$ops=="SQUARE ROOT",sqrt(input$a),
                                                              ifelse(input$ops=="MULTIPLICATION",input$a*input$b,"not a valid operation")))))
  })
}

shinyApp(ui = ui, server = server)


text:
Q: JavaFX | username and password checking does not work right I'm playing around with JavaFX and created a login form. So I want to test the inevitable, insert usernmae and password to check if correct. The problem is that it doesn't run as expected. It will always go to the else body no matter what. Code below:
public class Controller {
    @FXML PasswordField pass;
    @FXML TextField name;
    @FXML javafx.scene.control.Button login;
    @FXML Hyperlink signup;
    @FXML Label errormessage;

    @FXML private void buttonPressed() {
        checkUser();
    }

    @FXML private void ifEnterIsPressed(KeyEvent k) {
        if (k.getCode() == KeyCode.ENTER)
            checkUser();
    }

    @FXML private void checkUser() {
        System.out.println(name.getCharacters());
        System.out.println(pass.getCharacters());
        if (name.getCharacters().equals("Marios") && pass.getCharacters().equals("19981998")) {
            errormessage.setVisible(false);
            System.out.println("Access granted!");
        }
        else {
            errormessage.setText("Wrong username or password");
            System.out.println("Access denied");
        }
    }
}

I don't know if I'm missing something completely obvious here or what...
Thanks in advance!

A: The issue is your use of the TextField.getCharacters() method. This isn't the same thing as calling TextField.getText(). Currently, for Java 10, the method TextField.getCharacters() returns a StringBuilder (which is a CharSequence) rather than a String. This is can be expected because the Javadoc states:

Returns the character sequence backing the text field's content.

By "content" it most likely means the backing TextInputControl.Content and the source code of TextField seems to confirm this. What you want to compare, however, is the String contained in the textProperty() of the TextField.
Apparently, and I didn't know this (though its understandable), a StringBuilder does not equals a String even if they contain the same characters. Or, to put it in code:
StringBuilder sb = new StringBuilder("Hello, World!");
String s = "Hello, World!";
sb.equals(s); // FALSE
sb.toString().equals(s); // TRUE

So, to answer directly, change name.getCharacters() and pass.getCharacters() to name.getText() and pass.getText(), respectively.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Initializing a const array with size sizeof(int) If I wanted to initialize an array of constant integers in c++ that has size sizeof(int), how would I go about doing that? For example, I might want an array such that it has sizeof(int)*8 ints with the nth bit on (array[n]=1 << n).

A: Here's one way to initialize a constant array of 4 integers where sizeof(int) == 4:
#define SHIFT(__n) (1 << __n++)

int main()
{
    int n = 0;
    const int ir4[sizeof(int)] = {SHIFT(n), SHIFT(n), SHIFT(n), SHIFT(n)};

    ...
}

A: You can use std::array and a template
template<typename T, std::size_t N>
std::array<T, sizeof(T)*N> array_init() {
    std::array<T, sizeof(T)*N> ints;
    for (T n = 0; n < sizeof(T)*N; ++n) {
    ints[n] = 1 << n;
    }
    return ints;
}

Then you call it like
auto ints = array_init<int, 8>();

A: I don't think you can initialize a statically sized array of const objects without specifying each element, at least, not when it isn't a member of class. You can, however, initialize a reference to a statically sized array of const objects:
template <int N>
struct foo
{
    static bool init(int* array) {
        unsigned int bit(1);
        for (int i(0); i != N; ++i) {
            array[i] = bit << i;
        }
        return true;
    }
    static void use(bool) {}
    static int const (&array())[N] {
        static int rc[N];
        static bool dummy(init(rc));
        use(dummy);
        return rc;
    }
};

int const (&array)[sizeof(int) * 8] = foo<sizeof(int) * 8>::array();

If you really want to initialize a statically sized array, you can do it using variadic templates but the array would need to be a static member of a class type. Since the code isn't quite as obvious, here it is:
template <int...> struct indices {};
template <int N, typename> struct make_list;
template <int... Indices>
struct make_list<0, indices<Indices...>> {
    typedef indices<0, Indices...> type;
};
template <int N, int... Indices>
struct make_list<N, indices<Indices...>> {
    typedef typename make_list<N-1, indices<N, Indices...>>::type type;
};

template <int N, typename> struct array_aux;
template <int N, int... Indices>
struct array_aux<N, indices<Indices...>>
{
    static int const values[N];
};

template <int N, int... Indices>
int const array_aux<N, indices<Indices...>>::values[N] = { 1u << Indices... };

template <int N = sizeof(int) * 8>
struct array
    : array_aux<N, typename make_list<N-1, indices<>>::type>
{
};

With that you could then access the array using something like this:
array<>::values[i]


text:
Q: Matlab: Structure with 6x6 matrices - how to get the average across the group I have a structure named 'data' with 100 entries, each corresponding to a participant from an experiment. Each of the 100 entries contains multiple 6x6 matrices giving different values.
For instance, an example of a matrix from my first participant is:
data.p001.matrixCB

   18.9737   17.0000   14.2829   12.4499   11.7898   10.0995
   18.1384   16.0000   13.4907   11.7898   11.2250   10.3441
   14.7986   12.5300   11.7898   11.7473   12.2066    9.3808
   14.3527   13.4536   12.9615   13.3417   12.7279   11.7047
   18.0278   17.8885   17.6068   17.4642   17.1464   16.6132
   24.1661   24.7790   23.7697   23.3880   22.6495   23.8537

...and this is one of 100 entries in the structure with a similar setup.
I'd like to get the mean average value for each cell in the matrix across my 100 participants. So I would have a mean value for the 100 values in position matrixCB(1,1), and all other positions in the matrix. Unfortunately I can't see how this is done, and the help functions are less than helpful. Any assistance would be greatly appreciated!

A: You can sum all your 100 matrix into Sum and then divide it by 100  - Sum./100 and then each cell would represent the avg of all 100 cells on each index   .
For example  -
Sum = A + B ;
Sum./2 ;

A: Structures can be a pain.  To avoid typing out a bunch of code, you could take the following approach:

*

*Convert required matrices to cell array

*Reshape the cell array into 3D matrix

*Compute means across 3rd dimension

Code for this:
Mcell = arrayfun(@(x) data.(sprintf('p%03d',x)).matrixCB, 1:100, 'uni', 0);
M = mean( reshape(cell2mat(Mcell), 6, 6, []), 3 );


text:
Q: AirPods volume suddenly too low in Android mobile device The volume of the Airpods (Gen. 2) will become suddenly too low on my Android mobile device (Aquaris U2 with Android version 8.1.0).
It usually works all fine, but it just happens (twice so far) that at some point when I start listening to a podcast the volume will be so low than I can barely hear anything, even if I set the volume at the maximum.
The first time it happened, I managed to fix it somehow, but I do not know how and I am not managing to replicate it now.
Other information that might be useful to find a solution:

*

*Both times, the issue popped-up while listening to a podcast on Spotify. However, once the issue appears, also other apps like Youtube have the volume too low.
For other uses like calls, there is no problem with the volume.

*I never had this problem with other Bluetooth headphones.

*The AirPods work great on my laptop.

Note that this is a different problem than this question, as it is not about a firmware update.
So far I have tried, without success:

*

*Unpairing and pairing the AirPods again.

*Restarting the mobile phone.

*Going to Developer Options > Disable Absolute Volume and turning the switch to the On position, as suggested here + restarting.

*Turning the volume down and up again, as suggested in the comments of the link provided in point number 3. Also turning it totally down, restarting it and then up again.

*Roll back the Bluetooth AVRCP Version (also under Developer Options) from 1.4 to 1.3, also suggested in the same comments as above.

Any ideas of what the problem is and how to fix it?

A: For future reference, the solution that works for me every time is resetting the AirPods by pressing the button on the back of the AirPods for 15 seconds.
Then I will need to pair them again and it will work fine.
This solution can be found here and here.
Note that this is only a temporary fix. The volume issue will continue to appear randomly and this solution will have to be applied again and again...
If anybody has a solution that fixes the issue forever, please share it.

A: After some time testing different things, I found a way to avoid this issue from happening ever again.
I noticed that the problem pop up when:

*

*The AirPods were connected to the phone and working properly.

*The AirPods were disconnected because I put them back into the case, but the Bluetooth on the phone was still enabled.

*I took the AirPods out of the case again and they automatically connected to the phone.

Once I started disabling the Bluetooth of my phone each time I put the AirPods back into the case, I never faced the problem again.


text:
Q: How can I mitigate DNS Server outages? Let's say I have a root domain of "mysite.com". That domain and its sub-domains have DNS served by an external service - let's call them Setwork Nolutions. If this external company is hit with a DDoS attack, my interally-hosted websites under this domain are no longer accessible at "mysite.com" or "*.mysite.com", even though the website(s) is/are fully up and operational.
How can I mitigate such a problem so as to keep end users happy?
The only solution others at my company have come up with is to create a second domain - i.e. "mysite2.com", and host its DNS at another company, and then communicate to all end users that this is the website they should use. I think this is ridiculous, and just leads to a bunch of other problems.
I'd like to find a solution where we can point to the same website with the same URL without the original DNS host being operational.
Any thoughts?

A: You can set up additional DNS servers outside of SN and then register those nameservers as authoritative for that domain.
One such DNS provider I can strongly recommend is called UltraDNS.
This will solve all the problems.  Instead of having:
mysite.com ns ns1.sn.com
mysite.com ns ns2.sn.com

you'd have:
mysite.com ns ns1.sn.com
mysite.com ns ns2.sn.com
mysite.com ns ns3.ultradns.com

If your real problem is only internally-hosted websites, you could partially mitigate any outage of your authoritative nameservers by setting up local caching nameserers for your domain and then pointing your LAN machines at these caching nameservers.
http://www.tldp.org/HOWTO/DNS-HOWTO-3.html
Combine this with a somewhat longer TTL (say as long as a outage you'd like to survive * 2) and you should be able to survive that scenario just fine.
As a final, oh crap, we're down, always remember a local /etc/hosts entry (or equivalent) can get you out of a jam.

A: You will encounter this problem with any domain whose servers are hit by a DDOS attack.  Having the servers for your own domain hit by a DDOS is more likely to be visible and traceable.
Setting up one or more caching name servers on your own network and configuring your computers to use those for DNS resolution should resolve the problem unless the DDOS is extremely prolonged.  I use dnsmasq on a linux server, and have run it on an OpenWRT router.  It will also read values from /etc/hosts and/or other files in the same format.
It your external DNS host supports it, you could run a local bind server as a hidden slave.  This would provide the best protection you could get without hosting DNS locally.   Alternatively, you could run bind as your local caching name server.


text:
Q: Debugging a Fortran program using Emacs (on MacOS) I am trying to debug a fortran program within Emacs using GDB. My compiler is intel fortran 2017.4. The problem is with a particular subroutine which inverts a matrix. The program runs without a problem when the size of the matrix is "small" i.e. 100x100. When I increase the size of the matrix to, for example 600x600, I get the following message: "Thread 3 received signal SIGSEGV, Segmentation fault."
Now, if I try to debug the program launching GDB from the terminal, everything works fine. I strongly prefer to debug the program from within Emacs since it would save me a lot of time. Any ideas about how can I fix this issue?
I already try to increase the stack size to the max (which is 65532 for MAC) and all the arrays are allocated on the heap.
Thanks for your help,

A:
Now, if I try to debug the program launching GDB from the terminal, everything works fine.

It appears that your program does not crash when run from GDB (whether GDB is invoked from within Emacs or from a terminal), in which case your references to Emacs are superfluous.
Some of the reasons why a program may not crash under GDB are listed here.


text:
Q: NVIDIA drivers instalation : "An alternate method of installing the NVIDIA driver was detected." I'm trying to install the newest nvidia drivers for my GTX1060 from the ".run" files provided by nvidia.
 sudo bash NVIDIA-Linux-x86_64-450.80.02.run

Returns an error telling me that  an alternate method of installing the NVIDIA drivers was detected, but I dont know what that alternate method is.
note: I'm bad with linux.  I'm running kubuntu 20.04, upgraded from kubuntu 18.10.   Back when I was running  18.10 I had installed the latest drivers and CUDA.
I don't see any nvidia package installed when I run
dpkg -l | grep nvidia

but modinfo shows I am running the 440.100 nvidia drivers.
modinfo nvidia
filename:       /lib/modules/5.4.0-52-generic/updates/dkms/nvidia.ko
alias:          char-major-195-*
version:        440.100
supported:      external
license:        NVIDIA
srcversion:     79812FEC91C545B3F516DF2
alias:          pci:v000010DEd*sv*sd*bc03sc02i00*
alias:          pci:v000010DEd*sv*sd*bc03sc00i00*
depends:        ipmi_msghandler
retpoline:      Y
name:           nvidia
vermagic:       5.4.0-52-generic SMP mod_unload
sig_id:         PKCS#7
signer:         ryzen Secure Boot Module Signature key
sig_key:        06:8D:79:52:D7:64:F5:CB:29:28:CA:9C:9B:38:4C:E1:23:5E:06:62
sig_hashalgo:   sha512
signature:      B5:01:BC:BD:8B:3C:30:0F:EA:21:0F:CA:9F:78:65:AC:32:D4:2A:55:
                E2:20:45:B5:FB:2D:10:86:FF:2B:56:47:C9:3C:05:B6:5A:73:DF:A6:
                A3:5C:52:9D:05:9F:47:F1:17:13:87:09:06:F7:EE:41:A2:DA:9F:E7:
                F3:78:38:92:70:5A:13:B1:96:44:EC:D0:EC:C0:23:CC:05:94:9C:8D:
                48:01:94:59:36:6E:D5:D0:F4:F0:44:2B:F6:AA:41:9F:52:BC:D9:4F:
                EC:EE:2D:F0:5C:8D:33:79:F8:84:F7:B9:C1:9E:DA:2B:A2:7F:05:80:
                1E:D0:2F:72:26:9D:D4:03:3F:02:0A:EC:08:24:53:83:60:ED:C9:14:
                5A:A0:2E:08:D3:D3:3D:46:B8:EC:27:66:E4:51:74:47:AA:64:68:C7:
                EC:F4:CE:5B:DC:29:A2:5B:56:F1:60:4B:49:04:A7:5C:11:B2:8E:14:
                A5:D4:D5:1B:C0:F5:0E:EF:19:D8:28:28:D3:E4:30:7C:E0:5D:C1:F5:
                05:D8:A9:62:68:FF:C4:B7:BF:1D:16:17:4A:40:93:97:8B:E4:96:AF:
                F6:15:04:D5:54:45:9C:30:29:97:E5:3C:73:AF:B9:F5:B5:01:86:3C:
                E5:EE:4E:09:E7:5D:87:C8:6F:39:49:82:FE:F2:38:B7
parm:           NvSwitchRegDwords:NvSwitch regkey (charp)
parm:           NVreg_Mobile:int
parm:           NVreg_ResmanDebugLevel:int
parm:           NVreg_RmLogonRC:int
parm:           NVreg_ModifyDeviceFiles:int
parm:           NVreg_DeviceFileUID:int
parm:           NVreg_DeviceFileGID:int
parm:           NVreg_DeviceFileMode:int
parm:           NVreg_InitializeSystemMemoryAllocations:int
parm:           NVreg_UsePageAttributeTable:int
parm:           NVreg_MapRegistersEarly:int
parm:           NVreg_RegisterForACPIEvents:int
parm:           NVreg_EnablePCIeGen3:int
parm:           NVreg_EnableMSI:int
parm:           NVreg_TCEBypassMode:int
parm:           NVreg_EnableStreamMemOPs:int
parm:           NVreg_EnableBacklightHandler:int
parm:           NVreg_RestrictProfilingToAdminUsers:int
parm:           NVreg_PreserveVideoMemoryAllocations:int
parm:           NVreg_DynamicPowerManagement:int
parm:           NVreg_EnableUserNUMAManagement:int
parm:           NVreg_MemoryPoolSize:int
parm:           NVreg_KMallocHeapMaxSize:int
parm:           NVreg_VMallocHeapMaxSize:int
parm:           NVreg_IgnoreMMIOCheck:int
parm:           NVreg_NvLinkDisable:int
parm:           NVreg_RegisterPCIDriver:int
parm:           NVreg_RegistryDwords:charp
parm:           NVreg_RegistryDwordsPerDevice:charp
parm:           NVreg_RmMsg:charp
parm:           NVreg_GpuBlacklist:charp
parm:           NVreg_TemporaryFilePath:charp
parm:           NVreg_AssignGpus:charp

Here is the exact warning screen I got  after running
 sudo bash NVIDIA-Linux-x86_64-450.80.02.run

.
    NVIDIA Accelerated Graphics Driver for Linux-x86_64 (450.80.02)

  An alternate method of installing the NVIDIA driver was detected. (This is usually a package provided by your distributor.) A driver installed via that method may integrate better with your system than a driver installed by nvidia-installer.

  Please review the message provided by the maintainer of this alternate installation method and decide how to proceed:

                                                                                Continue installation                                                                                Abort installation

ERROR: The installation was canceled due to the availability or presence of an alternate driver installation. Please see /var/log/nvidia-installer.log for more details.
there really isnt much in the log file:
cat /var/log/nvidia-installer.log

.
nvidia-installer log file '/var/log/nvidia-installer.log'
creation time: Sun Nov  1 20:32:12 2020
installer version: 450.80.02

PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin

nvidia-installer command line:
    ./nvidia-installer

Using: nvidia-installer ncurses v6 user interface
-> Detected 16 CPUs online; setting concurrency level to 16.
-> Installing NVIDIA driver version 450.80.02.
-> An alternate method of installing the NVIDIA driver was detected. (This is usually a package provided by your distributor.) A driver installed via that method may integrate better with your system than a driver installed by nvidia-installer.

Please review the message provided by the maintainer of this alternate installation method and decide how to proceed:

The NVIDIA driver provided by Ubuntu can be installed by launching the "Software & Updates" application, and by selecting the NVIDIA driver from the "Additional Drivers" tab.

(Answer: Abort installation)
ERROR: The installation was canceled due to the availability or presence of an alternate driver installation. Please see /var/log/nvidia-installer.log for more details.

A: Running
ubuntu-drivers devices

shows a bunch of available drivers:
== /sys/devices/pci0000:00/0000:00:03.1/0000:1c:00.0 ==
modalias : pci:v000010DEd00001C03sv00003842sd00006161bc03sc00i00
vendor   : NVIDIA Corporation
model    : GP106 [GeForce GTX 1060 6GB]
driver   : nvidia-driver-435 - distro non-free
driver   : nvidia-driver-440-server - distro non-free
driver   : nvidia-driver-455 - third-party free recommended
driver   : nvidia-driver-418-server - distro non-free
driver   : nvidia-driver-450-server - distro non-free
driver   : nvidia-driver-390 - distro non-free
driver   : nvidia-driver-450 - distro non-free
driver   : xserver-xorg-video-nouveau - distro free builtin

so I just installed my preferred one with apt install..
sudo apt install nvidia-driver-450

modinfo nvidia now shows the latest version:
modinfo nvidia
filename:       /lib/modules/5.4.0-52-generic/updates/dkms/nvidia.ko
alias:          char-major-195-*
version:        450.80.02
supported:      external
license:        NVIDIA


text:
Q: WPF Blend animation button events I have animations:

*

*btnHome.MouseEnter

*btnHome.MouseLeave

On mouse enter/leave they are called correctly, but on touch MouseEnter fires and MouseLeave not.
Is there a way to have event for TouchLeave (there is no such event in Blend for button) so i can call this animation, or at least to prevent animations when touch used?


text:
Q: Using custom keras model with layer sharing together dqn_agent.DqnAgent() I am trying to use a custom neural network with the DqnAgent() from tf. In my model I need to use layer sharing. Thus, I use the functional API to build the model. The model has a dict as input and one layer with n neurons as output. The last layer is a Concat- and not a Dens-Layer though. The type of the model that i get from the functional API keras.Model(inputs=[...], outpunts[...]
is "keras.engine.functional.Functional".
Now i want to use my Model with the tf Agent like this:
agent = dqn_agent.DqnAgent(
    train_env.time_step_spec(),
    train_env.action_spec(),
    q_network=model,
    optimizer=optimizer,
    td_errors_loss_fn=common.element_wise_squared_loss,
    train_step_counter=train_step_counter)

I get the following Error thoug:
AttributeError: 'Functional' object has no attribute 'create_variables'
  In call to configurable 'DqnAgent' (<class 'tf_agents.agents.dqn.dqn_agent.DqnAgent'>)

The q_network expects a network from type "network.Network". I am not sure how to convert or wrap my environment in such a way, that the DqnAgent() will accept it. How could I manage to do this? Any support is much appreciated. If you need more information about anything let me know.
Additional information about my Network:

*

*Input dict with multiple inputs.

*multiple shared dens layers. output of the last one is shape (1,).

*concatenate all those outputs of shape (1,)

*one multipy layer to eliminate infeasible actions by multiplying the outputs with 0 or 1 respectively.


text:
Q: download .zip file from server in nodejs I am using MEAN, in which I want to allow user to download zip file from server.
So basically I have to do following things:

*

*Create csv files from certain data.

*Store that file into some directory.

*Compress these file to zip.

*When a user clicks on the button, zipped file should be downloaded and readable.

I have achieved 1,2,3 completely, and 4 partially. In this I have been able to successfully download zip file, but this file is in corrupted format and I am not able to read this file.
My code for download functionality is here:
html:
Download CSV Reports
angular part:
$scope.downloadFiles = function() {
    $http({
      method: 'GET',
      url: '/download/csv/files'
    }).
    success(function(data, status, headers, config) {
      var anchor = angular.element('<a/>');
      anchor.attr({
        href: 'data:attachment' + encodeURI(data),
        target: '_blank',
        download: 'filename.zip'
      })[0].click();
    }).
    error(function(data, status, headers, config) {
      alertify.error(data);
    });
  };

NodeJS:

    var path = require('path'),
        fs = require('fs');

    exports.downaloadAllCsv = function(req, res) {

    var file = 'local path to my zip file',
      filename = path.basename(file);

      res.setHeader('Content-disposition', 'attachment; filename=' + filename);

      res.setHeader('Content-type:',' application/zip');

      var filestream = fs.createReadStream(file);
      filestream.pipe(res);
     };

A: I used an npm library called express-zip (found here: https://www.npmjs.com/package/express-zip)
Using Node 4.X and Express 4.X, I can download a zip file from my browser.  Getting it to work through Angular is what lead me to my own question:
Client download of a server generated zip file
Given all of that, here is my server code that worked:
Node (4.X) code with express-zip:
router.get('/bulkdownload',function(req,resp){
    var titles = req.query.titles || [];

    if ( titles.length > 0 ){
        utils.getFileLocations(titles).
        then(function(files){
            let filename = '/tmp/zipfile.zip';

            // .zip sets Content-Type and Content-disposition
            resp.zip(files,filename);
        },
        _errorCb)
    }
});

The utils.getFileLocations(titles) returns a promise where files is an array like this:
[{path: '/path/to/file/file.abc',name:'file.abc'},{...},{...},...]

My .zip file is not corrupted, and is readable.


text:
Q: Benefit of postfix over prefix notation My compiler design professor said while evaluating a statement, we convert every token into postfix notation. Everything other than function calls are in infix notation, and therefore must be converted to postfix.However functions are in prefix and NOT infix notation. So they must be converted as well.
This can be demonstrated as a+b in infix being equivalent to +(a,b) or +ab in prefix notation.
However, I do not understand why we must convert everything to postfix and not prefix notation instead? Functions are already in prefix, so shouldn't it be faster to convert non function entities to prefix notation and execute in reverse?

A: The approach your instructor is describing is one possible approach to parsing expressions, but it's not the only one. Fundamentally, the goal of parsing is to get the expression into a format that's easy to work with and interpret, and both prefix and postfix notations meet those requirements. In an actual compiler it's far more common to build an abstract syntax tree, a tree encoding the structure of the input, and you can think of both prefix and postfix notations as either a preorder or postorder walk of that tree.
As for efficiency - the actual difference in cost between using prefix and postfix notations are trivial and are not going to be the bottleneck in your compiler. Typically, the most time-intensive phase of a compiler is optimization, with parsing consuming very little time. I wouldn't worry about doing the efficiency of parsing until you have concrete evidence that it's causing a problem.


text:
Q: PHP script to deliver latest version of a file My PHP's rusty and I'm hoping that someone can help me with a quick script - I don't really know where to start with it!
I have a folder containing zipped archives of various versions of a software product:

*

*Product_1.00.zip

*Product_1.05.zip

*Product_2.00.zip

etc.
Now, on my web site I have a button to download the product. However, I'd like that button to always download the latest version.
It seems to me that a nice solution would be to link to a PHP script that would scan the folder for the latest version and deliver that file to the user as if they have pointed the browser directly at the file.
Can anyone provide me with a starting point?

A: I think it's the easiest to read the files from the directory into an array. Then natsort the array and pop off the last entry.
Here is an example:
<?php
function getLatestVersion() {
    $dir = dir('.');
    $files = array();

    while (($file = $dir->read()) !== false) {
        $files[] = $file;
    }
    $dir->close();

    natsort($files);
    return array_pop($files);
}

Outputs
array(6) {
  [0]=>
  string(1) "."
  [1]=>
  string(2) ".."
  [2]=>
  string(16) "Product_1.00.zip"
  [3]=>
  string(16) "Product_1.05.zip"
  [5]=>
  string(16) "Product_2.00.zip"
  [4]=>
  string(17) "Product_10.00.zip"
}

How to download the latest version of the zip file?
EDIT
Like @j_mcnally pointed out in his comment below it's more efficient to let the webserver handle the serving of static files. Possible ways are direct links or redirecting the request from the PHP file to the right location using a 301.
But if you still want to let PHP do the work. Here is an example.

Grabbed the example below from http://perishablepress.com/http-headers-file-downloads and altered it a bit.
<?php // HTTP Headers for ZIP File Downloads
// http://perishablepress.com/press/2010/11/17/http-headers-file-downloads/

// set example variables

// Only this line is altered
$filename = getLatestVersion();

$filepath = "/var/www/domain/httpdocs/download/path/";

// http headers for zip downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
@readfile($filepath.$filename);
?>

A: This should work. Of course, more checks can be added depending on what else can be stored in that folder; you may also change the way of reading the folder content if it contains too many files, etc.
Keyword in this code is probably strnatcmp() for strings comparison.
<?php
$files = scandir('/path/to/files');
$result = array_reduce(
    $files,
    function($a, $b) {
        $tpl = '/^Product_(.+).zip$/';
        // return second file name if the first file doesn't follow pattern Product_XXX.zip
        if (!preg_match($tpl, $a)) {
            return $b;
        }
        // return first file name if the second file doesn't follow pattern Product_XXX.zip
        if (!preg_match($tpl, $b)) {
            return $a;
        }
        return strnatcmp($a, $b) >= 0 ? $a : $b;
    },
    ''
);

A: The below will look within the downloads directory, find the latest file (by looking at the modify time of the files) and return the name of the newest file:
$dir = dir("downloads");
$files = array();
while (($file = $dir->read()) !== false) {
    $files[filemtime($file)] = $file;
}
$dir->close();

ksort($files);
$fileToDownload = $files[0];

Hope this helps!

A: This code works by using the file modification time to determine the latest version in the given directory, perhaps using regular expressions on the file names would be a better approach, however this demonstraits PHP's DirectoryIterator.

$files = array();

foreach(new DirectoryIterator("productZips/") as $fileInfo) {

  if(!$fileInfo->isFile()) continue;
  $files[$fileInfo->getMTime()] = $fileInfo->getFilename();
}

ksort($files);
$latestFile = array_pop($files);

You can read more here: http://php.net/manual/en/class.directoryiterator.php


text:
Q: sonarqube failed to start I am currently trying to install sonarqube to try it, but I am unable to make it start.
My OS is Ubuntu 64 bits.
What I did :
First I wanted to try it with all basics settings so I downloaded the last version of sonarqube on their website (5.6). Then I unzipped it and went to the bin/linux-x86-64/ and then I did ./sonar.sh start
The terminal then said Sonarqube started. However, I can't get access to it on the web interface, and my logfile is fulled with this error.

2016.06.20 15:33:15 ERROR web[o.a.c.c.C.[.[.[/]] Exception sending context initialized event to listener instance of class org.sonar.server.platform.RubyRailsContextListener
org.jruby.rack.RackInitializationException: java.lang.NullPointerException
at org.jruby.rack.RackInitializationException.wrap(RackInitializationException.java:31) ~[jruby-rack-1.1.13.2.jar:na]

Full log on pastebin
I am searching a lot since this morning to find out how to solve this but I did not find the answer at this time. Have you any idea or solution to solve this ?
EDIT :
Tried it on my Windows 7 OS => No problem at all, it works perfectly without editing anything. Maybe something is not installed on my Ubuntu sessions, I do not know. I still did not find the fix at the moment.
EDIT 2:
I tried ./sonar.sh console (can't edit my first message because it would be too long)
Running SonarQube...
wrapper  | --> Wrapper Started as Console
wrapper  | Launching a JVM...
jvm 1    | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
jvm 1    |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
jvm 1    |
jvm 1    | 2016.06.21 08:43:46 INFO  app[o.s.a.AppFileSystem] Cleaning or creating temp directory /home/chris/Téléchargements/sonarqube-5.6/temp
jvm 1    | 2016.06.21 08:43:46 INFO  app[o.s.p.m.JavaProcessLauncher] Launch process[es]: /usr/lib/jvm/java-8-oracle/jre/bin/java -Djava.awt.headless=true -Xmx1G -Xms256m -Xss256k -Djava.net.preferIPv4Stack=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -Djava.io.tmpdir=/home/chris/Téléchargements/sonarqube-5.6/temp -javaagent:/usr/lib/jvm/java-8-oracle/jre/lib/management-agent.jar -cp ./lib/common/*:./lib/search/* org.sonar.search.SearchServer /home/chris/Téléchargements/sonarqube-5.6/temp/sq-process3660637613352616230properties
jvm 1    | 2016.06.21 08:43:58 INFO  app[o.s.p.m.Monitor] Process[es] is up
jvm 1    | 2016.06.21 08:43:58 INFO  app[o.s.p.m.JavaProcessLauncher] Launch process[web]: /usr/lib/jvm/java-8-oracle/jre/bin/java -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djruby.management.enabled=false -Djruby.compile.invokedynamic=false -Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError -Djava.net.preferIPv4Stack=true -Djava.io.tmpdir=/home/chris/Téléchargements/sonarqube-5.6/temp -javaagent:/usr/lib/jvm/java-8-oracle/jre/lib/management-agent.jar -cp ./lib/common/*:./lib/server/*:/home/chris/Téléchargements/sonarqube-5.6/lib/jdbc/h2/h2-1.3.176.jar org.sonar.server.app.WebServer /home/chris/Téléchargements/sonarqube-5.6/temp/sq-process3224593936857414396properties
jvm 1    | 2016.06.21 08:44:19 INFO  app[o.s.p.m.Monitor] Process[es] is stopping
jvm 1    | 2016.06.21 08:44:20 INFO  app[o.s.p.m.Monitor] Process[es] is stopped
wrapper  | <-- Wrapper Stopped

I tested on an other computer running Ubuntu 64 bits, with an other connection : exact same error. I do not know what to do at this point ...

A: I just fixed my problem. My sonarqube folder was in a directory containing "é" in his name. It seems that it caused some issues. I moved my folder on my Desktop and tried again, and it works


text:
Q: iOS Image Saving and Accessing Images From NSDocumentDirectory I am very frustrating about to accessing multiple images from NSDocumentDirectory. See the steps what i had done in this process and what i want to get from you.
My App can download images with the following code:
  // get the image from the url
  UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]];

  // Save the image file into document folder
  NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];

  // Saving JPG File
   **NSString *jpefilepath = [dir stringByAppendingPathComponent:[NSString stringWithFormat:@"%dwallpaper.jpg",arc4random()]];**
  NSData *data1 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
                                    [data1 writeToFile:jpefilepath atomically:YES];

With this code i download all images with unique name. and i use jpefilepath directly store in mysql database.
Now i have question about how to access images from directly local path with example code.

A: Load the image:
UIImage *image = [UIImage imageWithContentsOfFile:jpefilepath];

Load the data:
NSData *data = [NSData dataWithContentsOfFile:jpefilepath];

A: Use this method:
    UIImage *testImage = [UIImage imageWithContentsOfFile:filePath];


text:
Q: Adding JavaScript ES6 to Dreamweaver CS6 How do I make it so that Dreamweaver CS6 doesn't give me a syntax error when I use let instead of var?

A: Ok, just go to:
Edit > Preferences > Linting
then Edit the JS file.
add this property:
"esversion" : 6

This helped me.

A: The "Edit > Preferences > Linting then Edit the JS file" is a bogus answer, there is no "linting" option in the preferences of Dreamweaver CS6.  The "linting" feature wasn't added until Creative Cloud.  It is unlikely that there will be a patch, Adobe wants you to switch to a subscription-based version instead.
Screenshot of Dreamweaver settings


text:
Q: I would like to mint a new token on solana. How can I do this using solana-web3.js? I'm using the solana-web3.js but can't find any examples for how to create and mint my own tokens. What's the best way to do this?

A: Here's an example of how you can do that.
Assumptions:

*

*You (mintRequester) have a Phantom wallet.

*The minting will take place from a separate minting wallet, and not your Phantom wallet.

*Some SOL is air-dropped into this newly created minting wallet to handle the minting charges.

*Your new token has 6 decimal places and you are minting 1 token.

*The token(s) are finally transferred from your minting wallet to your Phantom wallet.

Code

import * as web3 from '@solana/web3.js';
import * as splToken from '@solana/spl-token';

 const getProvider = async () => {
    if ("solana" in window) {
      const provider = window.solana;
      if (provider.isPhantom) {
        console.log("Is Phantom installed?  ", provider.isPhantom);
        return provider;
      }
    } else {
      window.open("https://www.phantom.app/", "_blank");
    }
  };

const mintingTest = async () => {
    const phantomProvider = await getProvider();
    const mintRequester = await phantomProvider.publicKey;
    console.log("Public key of the mint Requester: ", mintRequester.toString());

    //To connect to the mainnet, write mainnet-beta instead of devnet
    const connection = new web3.Connection(
      web3.clusterApiUrl('devnet'),
      'confirmed',
    );

    //This fromWallet is your minting wallet, that will actually mint the tokens
    var fromWallet = web3.Keypair.generate();

    // Associate the mintRequester with this wallet's publicKey and privateKey
    // This is basically the credentials that the mintRequester (creator) would require whenever they want to mint some more tokens
   // Testing the parameters of the minting wallet

    console.log("Creator's Minting wallet public key: ",fromWallet.publicKey.toString());
    console.log(fromWallet.secretKey.toString());

    // Airdrop 1 SOL to the minting wallet to handle the minting charges
    var fromAirDropSignature = await connection.requestAirdrop(
      fromWallet.publicKey,
      web3.LAMPORTS_PER_SOL,
    );

    await connection.confirmTransaction(fromAirDropSignature);
    console.log("Airdropped (transferred) 1 SOL to the fromWallet to carry out minting operations");

    // This createMint function returns a Promise <Token>
    let mint = await splToken.Token.createMint(
      connection,
      fromWallet,
      fromWallet.publicKey,
      null,
      6, // Number of decimal places in your token
      splToken.TOKEN_PROGRAM_ID,
    );

    // getting or creating (if doens't exist) the token address in the fromWallet address
    // fromTokenAccount is essentially the account *inside* the fromWallet that will be able to handle the              new token that we just minted
    let fromTokenAccount = await mint.getOrCreateAssociatedAccountInfo(
      fromWallet.publicKey,
    );

    // getting or creating (if doens't exist) the token address in the toWallet address
    // toWallet is the creator: the og mintRequester
    // toTokenAmount is essentially the account *inside* the mintRequester's (creator's) wallet that will be able to handle the new token that we just minted
    let toTokenAccount = await mint.getOrCreateAssociatedAccountInfo(
      mintRequester,
    );

    // // Minting 1 token
    await mint.mintTo(
      fromTokenAccount.address,
      fromWallet.publicKey,
      [],
      1000000 // 1 followed by decimals number of 0s // You'll ask the creator ki how many decimals he wants in his token. If he says 4, then 1 token will be represented as 10000
    );

    console.log("Initial mint successful");

    // This transaction is sending of the creator tokens(tokens you just created) from their minting wallet to their Phantom Wallet
    var transaction = new web3.Transaction().add(
      splToken.Token.createTransferInstruction(
        splToken.TOKEN_PROGRAM_ID,
        fromTokenAccount.address,
        toTokenAccount.address,
        fromWallet.publicKey,
        [],
        1000000, // This is transferring 1 token, not 1000000 tokens
      ),
    );

    var signature = await web3.sendAndConfirmTransaction(
      connection,
      transaction,
      [fromWallet],
      {commitment: 'confirmed'},
    );

    const creatorTokenAddress = mint.publicKey;
    const creatorTokenAddressString = mint.publicKey.toString();

    console.log("SIGNATURE: ", signature); //Signature is basically like the paying party signs a transaction with their key.
    console.log("Creator Token Address: ", creatorTokenAddressString);
    console.log("Creator Minting Wallet Address: ", mint.payer.publicKey.toString());

    let creatorTokenBalance = await toTokenAccount.amount;
    console.log("Creator's Token Balance: ", creatorTokenBalance);
  };

A: For this you'll also need to be using our token program js bindings. You can import them via npm as you can see in the sample code below.

const web3 =  require('@solana/web3.js');
const splToken = require('@solana/spl-token');

(async () => {

    //create connection to devnet
    const connection = new web3.Connection(web3.clusterApiUrl("devnet"));

    //generate keypair and airdrop 1000000000 Lamports (1 SOL)
    const myKeypair = web3.Keypair.generate();
    await connection.requestAirdrop(myKeypair.publicKey, 1000000000);

    console.log('solana public address: ' + myKeypair.publicKey.toBase58());

    //set timeout to account for airdrop finalization
    let mint;
    var myToken
    setTimeout(async function(){

        //create mint
        mint = await splToken.Token.createMint(connection, myKeypair, myKeypair.publicKey, null, 9, splToken.TOKEN_PROGRAM_ID)

        console.log('mint public address: ' + mint.publicKey.toBase58());

        //get the token accont of this solana address, if it does not exist, create it
        myToken = await mint.getOrCreateAssociatedAccountInfo(
            myKeypair.publicKey
        )

        console.log('token public address: ' + myToken.address.toBase58());

        //minting 100 new tokens to the token address we just created
        await mint.mintTo(myToken.address, myKeypair.publicKey, [], 1000000000);

        console.log('done');

    }, 20000);

})();


text:
Q: EF Codefirst and RDLC Reports I'm working on a MVC4 web app with EF 6. I'm using EF code first approach (on a brand new database). So i have the model classes which i use in EF.
Now i need to create some RDLC Reports. To do this i need to create a Dataset. So how can i create a dataset using my model classes? There are relationships between models classes which i need to carry to the dataset.
My ultimate goal is to design and populate data to my report using my ef models.
Thanks in Adance

A: Generally EF does not support DataSets. If you want to populate DataSets with data loaded with EF then you've got to provide your own functionality for that. Here I present an example how to populate DataTable object from result obtained with query:
public static class IEnumerableExtensions
{
    public static DataTable ToDataTable<TEntity>(this IEnumerable<TEntity> entities)
    {
        DataTable table = new DataTable();
        IEnumerable<PropertyInfo> properties = typeof(TEntity)
            .GetProperties()
            .Where(p => !p.PropertyType.IsClass || p.PropertyType == typeof(string))
        foreach(string propertyName in properties.Select( p => p.Name))
        {
            table.Columns.Add(propertyName);
        }
        foreach(object item in entities)
        {
            List<object> propertiesValues = new List<object>();
            foreach (PropertyInfo property in properties)
            {
                propertiesValues.Add(property.GetValue(item));
            }
            table.Rows.Add(propertiesValues.ToArray());
        }
        return table;
    }
}

You might use then this extension method as follows:
DataTable table = context.People.ToDataTable();

If you want to implement relationships between tables then the logic you have to do will be more complicated. You should use ChildRelations property of DataTable objects to bind them with relations. Then your DataTable objects you might insert into DataSet.


text:
Q: R creating combinations with replacement I have a small example like the following:
df1 = data.frame(Id1=c(1,2,3))

I want to obtain the list of all combinations with replacement which would look like this:

So far I have seen the following functions which produces some parts of the above table:
a) combn function
t(combn(df1$Id1,2))

# Does not creates rows 1,4 and 5 in the above image

b) expand.grid function
expand.grid(df1$Id1,df1$Id1)

# Duplicates rows 2,3 and 5. In my case the combination 1,2 and 2,1
#are the same. Hence I do not need both of them at the same time.

c) CJ function (from data.table)
#install.packages("data.table")
CJ(df1$Id1,df1$Id1)

#Same problem as the previous function

For your reference, I know that the in python I could do the same using the itertools package (link here: https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem)
Is there a way to do this in R?

A: Here's an alternative using expand.grid by creating a unique key for every combination and then removing duplicates
library(dplyr)

expand.grid(df1$Id1,df1$Id1) %>%
   mutate(key = paste(pmin(Var1, Var2), pmax(Var1, Var2), sep = "-")) %>%
   filter(!duplicated(key)) %>%
   select(-key) %>%
   mutate(row = row_number())

#  Var1 Var2 row
#1    1    1   1
#2    2    1   2
#3    3    1   3
#4    2    2   4
#5    3    2   5
#6    3    3   6


text:
Q: RoleProvider IsUserInRole Called Twice I recently noticed that GetRolesForUser() is called twice when I try to access a controller action that uses my custom attribute. I'm new to Forms and trying to fully understand each piece. Is this typical behavior or am I missing something?
Here is my controller:
namespace Forms.Controllers
{
    public class AdminController : Controller
    {
        [SiteAuthorization(Roles = "Admin")]
        public ActionResult AddUser()
        {
            return View();
        }
    }
}

Here is my Authorize Attribute:
namespace Forms.Attributes
{
    public class SiteAuthorization : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
            else if (!Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "~/Views/Shared/Unauthorized.cshtml"
                };
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
    }
}

Here is my custom Role Provider:
namespace Forms.Providers
{
    public class SiteRoleProvider : RoleProvider
    {
        private UserRoleRepo _userRoleRepo { get; }

        public SiteRoleProvider()
        {
            _userRoleRepo = new UserRoleRepo(new SMDMContext());
        }

        // Always called twice (?)
        public override string[] GetRolesForUser(string username)
        {
            return _userRoleRepo.GetUserRolesByUserName(username).ToArray();
        }
    }
}


text:
Q: Watershed using c# or c++ I am trying to convert the Matlab function watershed into C# or C++.
I tried to use this code but CvFindContours returns NULL with this image.
I also tried to use this implementation but I had issues with FilterGrayToGray.
Does anyone knows how I can solve my problems or how I can calculate watershed on my image? Can someone explain me more precisely meyers flood algorithm for watershed?

A: Have you looked at the watershed algorithm provided by OpenCV? Also, here is an example of how to use watershed with OpenCV. Hope that is helpful to you!

A: Although I think the solution given (OpenCV like) is good, you could also search for a different implementation of watershed. Search for Luc Vincent and Pierre Soille "Watersheds in Digital spaces: an efficient algorithm based on immersion simulations".


text:
Q: How to redirect a html page to two other html pages using two buttons? I can connect to another html page by using the following code by using a button click.
<form action="where-you-want-to-go"><input type="submit"></form>

but I have a problem. When there are two buttons on the page how can I redirect them to two different pages by using this code? Or is there any other way to do that?

A: YOU COULD DO something like this
<input type="button" onclick="window.location = 'where-you-want-to-go';">
<input type="button" onclick="window.location = 'where-you-want-to-go';">

A: What do you mean by "redirect"? After clicking submit button the form data is send to action url. If you want you can create two forms:
<form action="action-first"><input type="submit"></form>
<form action="action-second"><input type="submit"></form>

But if you don't want to send data, you can use links to go to the page:
First link
Second link


text:
Q: How to detect change in GPIO input raspberry pi Is there a way to detect to detect change in raspberry pi GPIO without using a infinite loop?
You can detect rise or fall by using this:

GPIO.add_event_detect(channel, GPIO.RISING, callback=my_callback)

But you only can set event detector for either falling or rising at a time. Is there any way to do it without checking the input in a infinite loop?

A: You can use threaded callbacks on event_detect. As per raspberry-gpio-python, you can make use of something like this.
GPIO.add_event_detect(channel, GPIO.RISING, callback=my_callback)
Where event could be GPIO.RISING, GPIO.FALLING or GPIO.BOTH, my_callback is a normal python function which behaves like an ISR which is run in a different thread.
Hope it helps.

A: This link might be helpful raspberry-gpio-python
Basically just use callbacks to do whatever you want at the rising or falling edge instead of polling (what you described)

A: If you get a simple MCP3004 or MCP3008 IC which is a Analog to Digital converter you can do much more with inputs. Here is some sample code to get you started. More info on ADC's here and how to hook them up to your pi
import spidev

#this fucntion can be used to find out the ADC value on ADC 0
def readadc_0(adcnum_0):
    if adcnum_0 > 7 or adcnum_0 < 0:
        return -1
    r_0 = spi_0.xfer2([1, 8 + adcnum_0 << 4, 0])
    adcout_0 = ((r_0[1] & 3) << 8) + r_0[2]
    return adcout_0

reading= readadc_0(0))

depending on the resolution of your ADC you will have to do some calculations to get the reading into terms of voltage


text:
Q: Does a map-only UDF benefit from being Algebraic or Accumulative? In Pig on Hadoop I have a Java UDF being applied to big tuples which just takes 4 fields of the big tuple and (after some nontrivial calculation) returns two new values which I tack onto the big tuple.
There is no reduce phase.

Can this benefit from being made Algebraic, or Accumulative?

In the absence of any grouping, I don't see how it would result in a speed improvement.  And it seems like grouping just to try and get a speedup is a giant leap in the wrong direction.

A: No, I think you are creating a regular EvalFunc. It does not make sense to make it Algebraic or Accumulative.
LOWER or REGEX_EXTRACT are examples for other EvalFunc that do not implement any of the interfaces you mentioned.

A: The Algebraic interface works by utilizing Hadoop's combiner, which is like a mini-reduce phase before the real reduce phase. Therefore, if you are not actually doing any reducing, this interface is irrelevant.
Accumulator, on the other hand, is not necessarily tied to a reduce phase. It is simply a method for processing very large bags in a UDF.  Often such bags are the result of grouping, but this is not necessarily the case. Instead of loading the whole bag at once, Pig will load pieces of it at a time, keeping track of what it needs to produce the final result at the end. I don't know that it's a fit for your case, but it could be used in a map-only situation.
However, you mention that you have a very large tuple. If you really do mean tuple, and not bag, then Accumulator cannot help you.
As a side note, the purpose of Accumulator is not to speed up computation (though this would probably be the result for bags that do fit into memory, but just barely, due to garbage collection). It is to allow you to process bags that otherwise could not be processed at all due to memory constraints. Contrast this with Algebraic, which really is a speed-up mechanism by reducing (ha!) the amount of data that is sent to the reducers and written to disk in the shuffle phase.


text:
Q: How to append new elements to the end of a session in php? I have a Session where I am storing some IDs and I would like to add to the end of that session a string (attach to its own respective id).
Here I have a table with some elements and I have some checkboxes there so when each checkbox is selected I am taking their ids and when posting I am storing those ids to a session:
    <form method="post">
    <?php if (!empty($arr_devices)) { ?>
        <?php foreach ($arr_devices as $device) : ?>

                    <input type="checkbox" name="devices[]" value="<?php echo $device["id"] ?>">
                    <?php echo '' . $device["name"] . ''; ?>

                    <?php echo '' . $device["device_no"] . ''; ?>

                    <?php echo '' . $device["barcode"] . ''; ?>

                            <textarea name="dev_comment" placeholder="Write your comment here" rows="1" cols="50"><?php echo $dev_comment; ?></textarea>

    <?php endforeach; ?>
    <?php } ?>
    <input class="btn" type="submit" name="submit" value="Report">
    <form>

Here is the the way I am storing those IDs:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $_SESSION['devices_id'] = $_POST['devices'];
}

what I would like to do is to add the $dev_comment to that Session. So that when I use that Session I need to have the $dev_comments attached to each respective id. How can I implement that?

A: At first, ensure that $_SESSION['devices_id'] exists and is an array:
if(!isset($_SESSION['devices_id'])) {
    $_SESSION['devices_id'] = [];
}

The, $_POST['devices'] is an array, you can easily merge:
$_SESSION['devices_id'] = array_merge($_SESSION['devices_id'], $_POST['devices']);


text:
Q: How to get the uploaded tracks and its details of a specific user in Sound Cloud using a CLIENT_ID? How to get the uploaded tracks and its details of a specific user in Sound Cloud using a CLIENT_ID.
I had tried to create an APP in sound cloud , but they said it will take a two week to evaluate on my APP request. I just want use this code to get if I would get a CLIENT_ID from the APP after two week. Is that OK ?
$tracks_json = file_get_contents('http://api.soundcloud.com/tracks.json?client_id=Here_My_CLIENT_IDc&limit=50&linked_partitioning=1');
$tracks = json_decode($tracks_json);

A: the CLIENT_ID is something you get when you register an app. Do not misconception it for the USER_ID, that's a code generated when you register a new account on Soundcloud. Everybody has a USER_ID but not everyone has a CLIENT_ID.
You will have to wait more than 2 weeks after you have submitted for an app to get your CLIENT_ID, there's nothing you can do.

A: You can use the /users/:id/tracks endpoint, which will give you the list of tracks for a user. Check out the documentation for the "Users" endpoint, particularly the "Subresources" section beneath.


text:
Q: How to get started with Google Custom Search API? I'm trying to write a Java program that uses Google's Custom Search API to retrieve search results. As a first-time user of API's, though, the documentation on the website is extremely confusing - does one retrieve results by connecting to the google api link like:
Google Custom Search API
(Then once you've connected, how do you display the results? Using BufferedReader gives me a 403 error)
...or do you need to download the library and use their GoogleCustomSearch class like:
java google custom search api
? I have the googleux-customsearch jar (from http://blog.lux-medien.com/2011/08/google-custom-search-java-implementation/) and integrated it into Eclipse but I'm not quite sure what import statements I should be using to use these classes (again, first-time user).
I'm also not quite sure the distinction between the Java client, REST API, and JSON API (are they all the same thing??) as detailed on the Google Custom Search API website...can anyone please clarify? Thanks!

A: It is true the docs are quite confusing at the moment.
There are 2 version of Google Custom Search: free (CSE - Custom Search Engine) and paid (GSS - Google site Search).
When using the free one you have 2 options:
+ implement javascript widget with search box and placeholder for results:
https://developers.google.com/custom-search/docs/element - this is a standard way of implementing CSE
+ use JSON REST api - https://developers.google.com/custom-search/v1/overview - this is experimental feature and has a limited free quota (100 queries as of now)
When using GSS (paid one), you can still use javascript widget, but additionally you get access to XML results: https://developers.google.com/custom-search/docs/snippets#presentation_layer
Ususally first you create a search engine in the Control Panel: http://www.google.com/cse and then you use either js widget to access it or JSON (free but low quota) or XML (paid) feeds via HTTP GET requests from your website.


text:
Q: Использование Getters/Setters внутри класса Читал документацию на русском про использование Getters/Setters в Android. Их необходимо избегать внутри одного класса. Пример плохой практики:
class A {
    int a;
    int getA() { return a;}
    void test() {
        int x = getA();
    }
}

Правильно ли я понял? В других случаях выходит их использовать желательно(Например если обращаемся к полю вне класса)

A: Да вы правильно поняли.

Например если обращаемся к полю вне класса

Я бы перефразировал это по другому:
Геттеры и сетеры желательно использовать вместо прямого обращения других классов к полям данного.


text:
Q: How to add before_widget 2 div
register_sidebar( array(
        'name'          => __( 'Main Widget Area', 'predator' ),
        'id'            => 'sidebar-1',
        'description'   => __( 'Appears in the footer section of the site.', 'predator' ),
        'before_widget' => '

',
        'after_widget'  => '

',
        'before_title'  => '
',
        'after_title'   => '
',
    ) );

before_widget how to add 2 div? now combine all div in one div.
Or
another way like sidebar first widget before add col-md-6 and others col-md-3

A: Using javascript you can apply div whereever you want,just apply this script in your wp footer, i hope it will help you.

$(document).ready(function(){

    $(".widget-1").append("");

    $(".widget-1").append("");

})


text:
Q: IIS intermittently redirect to wrong URL I am running IIS 8 and I setup a quick URL redirect from a virtual folder. The url resembles something like home.cginet/applicaton/ and redirects to home.cginet/applicaton/tools/.
What happens randomly is when refreshing my page at the url home.cginet/applicaton/ sometimes it will come back with home.cginet/applicaton/tools/tools/tools/. In order to fix this I have to refresh 3-4 times for the page to kick in.
Just wondering is anyone has seen this type of behavior with their site?
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpRedirect enabled="true" destination="/Directory/staff/" exactDestination="false" childOnly="true" />
    </system.webServer>
</configuration>


text:
Q: How to send notification only when an item is modified - SQL Server I am making use of the "When an item is modified (V2)" action of SQL Server, this to determine if an item was modified in the table and then send a notification.
There are two situations where I want mail to be sent when you modify a table item in SQL Server.
One of the situations in which the flow is executed is when the value of the "Estado" column that is of type boolean changes to "false", after the flow is executed the notification is sent.
Another situation in which the flow is executed is when the modification is made to any field in the table, that is, any modification that is made to a record, whether it is a change in a text entry, name change, etc., after this a notification will also be sent.
I am presenting a problem and it is when the second situation is executed, in which I make a modification to any field and where the record has as "Estado" equal to "false", it is here where the two conditions are being executed and the notification is being sent for the first situation that I mention and for the second.
I want to correct in my flow is that when I make the modification to any field in a record where the "Estado" column is equal to "false" only the notification of this situation is sent.
The following is the flow I am using where I have a parallel branch with the two conditions mentioned:

Someone has an idea of what change I should make in my flow so that the notification was only sent in case of making a modification to any field regardless of whether it has as "Estado" equal to "false", I am having a problem because when I make a modification I am being sent the notification in both situations.


text:
Q: Disable input validation for input type=number I have a numeric input tag in a form element:
<form novalidate="">
      <input type="number" data-role="none" autocapitalize="off" autocorrect="off" autocomplete="off" placeholder="Quantity" class="quantityInput" />
</form>

When user types in any non-numeric value, the browser validates it and removes the whole text before submit call.
From the suggestions of other answers I tried using novalidate and novalidate="novalidate" attributes on the form. I also tried to tap invalid events. But nothing seems to work. The browser just removes the whole text if it is non-numeric before doing the submit call.
The reason to use input type="number" is that I need a quantity field in which user types something like 10 grams or 23 pcs etc. So by setting the input type="number", iOS shows the numeric version of the keyboard first.
How do I disable browser validation for input types of number?

A: The modern answer (as of 2020) is to use inputmode:
    <input type="text" inputmode="email">
    <input type="text" inputmode="tel">


text:
Q: Grothendieck group of a symmetric monoidal category is a lambda ring? I understand that taking the Grothendieck group of a braided monoidal (abelian) category gives us a commutative ring and that taking that of a symmetric monoidal (abelian) category gives us a $\lambda$-ring.  Now, I have simply seen this (latter) fact stated on the internet by reputable mathematicians, but I have not been able to find a reference explaining how one gets all that extra structure ($\lambda$-rings seem quite complicated!) from one extra property that symmetric monoidal categories have.
I was wondering if anybody could point me in the right direction or shed some light on the details?
Thanks!

A: The $\lambda$-structure is given by taking exterior powers. This is the main motivation I know for defining $\lambda$-rings in the first place. (You need an action of $S_n$ on an $n^{th}$ tensor power $V^{\otimes n}$ to define the exterior power, which is what being symmetric monoidal gets you; in the braided monoidal case you only get an action of $B_n$.)


text:
Q: Tangent line of a circle as a limit of secant lines with Tikz I was trying to draw an illustration for a tangent line at a point on a circle as a limit of secant lines.

Here is my MWE
\documentclass{standalone}
\usepackage{pgf,tikz}
\usetikzlibrary{arrows}
\pagestyle{empty}
\begin{document}
\begin{tikzpicture}
\clip(-2.0,-1.7179963269168166) rectangle (3.4,3.0543741726287474);
\draw(0.,0.) circle (1.4142135623730951cm);
\draw [color=blue,domain=-1.3:3.0] plot(\x,{(--2.-1.*\x)/1.});
\draw [domain=-1.3:3.0] plot(\x,{(-0.8--0.3*\x)/-0.47});
\draw [domain=-1.3:3.0] plot(\x,{(-1.15--0.4*\x)/-0.76});
\draw [domain=-1.3:3.0] plot(\x,{(-1.47--0.4*\x)/-1.05});
\draw [->] (-2.,0.) -- (3.3,0.);
\draw [->] (0.,-1.6) -- (0.,3.);
\begin{scriptsize}
\draw [color=blue,fill=blue] (1.,1.) circle (1.5pt);
\end{scriptsize}
\draw (1.1,1.43) node[anchor=north west] {$P$};
\end{tikzpicture}
\end{document}

Anything to make the diagram better is  appreciated.

A: \documentclass[tikz]{standalone}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\draw[-latex] (0,-2.5) -- (0,4);
\draw[-latex] (-2.5,0) -- (4,0);
\coordinate (a) at (-0.5,3);
\node[circle,draw,minimum size=4cm] (c) at (0,0) {};
\draw[blue,thick] (a) -- (tangent cs:node=c,point={(a)},solution=2) coordinate[label={45:$P$}](p) -- ($(a)!2!(p)$);
\foreach \x in {1,...,5}{\draw (-0.5,3-\x*0.2) coordinate(@) -- ($(@)!2!(p)$);}
\end{tikzpicture}
\end{document}

A: Trying to adjust the most to the image provided

\documentclass[border=4mm]{standalone}
\usepackage{amsmath}
\usepackage{pgfplots}
  \usetikzlibrary{arrows,calc,decorations.pathreplacing}
  \pgfplotsset{compat=1.15}

\begin{document}
\scriptsize

\begin{tikzpicture}[%
        decoration = {brace,
        amplitude=6pt}]

\tikzset{arrowheads/.style={<->, >=stealth}}
\tikzset{ind arrow/.style={->, blue, bend right=30, opacity=0.4}}
\tikzstyle{secant} = [%
        gray, thin,
        arrowheads,
        domain=-1.5:3]

\draw [thick, gray, decorate, transform canvas={xshift = -0.3em}]
    (-1.5,1) -- node [left=6pt]
    {\rotatebox[origin=c]{90}{\text{secants}}} (-1.5,3.2);

\draw [->] (-2,0) -- (3.5,0) node [right] {$x$};
\draw [->] (0,-2) -- (0,3.5) node [above] {$y$};
\draw node at (0,0) [below left] {$O$} circle (1.4142135623730951cm);
\draw [%
  thick,
  arrowheads,
  color=blue,
  domain = -1.5:3.0] plot(\x, {-1*\x+2});

\foreach \i in {1.1,1.26,1.48,1.8}
{
\draw [secant] plot (\x,{(1-\i)*\x+\i});
}

\draw [color=blue, fill=blue] (1,1) circle (1pt) node (T){};
\node (P) [blue, above right of=T, align=center] {Point of \\ Tangency $P$};
\node (Tang) at (1,3) [blue] {Tangent};

\draw [ind arrow, out=90, in=180] (P.south) to (T.north east);
\draw [ind arrow] (Tang.west) to (-0.5,2.5);

\end{tikzpicture}

\end{document}

A: A PSTricks solution for comparison purpose.
\documentclass[pstricks,border=1cm]{standalone}
\usepackage{pst-plot}
\begin{document}
\begin{pspicture}(-4,-4)(6,6)
    \pscircle[linecolor=blue]{3}
    \pnodes{A}(0,0)(3;60)
    \psaxes[linecolor=gray]{->}(0,0)(-4,-4)(6,6)[$x$,0][$y$,90]
    \foreach \i in {65,70,...,90}{\pcline[nodesepB=-3,linecolor=red]([nodesep=3,angle=\i]{A2}A1)(A1)}
\end{pspicture}
\end{document}


text:
Q: How to set cardinalities in Java field? Let us suppose we have the following class:
public class MyClass{
    List<String> list;

    void method() {
    }
}

Each object of this class has a list of strings, but what if we want to set the cardinality? For example, I want to force this class to have at least 2 strings in that list.
Is there a general pattern to represent the cardinalities on fields?

A: You simply need to make sure that there are at least 2 elements in list, by some means. There is no standard or simple way of doing this.
This is known as an invariant of the class. It is your responsibility as the person who writes the class to ensure that this invariant is preserved at all times. In particular:

*

*You need to document the invariant that there are at least 2 elements in the list.

*You need to ensure that the list contains at least two elements by the time the constructor finishes. The instance should be "valid" (in the sense that its documented invariant are true) when the constructor finishes.

*You need to ensure that all code within the class honors the invariant when it manipulates the list - you are allowed to temporarily make it invalid, but you must ensure that it is not possible to observe your instance in an invalid state.
In the single-threaded cases, this simply means that the invariant must be true once the public method returns (note that this includes if an exception occurs); but if your code is designed to be used in a multithreaded way, you must also ensure that no thread can ever see your instance in a state where the invariant is false (e.g. you may need synchronized blocks, or ensure that updates are atomic).

*You need to ensure that subclasses of your class are unable to make the invariant false; or document clearly that it is the responsibility of people writing subclasses to ensure that the invariant remains true.
There is a great item in Effective Java 2nd Ed about this: "Design and document for inheritance or else prohibit it".

*You need to ensure that nothing outside your class is able to access the reference to the list. For example, your code makes the list visible to other classes in the same package - any of these classes could call theInstance.list.clear(), and invalidate your invariant.
It's pretty hard to prevent this absolutely - for example, it could be possible for malicious actors to invalidate the invariant using reflection. You can prevent this, but it's a question of weighing the effort of identifying and blocking such methods vs the actual cost of the invariant becoming false (this strongly depends upon how this class is used).
By far the easiest way to enforce an invariant is on an immutable class. If it's not possible to change the observable state of an instance, it's not possible to invalidate the invariant. Then, all you need to worry about is a) making sure that the class is immutable; b) making sure that the invariant is true once the constructor returns. All of the other points above then simply fall away.

A:
Is there a general pattern to represent the cardinalities on fields?

Obviously, you can represent the cardinalities using integer fields, either in the objects themselves, or at the meta level.  But that's not much help if you cannot enforce them.
There is no general pattern for that.  @Andy Turner's answer provides a good summary of the alternatives on enforcement of cardinalities.  I just want to add a couple of points:

*

*Attempting to enforce the cardinality constraints via static typing is unlikely to work.  The Java type system is not rich enough to do this in a pleasant way1.

*Construction of objects that have fields that have minimum cardinalities can be tricky, especially if there are potentially circularities involving those fields.
One way to deal with construction is to separate the lifecycle of the objects into a "construction" phase and a "completed" phase. During the construction phase, the constraints are relaxed, to allow the construction to be performed in stages.  At some point, a "completed" switch is "flipped".  At that point 1) the cardinality constraints are checked, and 2) the behavior of mutating operations is changed to prevent changes that would violate cardinality.
This can be implemented using public constructors and a public method to "flip the switch".  Alternatively, you can implement this using the builder pattern; e.g.

*

*make the constructors private

*use alternative private means to side-step the cardinalities while building

*check the cardinalities and flip the switch (it one is needed) in the build() method.

Another approach is to allow fields to be below cardinality, but only allow items to be added to the fields when they are in that state.  In other words, this is the "flip the switch" approach without an explicit switch.  The downside is that a client needs to test if the cardinality constraint is in force yet; i.e. the constraint is weak.

1 - In theory, you could implement a ListOfTwoOrMore interface, etcetera, but that would bring a raft of new problems.

A: One way to do that is use a different type for the field. Now it has type List<String> which is a collection that can contain 0 or more elements. You can change it to a type which represents a list that contains 2 or more elements.

A: You could use var-args in constructor.
public MyClass(String s1, String s2, String... rest){
}


text:
Q: Is there a case missing in §8.5 p17 (semantics of initializers) of N3797? For the aggregate
struct S{int i, j;};

the declarations S s({1, 2}); and S s({1}); perform direct-initialization according to N3797 §8.5 p16:

The initialization that occurs in the forms
T x(a);
T x{a};

as well as in new expressions (5.3.4), static_cast expressions (5.2.9), functional notation type conversions (5.2.3), and base and member initializers (12.6.2) is called direct-initialization.

But §8.5 p17 doesn't seem to characterize them:

The semantics of initializers are as follows. The destination type is the type of the object or reference being initialized and the source type is the type of the initializer expression. If the initializer is not a single (possibly
  parenthesized) expression, the source type is not defined.

*

*If the initializer is a (non-parenthesized) braced-init-list, the object or reference is list-initialized (8.5.4).

*If the destination type is a reference type, see 8.5.3.

*If the destination type is an array of characters, an array of char16_t, an array of char32_t, or an array of wchar_t, and the initializer is a string literal, see 8.5.2.

*If the initializer is (), the object is value-initialized.

*Otherwise, if the destination type is an array, the program is ill-formed.

*If the destination type is a (possibly cv-qualified) class type:

*

*If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.

*Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3). If the conversion cannot be done or is ambiguous, the initialization is ill-formed. The function selected is called with the initializer expression as its argument; if the function is a constructor, the call initializes a temporary of the cv-unqualified
  version of the destination type. The temporary is a prvalue. The result of the call (which is the
  temporary for the constructor case) is then used to direct-initialize, according to the rules above,
  the object that is the destination of the copy-initialization. In certain cases, an implementation
  is permitted to eliminate the copying inherent in this direct-initialization by constructing the
  intermediate result directly into the object being initialized; see 12.2, 12.8.

*Otherwise, if the source type is a (possibly cv-qualified) class type, conversion functions are considered. The applicable conversion functions are enumerated (13.3.1.5), and the best one is chosen through overload resolution (13.3). The user-defined conversion so selected is called to convert the initializer expression into the object being initialized. If the conversion cannot be done or is ambiguous, the initialization is ill-formed.

*Otherwise, the initial value of the object being initialized is the (possibly converted) value of the initializer expression. Standard conversions (Clause 4) will be used, if necessary, to convert the initializer expression to the cv-unqualified version of the destination type; no user-defined conversions are considered. If the conversion cannot be done, the initialization is ill-formed. [Note: An expression of type "cv1 T" can initialize an object of type "cv2 T" independently of the cv-qualifiers cv1 and cv2.
 int a;
 const int b = a;
 int c = b;

— end note ]

The subject declarations, S s({1, 2}); and S s({1});:

*

*are not list-initialization, since each initializer is a parenthesized braced-init-list.

*the destination types are not references

*the destination types are not array of characters, in general.

*the initializers are not ()

*the destination types are not arrays.

A: This case is covered in the Standard: It's §8.5/17 6th bullet (emphasis mine):

If the destination type is a (possibly cv-qualified) class type:

*

*If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.

Explanation: We first note that S is an aggregate (by §8.5.1/1). But an aggregate is also a class and hence has an implicitely declared defaulted copy/move constructor (by §12.8). Both constructors take one argument and hence are viable (by §13.3.2). Their signatures are as usual:
S(const S&) //copy
S(S&&)      //move

Now we have to determine the conversion sequence to convert the initializer-list {1,2} to the parameter types. §13.3.3.1.5/6 states:

Otherwise, if the parameter is a reference, see 13.3.3.1.4. [ Note: The rules in this section will apply for initializing the underlying temporary for the reference. —end note ]

Since the parameter types are references, §13.3.3.1.4/2 applies:

When a parameter of reference type is not bound directly to an argument expression, the conversion sequence is the one required to convert the argument expression to the underlying type of the reference according to 13.3.3.1. Conceptually, this conversion sequence corresponds to copy-initializing a temporary of the underlying type with the argument expression. Any difference in top-level cv-qualification is subsumed by
  the initialization itself and does not constitute a conversion.

Since S is an aggregate, we have to apply §13.3.3.1.5/5 to initialize this temporary object:

Otherwise, if the parameter has an aggregate type which can be initialized from the initializer list according to the rules for aggregate initialization (8.5.1), the implicit conversion sequence is a user-defined conversion sequence with the second standard conversion sequence an identity conversion.

Hence, we finally arrive at aggregate initialization of this temporary object. To determine which of these two constructors is the best viable function one has to consult §13.3.3.2 (which is left to the reader). Since the reference is bound to a temporary object the move constructor will actually be chosen.

A:
The declarations S s({1, 2}); and S s({1}); perform direct-initialization according to N3797 §8.5 p16

Well, yes and no. In the first case, and similarly in the second, an S x-value object is constructed with {1, 2} and then passed to the implicitly-declared copy constructor of the s l-value.
This is not the case §8.5 p16 is discussing, because the initialization is not in the form:
S s(a);
S s{a};

unless the standard consider a to be anything. And even then, it's not part of the rest of the cases  he defines right after (new, static_cast, etc..).

The subject declarations, S s({1, 2}); and S s({1}); are not list-initialization, since each initializer is a parenthesized braced-init-list.

The expressions {1, 2} and {1} are definitely list-initializations of temporary/expiring S objects.


text:
Q: "2"-group cohomology In order to define the cohomology
of a topological group G, we first have to introduce the concept of a classifying space. A classifying space BG is the base space of a principal G bundle EG. The EG is the universal bundle: Any principal G bundle E over a manifold M allows a bundle map into the universal bundle, and any two such morphisms are smoothly homotopic. Given
$$
\gamma:  M \to BG
$$ the induced map of the base manifolds, it is the so-called classifying map.
The topology of the bundle E is completely determined by the homotopy class of the classifying map $\gamma$. That is, the different components of the space Map(M,BG) correspond to the different bundles E over M. It can be shown that up to homotopy BG is uniquely determined by requiring EG to be contractible. That is, any contractible space with a free action of G is a realization of EG. In general, the classifying space BG of a compact group is an infinite-dimensional space.
Attempt 1:
Naively, we can have a generalized statement by modifying the map to a product of Eilenberg–MacLane space:
$$
\gamma:  M \to K(G_1,1) \times  K(G_2,2)
$$
where $G_1$ and $G_2$ are two different groups. The $G_1$ can be non-abelian.

*

*How can we be more precise to state the similar structure, defining a "2"-group cohomology, by generalizing the relation between the "group cohomology" and the "topological cohomology of classifying space"?

*Is it necessary to have $G_2$ be abelian?

Attempt 2

*

*A more general classifying map may be:
$$
\gamma:  M \to BG'
$$
where $BG'$ is the possible fibration
$$1 \to  K(G_2,2)\to  BG' \to  K(G_1,1) \to 1,$$
where we may classify the fibration by Postinikov class $$[a] \in H^d(K(G_1,1), G_2).$$ Is this formulation precise?

*

*How can we be sure that $d=3$ is the only solution and $[a] \in H^d(K(G_1,1), G_2)$ classifies all sensible "2" group cohomology?

A: I am not sure if the following gives the answer you want, but there is a notion of crossed module  $\mathcal M =(\mu: M \to P)$ (due to JHC Whitehead)   where $M,P$ are groups and $P$ acts on $M$ satisfyng two rules, which I won't detail here. These crossed modules classify pointed homotopy $2$-types.  A crossed module $\mathcal M$ has a classifying space $B \mathcal M$. with first and second homotopy groups Coker $\mu$, Ker $\mu $ respectively. Full details are in the book Nonabelian Algebraic Topology.
This book does not contain much on the topological or Lie case.


text: Q: Video Conferência no Navegador preciso desenvolver um sistema de video conferência para rodar em navegadores, até o momento descobri vários provedores de streaming de video, mas não é o que preciso, preciso de qualquer dica sobre o assunto, para que posso me auxiliar a desenvolver uma ferramenta de video conferencia no navegador.


text:
Q: Minimum value of $\frac{4}{4-x^2}+\frac{9}{9-y^2}$ Given $x,y \in (-2,2)$ and $xy=-1$
Minimum value of $$f(x,y)=\frac{4}{4-x^2}+\frac{9}{9-y^2}$$
My try:
Converting the function into single variable we get:
$$g(x)=\frac{4}{4-x^2}+\frac{9x^2}{9x^2-1}$$
$$g(x)=\frac{4}{4-x^2}+1+\frac{1}{9x^2-1}$$
Using Differentiation we get:
$$g'(x)=\frac{8x}{(4-x^2)^2}-\frac{18x}{(9x^2-1)^2}$$
$$g'(x)=2x\left(\frac{4(9x^2-1)^2-9(4-x^2)^2}{(4-x^2)^2(9x^2-1)^2}\right)$$
$$g'(x)=70x\frac{9x^4-4}{(4-x^2)^2(9x^2-1)^2}=0$$
So the critical points are:
$x=0, x=\pm \sqrt{\frac{2}{3}}$
But $x \ne 0$ since $xy=-1$
$$g'(x)=70x \frac{(3x^2-2)(3x^2+2)}{(4-x^2)^2(9x^2-1)^2}$$
By using derivative test we get Minimum occurs when $x=\pm \sqrt{\frac{2}{3}}$
Hence $$x^2=\frac{2}{3}, y^2=\frac{3}{2}$$
Min value is $$\frac{4}{4-\frac{2}{3}}+\frac{9}{9-\frac{3}{2}}=\frac{12}{5}$$
Is there any other approach?

A: From "harmonic mean $\le$ arithmetic mean" one gets
$$
\frac{2}{f(x, y)} \le \frac12 \left(\frac{4-x^2}{4}+ \frac{9-y^2}{9} \right)
= \frac 12 \left(2- \frac{x^2}{4} - \frac{y^2}{9} \right)
$$
and from "arithmetic mean $\ge$ geometric mean"
$$
  \frac{x^2}{4} + \frac{y^2}{9}\ge 2 \frac{|xy|}{6} = \frac 13
$$
so that
$$
f(x, y) \ge \frac{4}{2-\frac 13} = \frac{12}{5} \, .
$$
In both estimates equality holds if $\frac{x^2}{4} = \frac{y^2}{9} \iff x^2=\frac{2}{3}, y^2=\frac{3}{2},$ i.e. equality is attained the two points
$$
  ( \sqrt \frac 23, -\sqrt \frac 32) \quad \text{and} \quad
  ( -\sqrt \frac 23, \sqrt \frac 32)
$$
which are both in the given domain $(-2, 2) \times (-2, 2)$ of $f$.

A: Using $xy = -1$, we can put the fractions over a common denominator as
$${4\over{4 - x^2}} + {9\over{9 - y^2}} = {{72 - 9x^2 - 4y^2}\over{37 - 9x^2 - 4y^2}} = 1 + {35\over{37 - (9x^2 + 4y^2)}}$$
So we need to minimize $9x^2 + 4y^2$. Since $9x^2 \times 4y^2$ is constant, the minimum occurs when $9x^2 = 4y^2$, i.e. $9x^2 = 4/x^2$, which gives the same result as you found.

A: With the change of variable $t=x^2$, and differentiating the logarithm of the function, things should be a bit easier:
$$h(t)=\frac4{4-t}+\frac{9t}{9t-1},t\in\left(\frac14,4\right)$$
Then
$$h(t)=\frac{-9t^2+72t-4}{(4-t)(9t-1)}$$
$$\log h(t)=\log(-9t^2+72t-4)-\log(4-t)-\log(9t-1)$$
$$(\log h(t))'=\frac{-18t+72}{-9t^2+72t-4}+\frac1{4-t}-\frac9{9t-1}=\frac{315t^2-140}{\text{Irrelevant}}$$
This is $0$ for $t=\frac23$

A: From $xy=-1$
$$ S = \frac{4}{4-x^2} + \frac{9}{9-y^2} = 1 + \frac{35}{25 - \left(3x - \frac{2}{x}\right)^2}\geq \frac{12}{5}$$
Equality hold when $$3x=\frac{2}{x}$$


text:
Q: insertar imagen en SQL campo IMAGE con Java Quiero guardar mi imagen en una base de datos en SQL en un campo llamado fotoEmpleado de tipo IMAGE, hasta ahí todo bien, pues se me guarda en BYTES

El problema es a la hora de leerla, quiero mostrarla en un Label en mi formulario, tengo entendido que es obtener ese array de BYTES y convertirlo a imagen pero me manda un error java.lang.NullPointerException y no se como leerla. les dejo mis clases y métodos que utilizo (MVC):
Método que hace la consulta y recibe como parametro el idEmpleado:
public static String getImagenEmpleado(int idEmpleado) {

    String consulta = "SELECT fotoEmpleado FROM Empleado WHERE idEmpleado="+idEmpleado;
    return consulta;
}

Método que hace la conexión a la BD y ejecuta la consulta y convierte los BYTES a IMAGE:
public Image obtenerImagen(int idEmpleado) throws Exception {
    Image foto = null;
    //Creamos un objeto de conexion:
    ConexionSQL conexion = new ConexionSQL();
    //Declaramos el ResultSet:
    ResultSet rs = null;
    Statement stmt = null;
    //Establecemos la conexion con la BD:
    ConexionSQL.conectar();

    stmt = ConexionSQL.con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    rs = stmt.executeQuery(CommandsEmpleado.getImagenEmpleado(idEmpleado));

    //Iteramos sobre cada registro devuelto:
    if (rs.next()) {//si no encuentra la imagen
        Blob blob = rs.getBlob("fotoEmpleado");
        foto = javax.imageio.ImageIO.read(blob.getBinaryStream());
    }

    //Cerramos el ResultSet:
    rs.close();
    stmt.close();

    //Cerramos la conexion:
    conexion.desconectar();

    //Devolvemos la foto del Empleado
    return foto;
}

y en la vista le mando el parámetro idEmpleado y le mando la imagen al label:
ImageIcon image = new ImageIcon(controladorEmpleado.obtenerImagen(idEmpleado));

                if (image.getIconHeight() > 342 || image.getIconWidth() > 230) {
                    ImageIcon imageScalada = new ImageIcon(image.getImage().getScaledInstance(90, 100, 100));
                    lblFotoEmpleado.setIcon(imageScalada);
                } else {
                    lblFotoEmpleado.setIcon(image);
                }
                ;
            } catch (Exception ex) {
                Logger.getLogger(PanelEmpleados.class.getName()).log(Level.SEVERE, null, ex);
        }

¿o alguien sabe otra manera de guardar y mostrar la imagen en SQL y Java?

A: Creo que no estás nunca dando valor a la variable fotoanalizando este fragmento de código:
//Iteramos sobre cada registro devuelto:
if (!rs.next()) {//si no encuentra la imagen
    Blob blob = rs.getBlob("fotoEmpleado");
    foto = javax.imageio.ImageIO.read(blob.getBinaryStream());
}

Se deduce que solo da valor a foto si el cursos hubiera alcanzado su último puntero sobre el ResultSet. Eso no nunca va a ocurrir siempre y cuando existan valores en el ResultSet. Así pues, deberías hacer los contrario:
// Se valida que existen valores.
if (rs.next()) { <-- // En caso de que existan valores
    Blob blob = rs.getBlob("fotoEmpleado");
    foto = javax.imageio.ImageIO.read(blob.getBinaryStream());
}

Te dejo un enlace con la documentación de next();

A: Tal vez deberias usar BufferedImage en vez de Image.
BufferedImage foto = javax.imageio.ImageIO.read(blob.getBinaryStream());

Image como tal es una clase abstracta, mientras que BufferedImage extiende de ella y es la que he visto que es implementada para este tipo de situaciones.
EDIT: Estuve haciendo varias pruebas con partes de tu código y no me salio el error del null, te muestro la manera en la que lo hice para cargar la imagen de la base de datos.
 public Image obtenerImagen(int idEmpleado) throws Exception {
    BufferedImage foto = null;
    //Declaramos el ResultSet:
    ResultSet rs = null;
    Statement stmt = null;
    //Establecemos la conexion con la BD:
    stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    rs = stmt.executeQuery("SELECT image FROM imagetest LIMIT 1;");
    //Iteramos sobre cada registro devuelto:
    if (rs.next()) {//si no encuentra la imagen
        Blob blob = rs.getBlob("image");
        foto = ImageIO.read(blob.getBinaryStream());
    }
    //Cerramos el ResultSet:
    rs.close();
    stmt.close();
    //Devolvemos la foto del Empleado
    return foto;
}

Como te puedes dar cuenta, es basicamente tu mismo codigo, solo que le cambie el Image por BufferedImage y otros detalles para traer la información de mi base de datos (como mi propia conexion, el hecho de que no necesito el id del empleado, etc), pero del resto es lo mismo.
Con respecto a la parte de visualización, tu codigo sirvio basicamente igual, solo lo adapte para que me funcionara a mi.
ImageIcon image = new ImageIcon(imageManager.obtenerImagen(1));
    JLabel lblFotoEmpleado = new JLabel();
    Frame frame = new Frame("Image Example");
    frame.setSize(400,400);
    lblFotoEmpleado.setSize(400,400);
    lblFotoEmpleado.setVisible(true);

    if (image.getIconHeight() > 342 || image.getIconWidth() > 230) {
        ImageIcon imageScalada = new ImageIcon(image.getImage().getScaledInstance(90, 100, 100));
        lblFotoEmpleado.setIcon(imageScalada);
    } else {
        lblFotoEmpleado.setIcon(image);
    }

    frame.add(lblFotoEmpleado);
    frame.setVisible(true);
}

Lo único que se me ocurre que tengamos de diferente, es la manera en la que se guarda la imagen en la base de datos. Yo pues use un Longblob, el cual supongo que tu tambien y al guardalo en la base de datos me muestra lo siguiente, a comparación tuya que muestra los Bytes.

Si algo, el codigo que utilice para guardar las imagenes fue el siguiente.
 public void saveImage(String ruta) throws SQLException, FileNotFoundException
{
    String sql = "INSERT INTO imagetest(image) VALUES (?)";
    //Creamos una cadena para después prepararla
    PreparedStatement stmt = connection.prepareStatement(sql);
    File image = new File(ruta);
    //ruta puede ser: "/home/cmop/Desktop/1.jpg"
    FileInputStream fis = new FileInputStream(image);
    //Lo convertimos en un Stream
    stmt.setBinaryStream(1, fis, (int) image.length());
    //Asignamos el Stream al Statement
    stmt.execute();
}

Lamento no poder ayudarte más, la verdad aparte de lo que te comente, no se me ocurre otra causa de error.


text:
Q: R: How to subtract each observation from a number I have a dataframe (SCWB) from 2001 with 5500 observations (people).
The variable YRBIRTH captures the individuals' year of birth.
I would like to create a new variable called AGE -->  "AGE = 2001 - YRBIRTH"
I can't seem to figure out how to code this variable into R - so far I have:
SCWB$AGE <- lapply(SCWB, transform, YRBIRTH = 2001 - YRBIRTH)

And an error message:

Error: unexpected '=' in "SCWB$YrBrth <- lapply(transform, SCWB$YRBIRTH ="

Any ideas on how to fix this?
Thank you!

A: If 'SCWB' is a data.frame, we can directly apply transform on the column 'YRBIRTH' instead of a loop with lapply
SCWB <- transform(SCWB, YRBIRTH = 2001 - YRBIRTH)


text:
Q: Antisamy or Content Security Policy or both to prevent XSS attack Recently I studied a lot related to XSS attacks. I was searching for prevention techniques of XSS attack.
I came across a library called Antisamy, suggested by OWASP. AntiSamy is an HTML, CSS and JavaScript filter for Java that sanitizes user input based on a policy file. AntiSamy is not an HTML, CSS and JavaScript validator. It is merely a way to make sure HTML, CSS and JavaScript input strictly follows rules defined by a policy file
Also I have read about a HTTP response header called Content Security Policy (CSP). It allows you to create a whitelist of sources of trusted content, and instructs the browser to only execute or render resources from those sources.
So should I use only Antisamy or CSP or using both will be beneficial?
Thank you in advance.

A: When it comes to security, the answer is always both/all/everything so long as you have the time.
They are both beneficial in their own right.
I'd argue CSP is more beneficial long term, but I'm highly biased.
EDIT based on completely valid comment
CSP is not supported by all user agents, whereas anti-sammy is user-agent agnostic.

A: There have been exploits found to AntiSamy in the past and there will probably be in the future as XSS attacks get cleverer (check out this video on mXSS).
It would be advisable to use both. AntiSamy will be effective for browsers that do not support CSP. CSP will be effective for current and future supported browsers.


text:
Q: How to add custom label in static resource JS alert How to add custom label in static resource JS alert , i want to create a alert error message using a custom label in static resources

A: If we need to access labels in JS file which is saved in static resource:
There are two way to do the same requiremnt:

*

*Pass label as a parameter or pass-through attributes to JS function.

*JavaScript bridging component:
2.a) loads before your script, like so:
<script>
    window.$Label = window.$Label || {};
    $Label.MyError = '{!JSENCODE($Label.MyError)}';
    $Label.MyPrompt = '{!JSENCODE($Label.MyPrompt)}';
    $Label.MyMessage = '{!JSENCODE($Label.MyMessage)}';
</script>

2.b) Now in your javascript (in a static resource) use the variables just as
if they were VF without {!}
function errorHandler() {
    console.log($Label.MyError);
    alert($Label.MyMessage);
}