Different Results When Printing Element of Integer Pointer Different Ways

Question: I have an integer array: int* b whose values are set for elements 0 through 7. When I print out each element individually, I get the correct elements. However, when I use a for loop, I am getting different results. Any idea why?
Here's the code:
//toBinary(int x) returns an int pointer whose value is an array of size 8: int ret[8]
int* b = toBinary(55);

//Print method 1 (Individual printout)
cout << b[0] << b[1] << b[2] << b[3] << b[4] << b[5] << b[6] << b[7] << endl;

//Print method 2 (for loop)
for (int t = 0; t < 8; t++)
    cout  << b[t];
cout << endl;

The result of the first print out is the following: 00110111
This is the correct printout.
When I print using the second technique, it says, -858993460-85899346051202679591765470927361022170810222364 This is the wrong printout.
Why am I getting two different printouts?
Here is the toBinary method:
int* toBinary(int i) {

    int byte[8];
    for (int bit = 7; bit >= 0; bit--) {
        if (i - pow(2, bit) >= 0) {
            byte[7-bit] = 1;
            i -= pow(2, bit);
        }
        else
            byte[7-bit] = 0;

    }
    return byte;
}

Comment: Can you construct a [minimal test-case](http://stackoverflow.com/help/mcve)?
Comment: How is `toBinary` implemented?
Comment: I updated with the toBinary method
Answer: The toBinary method returns the address of a local variable. byte will be deleted when the function exits.
The fact that your first output works seems to be just luck because the memory segment wasn't used by anything else at that point.
To fix this, you'll either have to allocate the array on the heap manually or you use one of the containers (std::array, std::vector).
Comment: @Drone6251 UB means anything is possible; nothing is guaranteed.
Comment: Thus undefined behaviour!
Comment: Why can I print each element individually, though?
Comment: Oh, gotcha! Thanks for the help! I'll accept the answer in 8 minutes once the timer expires.
Answer: Other answers already touched on what the problem is here, I want to emphasize that your code is anti-modern C++, you should really be using std::vector (or std::array if you have C++11) which will solve all of these things instantly:
#include <vector>

std::vector<int> toBinary(int i) {

    std::vector<int> byte(8);
    for (int bit = 7; bit >= 0; bit--) {
        if (i - pow(2, bit) >= 0) {
            byte[7-bit] = 1;
            i -= pow(2, bit);
        }
        else
            byte[7-bit] = 0;

    }
    return byte;
}

And then..
std::vector<int> b = toBinary(55);

//Print method 1 (Individual printout)
cout << b[0] << b[1] << b[2] << b[3] << b[4] << b[5] << b[6] << b[7] << endl;

//Print method 2 (for loop)
for (int t = 0; t < 8; t++)
    cout  << b[t];
cout << endl;

Comment: Thanks for the answer! I am used to Java, so I am still learning these different nuances.
Answer: Through toBinary you are returning a local variable that gets freed once the function call ends. You must allocate memory for the array using heap. And then return that pointer and collect it in the variable b.
Comment: Thanks for the help!


How can I perform one transaction per input row?

Question: I have a dataflow that has an oledb data source.  I then have a script component that performs three web service calls, this has two outputs that are (in effect) synchronous to the input row (one output row per input row), and one output that is asynchronous (outputs many rows for each input row).  Each output goes to a sql update command.  There is also an error log output (also asynch).
I wish to wrap the outputs in a transaction somehow, so that for each input row, if the row is not completely processed and updated, then none of the updates for that input row succeed.
From what I can tell, the way this works is that the scripts process each input row and output everything to a buffer before moving on to the update commands.  I want, instead to perform all updates on a per-row basis, committing changes when each input row has been processed and updated.
How can I structure my dataflow to achieve this?
I'm thinking perhaps of executing the source, then running the records through a foreach container, but i'm unsure of how I would chain multiple DataFlows together that way via a ForEach container.
Answer: I suspect the only way is to put everything, including the updates, in a single script. SSIS does not expose enough of its dataflow buffering strategy to give you that fine a level of control. In fact, it goes to great lengths to speed things up within a pipeline, which is just the opposite of the throttling strategy you're looking for. (See Data Flow Performance Features on MSDN for a discussion of what tuning features are available.)
Alternatively, you could build a completely custom destination pipeline component. Given how painful debugging script components is in SSIS 2008, that might even be a preferable approach.
Comment: Thanks for the info, however, I decided to change my strategy and moved everything into one script with several outputs.  I completely changed my question, and I think you were answering my previous question.
Answer: The solution here is that I create a Data Flow task which selects the users into a recordset, which is placed in a variable.
I then use a For Each container to read the recordset, and put the username in a variable.  In side the For Each, I have a dataflow that has an OLEDB source that uses the variable as a parameter to select the users again (this results in a lookup for each iteration of the dataset, but that's ok).
This feeds into my script.
Additionally, I place Execute SQL Tasks before and after the package in the for each loop so I don't have to use DTC transactions, and can process each input row as a separate transaction.


Comparing boolean values

Question: I am facing an issue while comparing boolean values, I want the loop to enter inside the block but its not entering the block.
else if (!(keyCompare.contains(compareKey)) || (save == true)) {
 //do something
}

here !(keyCompare.contains(compareKey) will return false. I am seeing if the vector keyCompare does not have compareKey or if save is true then enter if loop, but its not.
Where I am doing wrong?
Comment: I don't see any errors here, there must be something else. If save is true, it will enter your if-block. Btw, don't write `if (save == true)`, just write `if(save)`
Comment: what is your first if condition? Are you sure it's not entering the previous branch?
Comment: Could you please show the whole `if-else` statement
Comment: More readable: `else if (!keyCompare.contains(compareKey) || save) {`
Comment: just a note, `contains()` requires `equals()` method implemented correctly, so if compareKey is instance of object you created, that could be the problem...
Comment: An if is not a loop. Post more of your code so that someone can try and help you out.
Answer: There are three possibilities:

An if or else if block above this one is executing.
An exception is being thrown by contains.
You're incorrect and both of those conditions are false.

A debugger will tell you exactly which possibility is correct.  There's not really any need for discussion here - those are literally the only three possibilities.
Answer: Suppose you have a class as follows:
static class Contents {
  private String contents;
  public Contents(String contents) {
    this.contents = contents;
  }
}

Writing the following code:
Vector<Contents> v = new Vector<>();
v.add(new Contents("a"));
System.out.println("Contains a: "+v.contains(new Contents("a")));

Would yield the following output:
Contains a: false

However adding the equals method to the Contents class as follows:
public boolean equals(Object obj) {
  return Objects.equals(this.contents, ((Contents)obj).contents);
}

Yields suddenly the following result:
Contains a: true

A better implementation might have looked as follows:
@Override
public boolean equals(Object obj) {
  if (this == obj) return true;
  if (obj == null) return false;
  if (getClass() != obj.getClass())return false;
  final Contents other = (Contents) obj;
  if (!Objects.equals(this.contents, other.contents))return false;
  return true;
}

Comparing boolean values


How to align facet_wrap

Question: I am having a problem aligning my graphics using facet_wrap(). I have multiple years of data but I am subsetting to display only two years. For some unknown reason the upper plot is shifted to the left and the lower plot is shifted to the right (See attached snapshot). My dataset is very large to post here so it can be downloaded from the link below if someone is willing to help me to align the plots. https://login.filesanywhere.com/fs/v.aspx?v=8c6b678a5c61707ab0ae
 Here is the snapshot:

This is what I have tried:
library(writexl)
library(readxl)
library(tidyverse)
library(lubridate)
mydat <- read_excel("all.xlsx", sheet="Sheet1")

#subset 2 years
start <- 1998
end <- 1999
a <- dplyr::filter(mydat, year %in% start:end)

  ggplot(a,aes(date,Salinity,color=Box)) +
                  geom_line(size=.8) +
                  theme(legend.position = 'none')  +
       scale_x_date(date_breaks = "1 month",date_labels = "%b",expand=c(0,0.5)) +
                              labs(x="",y= "test") +
                                 facet_wrap(~year,ncol=1)

I will be subsetting up to 10 years in the future. I am also wondering what's  the best to subset multiple years using dplyr or base. Thanks beforehand.
I get the following error after trying your suggestion:
subset 2 years
start <- 1998
end <- 2000

a <- mydat %>%
    dplyr::filter(year %in% start:end) %>% # if you need to subset the years
    mutate(date = as.Date(gsub("\\d{4}", "0000", date)))

    ggplot(a,aes(date, Salinity,color=Box)) +
    geom_line(size=.8) +
    scale_x_date(date_breaks = "1 month",date_labels = "%b",expand=c(0,0.5)) +
    labs(x="",y= "test") +
    facet_wrap(~year,ncol=1,scales="free_x")

   Error in charToDate(x) :
  character string is not in a standard unambiguous format

Maybe 'date' doesn't like the zeros?
Question: Does it work for you using the dataset from the link?
Comment: It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions.
Comment: That's probably because X-axis is showing monthly values of two different years. You can try changing the scale of X-axis in the facets: `facet_wrap(~ year, ncol = 1, scales = "free_x")`
Comment: Please do not provide unnecessarily large files or data structures, especially not one that requires us to download from a random place. For all we know, it may contain a virus. Please keep it small and simple enough to use. That said, @Zaw's suggestion works, but if one year contains data from fewer months than another year, the scale would be off. An alternative is to change the dates so that they all have the same year within the `date`, while `year` (which you don't change) is retained the `facet_wrap`.
Comment: Understood. I couldn't make a smaller subset to show my point. I tried with about 300 records but nothing was being displayed, hence, I provided a link to the data. On a different note, Thanks to @Zaw for the suggestion. I am trying facet_grid() instead of facet_wrap but the scales ignore the `scales= "free" or scales="free_y"` arguments. Any idea why?
Comment: Just change the year "0000" to "0001" and it will work.
Answer: The plot from the OP appears shifted because the date column in the data contains separate years. Thus, the ggplot function is displaying those dates chronologically along the x-axis, spanning years.
A solution is to change the year in all the dates in the date column to be the same (e.g., "1111"), while the actual year information is retained in the year column. The years in the year column is used to stratify the plot.
# example data
mydat <- data.frame(
    date = as.Date(
        c("1998-10-1", "1998-11-1", "1999-10-1", "1999-11-1", "1999-12-1")),
    value = 1:5,
    year = c(1998, 1998, 1999, 1999, 1999))

mydat
#        date value year
#1 1998-10-01     1 1998
#2 1998-11-01     2 1998
#3 1999-10-01     3 1999
#4 1999-11-01     4 1999
#5 1999-12-01     5 1999

# solution by changing the year in all the dates the same
library(ggplot2)

mydat$date <- as.Date(gsub("\\d{4}", "1111", mydat$date))

ggplot(mydat, aes(date, value)) +
    geom_line(size=.8) +
    scale_x_date(date_breaks = "1 month",date_labels = "%b",expand=c(0,0.5)) +
    labs(x="",y= "test") +
    facet_wrap(~year, ncol = 1)

In gsub("\\d{4}", "1111", mydat$date), a regular expression is used for the pattern. It finds four consecutive digits and substitutes them with "1111".
EDIT
If you don't want to make a hard change to the actual date data, you can use pipe operators (%>%) and other functions from the dplyr package:
library(ggplot2)
library(dplyr) # or library(tidyverse) works, too

# subset 2 years
start <- 1998
end <- 1999

mydat %>%
    filter(year %in% start:end) %>% # if you need to subset the years
    mutate(date = as.Date(gsub("\\d{4}", "1111", date))) %>%
    ggplot(aes(date, value)) +
    geom_line(size = 0.8) +
    scale_x_date(date_breaks = "1 month", date_labels = "%b", expand = c(0,0.5)) +
    labs(x = "", y = "test") +
    facet_wrap(~year, ncol = 1)

UPDATE NOTE
I noticed that the year 0000 (or with just 0) or any year that is 9999+ do not work in the OP's dataset. The year may have to be an integer between 1 and 9998. As long as the arbitrary year is the same throughout the date column, the plot will work as intended.
Comment: I am trying it but getting an error message.`Error in match(x, table, nomatch = 0L) :
  'match' requires vector arguments
In addition: Warning message:
In data.matrix(data) : NAs introduced by coercion`
I will continue to troubleshoot...
Comment: @Salvador, do you know which part of the code is getting you this match error? I think it could be `filter(year %in% start:end)` because it uses `%in%` for matching. Try `dplyr::filter(year %in% start:end)` because you may have another `filter` function from another package or try subsetting it first and save the subset as another data frame, like you did in your code. Let me know if it works.
Comment: @LC-datascientist-- I edited my post above. Still get an error but it is different now.
Comment: @Salvador, You're right. Seems like the date doesn't like "0000" (and "9999") for the year in your dataset, but it works in my example here. I don't know why. Anyway, for the purpose of the figure, it doesn't matter what year you choose as long as they are all the same.
Comment: @LC-datascientist-- I wonder what data you used to make that plot because in your example you are plotting date and value. Changing from '0000' to '1111' on my dataset it stills give me this error `Error in match(x, table, nomatch = 0L) :
  'match' requires vector arguments In addition: Warning message:
In data.matrix(data) : NAs introduced by coercion` Can you try the dataset from the link to see if you can re-create my error message?
Comment: @LC-datascientist-- After playing with it for a bit it is working now. Really appreciate your help with this. I will use this trick in the future for other datasets.
Comment: @LC-datascientist-- After taking a closer look to the graphic you created, I noticed that you used facet_wrap and the bottom graph has the months along the x axis but the upper graph doesn't have any month labels. I can only get this behaviour with facet_grid. How do you hide the month labels for the upper graph using facet_wrap? Also, how do change the month labels from Oct to Sept?
Comment: @Salvador, I later tried with your large dataset and used your code (with modification on the year in `date` as described in the solution). `facet_wrap` hides axis labels that are between graph panels by default. The snapshot in your question shows that, too. If your new plots are showing the extra axis labels unintentionally, try restarting your R session, or see which R package that you're using may be affecting it (if you've loaded other R packages not shown in the question). If it still shows, you can post another question about axis labels showing in all of your `facet_wrap()` panels.
Comment: In my short example figure (first plot), the months on the x-axis are between Oct and Dec because I only provided the range of dates (after fixing the year) within those months in the example. If you want to change the dates to start from Oct and end at Sept (12 months later), you can add one year in `date` for all months from Jan to Sept—thus, chronologically, ggplot with be plotting, e.g., Oct 1111 to Sept 1112. If you want to restrict the x-axis scale to only a few months, you can set `scale_x_date(limits = c(min, max))`, where `min` and `max` are the min/max dates.
Comment: I am not sure why facet_wrap is showing all the months between panels on my plots. I have multiple years and all my panels are showing the months along the x axis which it takes space and is annoying to see repeated X axis all over. If I don't use your suggestion '1111' for date, my x axis starts from Oct to Sept but if I use it then my x axis labels start in Jan to Dec. I wonder why '111' changes the order of the months.
Comment: @LC-datascientist-- I would post a question with my full code and dataset but it is really large and people here don't like that. If I post a small dataset I can't recreate what I am trying to accomplish.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/234753/discussion-between-lc-datascientist-and-salvador).
Comment: Sure, I apologize.

How to align facet_wrap


How to view Windows desktops over network?

Question: I would like to view a remote Windows desktop and also control the action/clicks, start applications, etc, from my Ubuntu desktop.
Can this be done? If yes, is there any easy to use tool for this?
Note: One remote machine is running Windows 7, and other is on Windows 8. My machine is running ubuntu 12.04.
Answer: If you wish to control the remote machine along with remote user, like a remote assistance session in windows, the best solution for me was using teamviewer
Comment: Teamviewer is just the easiest way.
Answer: Install VNC server on the Windows machines, then connect to them from Ubuntu using Remmina Remote Desktop Client (select VNC as the protocol).
Answer: If the machine is NOT Windows Home-based license, you can also use Remmina with RDP protocol (no VNC required on the Windows side). Only downside of this approach is the Windows machine will not be accessible from the machine itself during the remote session. I do this all the time and it works very well.


How to make a CLabel in SWT look disabled (Windows)

Question: CLabel.setEnabled(false) apparently does not gray out the label.
Maybe I can use setForeground() to set it to a grey-ish color, but there are still a few questions/concerns:
 a. What color should I use? Will it look as good across platforms.
 b. I will need to save the original color somewhere to make it possible to revert when it's "enabled" again. Also I need to avoid calling setForeground() (from other code) while it's disabled.
Can somebody suggest a better solution? Or at least help answer question a above?
Thanks a bunch!
Comment: You migh use org.eclipse.swt.widgets.Label, its setEnabled method makes component as greyish.
Comment: Thank you. I wasn't aware that CLabel would behave differently in this aspect.
Answer: If you're going for the changing color solution, you can try getting a system color (which will normally be platform-dependent) with one of the constants defined in SWT, e.g.:
Display.getDefault().getSystemColor(SWT.COLOR_TITLE_INACTIVE_FOREGROUND)

and the corresponding
Display.getDefault().getSystemColor(SWT.COLOR_TITLE_FOREGROUND)

Comment: Unfortunately, SWT.COLOR_TITLE_INACTIVE_FOREGROUND doesn't show the correct disabled color in Windows XP for a CLabel. It shows up as a faint gray color and it differs from a disabled Label.


Select all input elements having type text, with matching data attributes value

Question: I have two html elements with input type text and one with input type button,
And I have clubbed them in one group using data-input-group attribute. Now i want to select all elements having input type text using data-input-group attribute but not button.
Please have a look into code which is not working for me,
<input type="text" data-input-group="reg-from">

<input type="text" data-input-group="reg-from">
<input type="button" data-input-group="reg-from" value="click me" >

and jquery code,
var iGroup = $(this).data("input-group");
iGrpElmnts = $('input:not[type=submit], input:not[type=button]').find("[data-input-group='" + iGroup + "']");
/*
* Get all buttons in current form.
*/`enter code here`
iGrpButtons = $("input[type=button]").find("[data-input-group='" + iGroup + "']");

Comment: iGrpElmnts = $("input[type!='button']input[type!='submit'][data-input-group='" + iGroup + "']");  worked for me.
Answer: iGrpButtons = $('input[type="text"][data-input-group="reg-from"]');

Comment: when its `text`, its obvious it cant be `button`
Comment: @Shaddow: Yes, added only text.
Answer: Get all the data-input-group stuff, then find the input with type text inside:
$('[data-input-group]').find('input[type="text"]');

Answer: You can use $("input[type=text]") to select all elements having input type text
Answer:   $(":input").each(function(){
  a = $(this).attr('data-input-group');
  b = $(this).attr("type");
  if( a !=undefined && b == "text") {
      //here you get the input element with type=text and having data-input-group attribute
  }
  })

Please try this


memset is not working with pointer to character

Question: What is wrong with the following code? memset is supposed to work with Pointer to the block of memory to fill. But this code displays problem in console saying segmentation fault(core dumped)
#include<iostream>
#include <cstring>
using namespace std;

int main(int argc, char** argv)
{
    char* name = "SAMPLE TEXT";
    memset(name , '*', 6);
    cout << name << endl;
    return 0;
}

Comment: Don't post pictures of text here. Post the text.
Answer: You have tripped over a very old backward-compatibility wart in C++, inherited from C and dating to the days when there was no such thing as const.  String literals have type const char [n], but, unless you tell your compiler you don't need to be compatible with pre-1990 code, it will silently allow you to set char * variables to point to them.  But it won't allow you to write through such a pointer.  The actual memory is (whenever possible) marked read-only; the "segmentation fault" error you observe is how the operating system reports an attempt to write to read-only memory.
In terms of the language specification, writing to const data through a non-const pointer — however you managed to set that up — has "undefined behavior", which is a fancy way of saying "the program is incorrect, but the compiler doesn't have to issue a diagnostic, and if you get a compiled executable, it might do anything."  A "segmentation fault" almost always means your program has undefined behavior in it somewhere.
If I compile your program with appropriate settings, I do get an error:
$ g++ -std=gnu++11 -Wall -Werror test.cc
test.cc: In function 'int main(int, char**)':
test.cc:7:19: error: ISO C++ forbids converting a string constant to 'char*'
[-Werror=write-strings]
      char* name = "SAMPLE TEXT";
                   ^~~~~~~~~~~~~

Until you gain enough skill to know when different settings are more appropriate, compile all your C++ programs with -std=gnu++11 -Wall -Werror, or whatever your compiler's equivalent of that is.  (You appear to be using a Unix-flavor operating system, so those settings should work.  You may also want -g and/or -O.)
Your program can be made to work by changing it to read
#include <iostream>
#include <cstring>

int
main()
{
    char name[] = "SAMPLE TEXT";
    std::memset(name, '*', 6);
    std::cout << name << '\n';
    return 0;
}

=>
$ g++ -std=c++11 -Wall -Werror test.cc
$ ./a.out
****** TEXT

The change that fixes the bug is from char *name to char name[]; I changed several other things as well, but only to demonstrate better style.  What this does is force the compiler to copy the string literal to writable memory upon entry to main.  Why it does that would take too long to explain here; consult a good C++ textbook.
Answer: This isn't valid C++ code since 2011, and had UB ever before. It is UB in C.
C++≥11: You cannot assign string literals to non-const char pointers.
C++≥98 and C: You cannot overwrite string literals.
change your code to
char name[] = "SAMPLE TEXT";

and you'll have a local array that can be overwritten.
Answer: The code tries to modify the content of a string literal ("SAMPLE TEXT"). That's not allowed.


How To Convert a 1-D Array into a 2-D Array

Question: I already have the code for how to convert a bidimensional one into a dimensional one, but I don't know how to do it vice-versa. Here's my code:
package laboratorio9;

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner entrada = new Scanner(System.in);
    int A[][];
    int B[];
    int n;
    int m;
    int nb = 0;

    System.out.println("Enter the number of lines in your array.");
    n = entrada.nextInt();

    System.out.println("Enter the number of columns in your array.");
    m = entrada.nextInt();

    A = new int[m][n];
    B = new int[m*n];

    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        System.out.println("Enter A["+i+"]["+j+"]");
        A[i][j] = entrada.nextInt();
      }
    }
    System.out.println();

    for (int i = 0; i < m;i++) {
      for (int j = 0; j < n; j++) {
        B[nb] = A[i][j];
        nb++;
      }
    }

    for (int i = 0; i < m*n; i++) {
      System.out.println(B[i] + "  ");
    }
    System.out.println();

    Boolean Swap = false;

    do {
      Swap = false;
      for (int i=0;i B[i + 1]) {
          int Temp = B[i];
          B[i] = B[i + 1];
          B[i + 1] = Temp;
          Swap = true;
        }
    } while (Swap);

    for (int i=0;i<B.length;i++)
      System.out.println(B[i]);
  }
}

Comment: It would be neat if you format your code correctly
Comment: Oh man, I'm not doing this for you. This is 100% doable problem, and solving it will make you a better programmer.
Answer: you're looking for something like:
int j = 0;
int k = 0;
for ( int i = 0; i < nb;i++)
{
    C[j][k] = B[i];
    k++;
    if( k >= n )
    {
        j++;
        k = 0;
        if( j >= m )
            throw Error();
    }
}

which is the same as:
int k = 0;
for ( int i = 0; i < m;i++)
{
    for ( int j = 0; j < n;j++)
    {
        C[i][j] = B[k++];
    }
}

but with trying to help explain the concept more.


Leona's gold income item?

Question: As a starting Leona (support) player, I've been trying to decide whether to start off with Amulet Coin or Relic Shield. (I know that a lot of pro players take Doran's Shield but I'm not up to that standard yet, so that's not what I'm looking for, at least right now.)
Apparently Relic Shield is more gold efficient as support gold income items go, but since I spend a lot of my time in the bush to be prepared to ambush, I'm not sure if Relic Shield could be well-implemented on Leona or if I'm just playing incorrectly.
And in the end, it's also a question about added health or extra mana regen, and about the final upgrades to the items (I like the cooldown reduction on Talisman).
So my question is, should I be taking Amulet Coin or Relic Shield, and why? Do playstyles determine which I should pick?
Comment: As seen by the answers so far, this really just depends on your playstyle(and I would add opponent in lane). If you want more durability go dorans shield or relic shield, if you want passive gold and a later game item start go coin :)
Comment: For starters go with ancient coin. After that, if you want to try a new playstyle, go doran's shield and be a bit more aggresive, and see if it suits you or if the results are positive. But don't play it once, at least play both 3 or 4 times consecutive, there are many posibilities as every adc works different.
Answer: I've been maining Leona as support for quite a while now and I usually pair with a lane partner with strong kill potential. I prefer Ancient Coin between the two for the following reasons:

It allows you to have a consistent gold income just by being near a
minion death (usually inside a brush), while Relic Shield requires
you to last hit a minion thus exposing your location. I usually
prioritize destroying enemy wards to deny them vision and wait for an
opportunity to catch the enemy ADC off-guard while inside the brush.
It builds into a Talisman of Ascension which is extremely useful on
ambush, team clash, chase or escape. I would normally build
Locket of Iron Solari to shield the entire team instead of Face of
the Mountain which only shields a single target.

EDIT 1:
Just tried Doran's Shield last night and I think it's a good starting item as well. Doran's Shield just gives you enough tankiness to sustain enemy damage pre 6, that allowed us to play aggressive, managed to pull off good fights and won the lane all the way. I recommend using this on a miser build (GP10 quints and masteries) to make up for your late Ancient Coin or Relic Shield.
Answer: First of all, you should not get too set in your ways with either Ancient Coin or Relic shield.  Substantial changes to both build paths have been implemented on the Public Beta Environment, indicating that large changes to the items are likely in the near future.
At the current time, either item is viable.  Relic Shield will generally give you and your team more gold.  However, the item that it eventually builds into (Face of the Mountain) is generally not considered that useful.  Also, you do have to take some care to maximize your gold gains as you want to be last hitting the appropriate minions with your charges (since some give much more gold than others).
On the other hand, Ancient Coin will usually give you less gold.  It is easier to use since you don't have to last hit anything.  But, the MAJOR benefit is that the final item it builds into (Talisman of Ascension) is considered extremely useful in the endgame for the team speed boost.
For this reason, I see most high level players preferring Ancient Coin over Relic Shield.
Answer: You should try considering the Doran's shield start.  It makes you much more resiliant to poke and makes diving them much safer.
As far as gold items.  Ancient coin is normally the recommended because of the active it builds into although relic shield is useful too.  Either can work just as well.
Also, note that you would still pair a gold items along with the doran's shield.
Comment: A dorans shield is only better if you're expecting harass while you're harassing, so essentially useless compared to a coin when you're pushed up to their turret. And playing against certain lane matches make an agressive leo risky :) As i said in the question comment it all depends on the game/playstyle for what item to take
Comment: This, use a shield to start.
Comment: @Blindy disagree that it should be taken all the time by everyone.. it depends on the matchup and player and opponent.. Passive players or lanes that push hard get little benefit from a dorans shield
Comment: If you are playing leona and playing passive, you are either playing her wrong or you are behind.  Lanes who push hard get lots of benefit from dorans.
Comment: Well Brian it's up to you what you pick, I'm just saying that if you don't go for a shield vs a support with a shield, you're far more likely to lose the lane, and lose hard. Leona's biggest weakness is her pre-3 game where smart laners will poke her down so she's too low to all in (or completely lose bush control). The shield helps mitigate this a lot.
Comment: No, you definitely want a doran's regardless of matchup.  You might get lucky sometimes without it, but you will lose your lane more often than not if you make other choices.  It hardly depends on the game/playstyle.  You still get a gold item, but if you against good players Doran's is a must.
Comment: If I get a Doran's first thing, when should I get a gold item and when should I sell Doran's to make room for other builds?
Comment: Your first back, you should either buy a gold item and wards or a sightstone depending on how much gold you have.  Only sell doran's later on when you need to free up an item slot for something.

Leona's gold income item?


Unable to "point to" passed array of function pointers in C

Question: I've been trying to pass an array of function pointers to a function.  Once in that function I need a pointer to that array of function pointers but I keep getting an error.  I'm able to do it when it isn't a function argument.
void (*(*PointerToFuncPtrArray)[2])(unsigned char data[], unsigned char length);
void (*FuncPtr[2])(unsigned char data[], unsigned char length) = {

    func1,
    func2,
}

void NotArguement(void)  // attempt to point to without passing as parameter
{
    PointerToFuncPtrArray = &FuncP;   // this works
}

//  attempt to pass as argument
void AsArguement((void (*ptr[])(unsigned char data[], unsigned char length))
{
   PointerToFuncPtrArray = &ptr;    // This throws error

}

This throws...
Error   1   error C2440: '=' : cannot convert from 'void (__cdecl **[])(unsigned char [],unsigned char)' to 'void (__cdecl *(*)[2])(unsigned char [],unsigned char)'

Comment: In addition to the type conversion problem you have disbalanced `()` in `AsArguement` parameter declaration. There should be only one `(` after `AsArguement`. In reality, this is normally the error the compiler will report first. I wonder how you managed to overlook that. Is the the real code you were trying to compile?
Comment: The error message seems fairly clear!  `PointerToFuncPtrArray` has explicit size info; you're trying to assign an incomplete type (i.e. it's missing size info) to it.
Answer: Array declaration in function argument list decays to pointer declaration. So, your function parameter is not declared as an array (despite the misleading appearance). It is declared as a pointer-to-pointer, meaning that inside the function the array type is lost irreversibly.
The same error will be reported in this simple example
int x[2];
...
void foo(int a[2]) /* <- equivalent to `void foo(int *a)` */
{
  int (*p1)[2] = &x; /* <- OK */
  int (*p2)[2] = &a; /* <- ERROR: can't convert `int **` to `int (*)[2]` */
}
...
foo(x);

In the above example a is no longer an array. It is a pointer of int * type, meaning that &a has type int ** and cannot be used to initialize an object of type int (*)[2].
In C, the only way to pass an array to a function while preserving the "arrayness" of the argument is to pass it "by pointer to the whole array", as in
int x[2];
...
void foo(int (*a)[2])
{
  int (*p)[2] = a; /* <- OK */
}
...
foo(&x);

Note that the application of & operator "moved" from inside of the function to the point of the call.
The same modification in your code would look as follows
void AsArguement(void (*(*ptr)[2])(unsigned char data[], unsigned char length))
{
   PointerToFuncPtrArray = ptr;
}

You just have to remember to apply & operator to the array argument when you call this function.
Comment: Awesome, Thanks for such a quick answer.
Comment: (*PointerToFuncPtrArray[0])(test, sizeof(test));
 (*PointerToFuncPtrArray[1])(test, sizeof(test));

The first line correctly calls the method func1, but the second gives an access violation.
Comment: Fixed it, sorry for the multiple comments.  Should be ...

(*PointerToFuncPtrArray)[1](test, 3);
Comment: @bassplayer142: So, how do you call it? In order to call through your `PointerToFuncPtrArray`, as declared in the original post, you have to do `(*PointerToFuncPtrArray)[0](...)`. Note how the `()` are placed. You have different placements of `()` in your comments. So which one are you using?
Comment: I might be a little confused on what you're asking..  The actual function call wasn't in the original post.  Afterwards I ran into the issue where...

(*PointerToFuncPtrArray[1])(test, 3);  // is the wrong way
(*PointerToFuncPtrArray)[1](test, 3);  // is the right way
Comment: @bassplayer142: I was referring to your comments right here. In the earlier comment you did `(*PointerToFuncPtrArray[1])(test, sizeof(test))`, which was incorrect. In the next comment you did `(*PointerToFuncPtrArray)[1](test, 3)`, which was correct.


How can I counterbalance a shelving cabinet with a rearward weight bias to prevent tipping?

Question: I will add drawing soon, but I have and old stand up piano brass back with all the strings. I was going to bolt that to the back of the shelves but obviously it will make it very back heavy. I am worried that it may cause it to fall backwards, how would i counter balance this or limit the chance of it falling backwards (with out drilling into the wall)? Thanks all!
The picture is an example of what I want to do (similar). it going to be a bit bigger closer to 60h x 60w x 30d. The part with all the stings in the back will be the really heavy part. It will be directly against the wall. is there anything I should worry about with it falling backwards still. I don't want it to rely on the wall behind it.
I am turning it into a bar!
Comment: So if you don't want to drill into the wall then it can lean against it. Or give it bigger feet.
Comment: Please show a picture and indicate the distance to the wall.
Comment: With freestanding you mean accessible from both sides? Like a library shelf? Or close to a wall, but not against it?
Comment: Accessible from one side, and will be close to a wall. The metal piece has to weight about 100-300lbs. About 3 1/2 -4 1/2 feet tall. So when it's on that back side and how tall it is, tipping will be easy either way regardless. Would bigger feet add that much more support? Would a complete flare bottom work best?
Answer: Solve the problem after it's a problem.
Unless the weight is cantilevered behind the rear feet you really don't need to worry about this. The center of gravity will be inside the box, so to speak, so it would take a substantial force to tip it back. If the feet do happen to be inboard, install some that are right at the back face of the cabinet, even if they're behind the decorative ones.
I'd build the thing, then assess the issue. If necessary, mount some 1/2"x2" steel bar under the front edge as ballast, using countersunk flat-head screws and good glue.
Answer: Put brass back at a right angle to the end of the shelf.

You are using salvaged piano parts to make a shelf!  Bravo!  But if it is in the back, it will be behind the books.  If you have a lot of books, people will not notice the piano piece and just see a prosaic shelf.  Boo.  Plus as you note, it is unstable.
Put the piano brass at right angles at the end of the shelf.  It should rest on the ground and in addition to its weight, will act as a wide foot to prevent tipping.  Best: it will be on full display to amaze and amuse!
And it will be accessible.  Might I suggest a pair of mallets be stored atop the piano brass.  After I finish the mead I brought to your place as a shelfwarming gift, I will play you an inspired tune.
Comment: that's actually not a bad idea to do it this way, I would have to cut it in half to use it on either side, I don't have any great metal cutting tools for something so thick. I will be stealing this mallet idea.  The piano its self was in bad condition (termite dmg) but the thing is 110 years old I couldn't let it go to waste
Comment: You do not need to cut it in half!  Just use it on one side.  I think ideals of symmetry can be set aside in the interest of art.  Eventually you may find something else that tells you it wants to be the other side.


Java socket unable to send two byte arrays

Question: I am trying to send two byte arrays over a Java socket. I have captured the data via wireshark and it shows that the first byte array sends; the second, however, doesn't send at all.
I am using Linux Mint and Oracle's JRE (not OpenJDK).
byte[] packet_one = new byte[] {(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x50};
byte[] packet_two = new byte[] {(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x78};
Socket sck;
DataInputStream dis;
DataOutputStream dos;

try {
sck = new Socket(IP_ADDRESS,PORT);
dis = new DataInputStream(sck.getInputStream());
dos = new DataOutputStream(sck.getOutputStream());

int recv_header = dis.ReadInt(); // This receives the correct response.

dos.write(packet_one); // Sends fine.

dos.write(packet_two); //Does not send.

int data_length = dis.readInt(); // No more data received.

}catch(Exception e) {
 System.out.println("Error: " + e.getMessage());
}

So, dos.write(packet_one) works (confirmed by wireshark). Writing packet_two doesn't work. The data_length returns 0 since I don't receive anymore data either. No errors or exceptions get caught.
I have also tried using dos.flush(), but it doesn't make a difference.
Any ideas on why this may be the case?
Comment: Can you post the receiver/client code?
Comment: This is the client code. The server's source code is outside my control.
Comment: make dos.flush(); to force data to be written
Comment: I have also tried dos.flush(). It doesn't seem to make a difference in this case.
Comment: if the first write() works and flushing die outputstream doesn't make a difference, close the stream after the first write and open it again to send the second package.
Answer: Maybe you're exiting the program before there's time to send the buffered bytes?
Perhaps if you add something like:
for (;;) {
    final byte x = dis.readByte();
    System.out.println("got byte: " + (x & 0xFF));
}

the program won't exit, and you'll also see if there are more bytes that the server sent back. Might offer clues.
And, in case you don't know, readInt() reads for bytes and returns an int made from those bytes, which is 0 if all the for bytes read are zero. So your comment 'No more data received.' feels a bit ambiguous.
You could also try inserting a
sck.setTcpNoDelay(true);

after creating the socket. Writes should then go on the network immediately. I think.
Hope this helps.


How can I use an HTML tag to wrap all elements that follow a specified element?

Question: I'm working with Vue 2 and Sanity.io and I need a way to surround all elements that comes after a specific element with HTML tag, and then surround this element along with the followed elements with another HTML tag.
let's say every
 will have multiple paragraphs that follows it and then another
 and another paragraphs follow it. I want those to be divided with summary and details HTML tags.
For example, I have data coming over from Sanity and it goes like this.

text

text

text

text

text

text

text

text

I need a way to manipulate the DOM to make it read my data like this

text

text

text

text

text

text

text

text

To clarify more, I'm using protable-text-to-vue package which sends back the data as vue components blocks. basically they are coming from sanity in a similar form to the example mentioned above.
Comment: How does the response from `sanity` look like?
Comment: Consider adding a *runnable* [mcve]. Please note codesandbox makes [importing local projects](https://codesandbox.io/docs/learn/getting-started/your-first-sandbox#import-local-projects-via-cli) via CLI fairly easy.
Comment: @BoussadjraBrahim I edited the question to add more clarification.
Comment: `blocks` is just a text? if yes  you could replace the tags using string methods
Comment: It's all test yes, some comes as h3 and some comes as paragraphs. Can you provide an example or a source to an example?
Answer: I was able to accomplish this by using the mounted() to call getElementsByTagName() :
https://www.w3schools.com/jsref/met_element_getelementsbytagname.asp
Then I looped over each element and wrapped it with  and  tags.
ele.outerHTML =
                '' +
                ele.outerHTML +
                ''

And then I moved all h1 children inside the  tags by using appendChild().
let children = document.querySelectorAll(
              `details:nth-child(index) ~ *:not(h1,h1 ~ *)`
)

Array.from(children).map(function(child) {
        document
        .getElementById(`uniqueId`)
        .appendChild(child)
})


Importing/requiring an NAPI addon from a Webpack ReactJS/ReactTS project

Question: I have a custom API (closed source for now), built in pure C. This API is the client side of a communication protocol (think network-based database queries). I have successfully used node-gyp to compile the C code wrappers so that the NAPI addon addon.node can function in JavaScript by calling the C. I have also written a .d.ts file, so that this addon can work from TypeScript. I have no issue with both of these use cases; ie, doing a tsc index.ts && nodejs index.js will compile and run the imported/required addon without a hitch, and the client-side operations of my C API happen without a hitch. I have made this addon into a private npm package, and have been using it in small TypeScript projects by installing it as a node_modules dependency without any issue.
My issue arrives when I try to run a React web app which needs to use this addon. I need React because my data-querying is to be used for GUI-type web applets (that query their data, and update the GUI view, in real-time). I launch my React app with react-scripts start, like is done with any React project created via webpack/create-react-app. I do not know if there is some other way of launching a ReactJS/ReactTS project than with a react-scripts-family command. If you know an alternative, I will try it.
My bug exactly:

On the TypeScript side of things: I get a Module not found: Can't resolve '@my-company/my_package/addon' in '/path/to/typescript/srcdirectory' error when I try to import/require the addon, for the right path. Yes, I am absolutely certain my path is correct (both in package.json "paths", and the calling source); other (normal .ts) files in the same dependency directory are found and imported just fine with the same path (and their own filename) from the same .tsx or .ts source. Also note that this same path+filename (ie, with addon and not addon.node) is recognized just fine by a non-React .ts file, compiled with tsc. It is the addon.node, generated by node-gyp that is simply not recognized when react-scripts start handles the TypeScript transpilation.

On the JavaScript side of things: I also tried first generating the corresponding JS file for my TS source with tsc, and "requiring" my addon; then launching react-scripts. For the path var api = require("@my-company/my_package/addon"); in the generated JS, I get the same "Module not found" error. For var api = require("@my-company/my_package/addon.node");, the addon IS recognized, however, the JS fails when I get to any line with api.MyFunction() for any function, with TypeError: api.MyFunction is not a function.

I have found the following question on SO, which seems to be related to mine: How to use a native node.js addon in React ; but it is unanswered and might not happen for exactly the same reasons as mine.
My question is: what is the appropriate way to compile an NAPI addon with node-gyp, packaging it with a certain structure for npm, and importing it from a React JS/TS project so that the imports work ? Should some specific constraints in either the package.json for the addon, or the one for the React project, be verified so that this can work smoothly? I'm not sure many people have experience with such a use case (going all the way from raw C to ReactTS); but there's bound to be some NAPI addon that's famous enough to be used in some React project: even a link to that might be useful to me.
Any links, ideas, or advice you provide will be greatly appreciated. Thank you for your time.
Edit: After much experimentation and documentation reading, I am now confident that the issue stems from webpack, and need to use externals in webpack.config.js to resolve how I import the addon in some way. What is the syntax for both the webpack.config.js, and how should this "external" lib be imported in my .tsx files ? Is there anything special to do with my package.json when using a specific Webpack config ?
Answer: So I managed to fix my issue. It turns out the problem was more fundamental than I thought. I figured it out through the following links, and understood the solution by asking around on the Reactiflux discord. Since the following questions didn't really explain what solutions are available, I figured I'd post them here.
How to use Native Node Modules on a React, ES6, Electron App?
Cannot load Node native addons with webpack
Basically, native node addons can only be launched from a node server, and not directly from the browser. The browser will NEVER run the code from the node addon itself, for security purposes. Ie, node-gyp/napi aren't some "C to JS" transpiler. If you want something of that kind, look up emscripten.
A node-only solution to this problem is simply to separate the front-end logic from the back-end logic. By this I mean having on one hand a small node server (serving with express for example) that handles the things that need to be done by the addon; and on the other hand, having a React front-end client in another project that connects to this server to get whatever data it needs for the front-end (say, by having the server communicate a JSON to the client). This allows the browser to consume the results of the addon's operations in a way where the browser itself doesn't ever run any addon code. As can be seen in the first link, some similar division is to be done for an Electron app, using ipcRenderer or remote instead of express to communicate between the front-end and the back-end parts of the app.


java -jar with cf -e not working on Java 14

Question: I'm playing around with javac + java + java -jar to get more involved with modules.
I'm using latest JDK 14.
I have this simple class:
package defaultpackage;
public class Main{
    public static final void main(final String args[]){
        System.out.println("HI WITH: "+java.util.Arrays.toString(args));
    }
}

I create the directories without problems:
javac -d . Main.java

Later on I can create the jar file playing mixing some values like this:
jar --create --file Jar.jar -e defaultpackage.Main defaultpackage
jar -cfe Jar.jar defaultpackage.Main defaultpackage
jar cfe Jar.jar defaultpackage.Main defaultpackage

They all create the jar with the class in the manifest file and I could run it with this simple command:
java -jar Jar.jar

But I could not this command to work is a slightly different of the previous perhaps this couldn't be mixed but i thought it could:
jar -cf Jar.jar -e defaultpackage.Main defaultpackage

I'm trying to said well create the Jar.jar file with the entry point defaultpackage.Main
But states.
jar -cf Jar.jar -e defaultpackage.Main defaultpackage
-e : no such file or directory
defaultpackage.Main : no such file or directory

I have try this as well but with the same response:
jar -cf Jar.jar defaultpackage -e defaultpackage.Main

And:
jar -cf Jar.jar -e defaultpackage/Main.class defaultpackage

But also with the same response.
How can I make this command to work? I could not mix -cf plus -e?
Comment: @LinuxServer: please do not bold all sentences in a question. That is less readable, not more readable.
Comment: "I could not mix `-cf` plus `-e`?"  Correct.  The options are somewhat like those of tar, but not exactly like tar.  You cannot use both combined letters and separate option letters.
Comment: got it mate please post it as answer.
Comment: @VGR By the way what is tar? mate The 1 thing it comes to my mind to that word is George Brett. :( hehe
Answer:
I could not mix -cf plus -e?

Correct.  The options are somewhat like those of the venerable Unix tar command, but not exactly the same.  You cannot use both combined letters and separate option letters.


javafx gantt chart

Question: I would like to do Gantt chart in javafx, but there is no examples how can I do this. I tried convert bar chart to gantt chart, but this didn't bring good results. :/
Is there any easy way to do it?
Ps. sorry for my english ;p
Comment: I think, the only way to get it - is to create it by yourself, now.
Comment: Did you observe a source code of opened part of javafx 2?
Answer: Ok, as you don't comment on my comments, I'll leave a version of official answer.
Now, Gant diagram is not a part of JavaFX 2+, and I don't know about an existing samples, where it is already built. So, the answer is - to build it by yourself.
Some part of JavaFX is open source, javafx controls, and javafx-charts projects are open-sourced as well. They can be found here : http://openjdk.java.net/projects/openjfx/
You can observe code of bar charts, line charts (and, may be, a scroll pane - for large charts), and it should become clear enough to understand, how to build a Gant chart yourself. It will require some coding, yes..
Possibly, if it will be created well, you can even go through the process and contribute it into open jfx.
Answer: Maybe you can try my commercial framework called FlexGanttFX for JavaFX Gantt charts.
http://www.flexganttfx.com

javafx gantt chart


What is the right code for a number sequence in VBA

Question: I'm trying to create a tool to generate a Continuity and Isolation Check.
This is the sequence I would like:

I'm basically trying to create a sequence on the right side of my table that generates a diminishing pattern. 1 to 5, 2 to 5, 3 to 5 etc.
On the left, every set of numbers will be next to 1, then 2, etc. Like the picture.
Here is my code so far. There is some sequence in here I can't figure out how to create a code for:
    Private Sub CommandButton1_Click()

Dim i As Integer

        For i = 1 To 5

        Cells(i, 4).Value = i     '' 1 -15 starting after the 15th integer
        Cells(i + 4, 4).Value = i      '' 2 -15 starting after the 15th integer
        Cells(i + 7, 4).Value = i      '' 3 -15 starting after the 15th integer
        Cells(i + 9, 4).Value = i
        Cells(i + 10, 4).Value = i

        Next i

End Sub

What can I try next?
Answer: You need 2 nested loops:
n = 5
row = 1
for i = 1 to n
    for j = i to n
        if i <> j Then
            cells(row, 1) = i
            cells(row, 2) = j
            row = row + 1
        EndIf
    next
Next

Comment: There should be a `row = row + 1` in the inner for loop as well. And the  inner for loop should be `For j = i to n`?
Comment: @RaymondWu Added it immediately after posting. Thanks though.
Comment: @TimWilliams Fixed. Doing this from my mobile :-)
Comment: This is clean, elegant as hell and beautiful thank you. This worked great. The only tweak id need is to delete the rows that have the same number on both rows. where its 1 and 1 and 2 and 2 etc. But i might employ a macro that clears the matching values across the rows or something like that, unless you have a simpler solution?
Comment: You mean that you do not want to include matching rows and remove the row entirely? Or you want to cross them as in the image?
Comment: yes, i want to remove the row entirely. i'm using to create Continuity and Isolation tables to check a cable harness, so there would be no need to test pin 1 to pin 1 on the same connector.
Comment: Updated my answer.
Comment: absolutely brilliant and worked like a charm. Thank you so much. Exactly what I needed. thank you.
Answer: Array version which is faster than writing to cells repeatedly in the loop:
Option Explicit

Private Sub Test()
    GenerateDiminishingPattern 5
End Sub

Private Sub GenerateDiminishingPattern(argLimit As Long)
    Const startRow As Long = 1

    Const repeatCol As Long = 1 'Column A
    Const diminishingCol As Long = 4 'Column D

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1") 'Change the sheet name accordingly

    '=== Uncomment if you need to apply strikethrough to the first value of each loop
    'ws.Columns(repeatCol).Clear
    'ws.Columns(diminishingCol).Clear

    '=== Determine the size for array based on sum of consecutive number
    Dim outputSize As Long
    outputSize = (argLimit * (argLimit + 1)) / 2

    Dim repeatOutput() As Long
    Dim diminishingOutput() As Long

    ReDim repeatOutput(1 To outputSize, 1 To 1) As Long
    ReDim diminishingOutput(1 To outputSize, 1 To 1) As Long

    Dim i As Long
    Dim j As Long

    Dim rowIndex As Long
    rowIndex = 1

    For i = 1 To argLimit

        '=== Uncomment if you need to apply strikethrough to the first value of each loop
        'ws.Cells(startRow, repeatCol).Offset(rowIndex - 1).Font.Strikethrough = True
        'ws.Cells(startRow, diminishingCol).Offset(rowIndex - 1).Font.Strikethrough = True
        For j = i To argLimit
            repeatOutput(rowIndex, 1) = i
            diminishingOutput(rowIndex, 1) = j
            rowIndex = rowIndex + 1
        Next j
    Next i

    'Write output to worksheet
    ws.Cells(startRow, repeatCol).Resize(outputSize).Value = repeatOutput
    ws.Cells(startRow, diminishingCol).Resize(outputSize).Value = diminishingOutput

    Erase repeatOutput
    Erase diminishingOutput
    Set ws = Nothing
End Sub


How to show $T(p(x))=xp(x)$ from $V$ to $V$ is either injective or surjective if $V=P(R)$?

Question: My first question is that can we assume that the two vector spaces $V$ have the same dimension??
If so, we can just prove injectivity.
My first method is let $p(x)\in \ker T$, then $T(p(x))=0$. Then $xp(x)=0$. But I don't know if $x$ is assumed to be not $0.$ If it's assumed that $x\ne 0$, then we easily see $p(x)=0$.
My second method is using matrix representation (which i don't know if that's valid since we don't know that dimension of $P(R)$). If we suppose $p(x)$ has degree of $n+1$, then we can write it as $a_0+a_1x+...+a_nx^n$. Then $xp(x)=a_0x+a_1x^2+...+a_nx^{n+1}$. The matrix has a row of $0$, so this outcome is contradicting my first method.
Could someone clear my mind?
Answer: If $p(x)\in\text{Ker}\,(T)$, then $xp(x)\equiv 0$, i.e., $xp(x)$ is the zero polynomial. Once $\mathcal{P}(\mathbb{R})$ is a domain, we must have $p(x)\equiv0$ once $x$ is not the zero polynomial. So $T$ is injective. Now observe that if $\text{deg}\,(p(x))=d$ then $\text{deg}\,(T(p(x)))=d+1$. So we see that $T(\mathcal{P}(\mathbb{R}))=\mathcal{P}(\mathbb{R})\setminus\mathbb{R}$, so you have the take $\mathcal{P}(\mathbb{R})\setminus\mathbb{R}$ as the domain of $T$ in order for it to be surjective.


laravel 5.4 image upload no file detected

Question: This is my code.It returns no file everytime. I have an input field with name="file" being sent with this form.
Please help me diagnose my code so I can understnd why this has happend. Thank you.

New Auction

                <form class="form-horizontal" role="form" method="POST" action="{{ url('/addproduct') }}">
                    {{ csrf_field() }}

                        Item name

                            <input id="itemname" type="text" class="form-control" name="itemname" value="" required>

                        Decsription

                            <textarea id="itemdesc" class="form-control" name="itemdesc" value="" required></textarea>

                        Category

                            <select id="category" class="form-control" name="category" required>
                                <option value="Games">Games</option>
                                <option value="Gadgets">Gadgets</option>
                                <option value="Books">Books</option>
                            </select>

                        Starting bid

                            <input id="bid" type="number" class="form-control" name="bid" value="" required>

                        Incremental value

                            <select id="increment" class="form-control" name="increment" required>
                                <option value="10">10</option>
                                <option value="20">20</option>
                                <option value="50">50</option>
                                <option value="100">100</option>
                                <option value="200">200</option>
                                <option value="300">300</option>
                                <option value="500">500</option>
                                <option value="1000">1000</option>
                            </select>

Images uploaded to SpinkyDink are resized. For the best quality images on your auction, please use land-scape images instead of portrait images.

(Turn your phone sideways and snap a pic)

                        Main Image

                            <input id="file" type="file" class="form-control" name="file" required>

                            <input id="file2" type="file" class="form-control" name="file2">

                            <input id="file3" type="file" class="form-control" name="file3">

                            <input id="file4" type="file" class="form-control" name="file4">

                            <button type="submit" class="btn btn-success">
                                Submit Auction
                            </button>

                </form>

ROUTES:
Route::post('/addproduct', 'NewProductController@addproduct');

Controller
public function addproduct(Request $request)
{
    if ($request->hasFile('file')) {
        echo "file found";
    }else{
        echo "no file";
    }
}

The line echo "no file" will return everytime when I hit this controller.
Answer: Add enctype attribute to the form:
<form class="form-horizontal" role="form" method="POST" action="{{ url('/addproduct') }}" enctype="multipart/form-data">

By default the data gets encoded, but if you want to upload files using the form you have to disable the encoding and this is what multipart/form-data does.


Can you paint Dow THERMAX WHITE FINISH INSULATION?

Question: Can you paint the insulation boards after installing them?  This would be for an attic interior installation. Then could I skip the dry wall?  How good would it look compared to drywall?
Answer: Thermax is rated for fire exposure and those particular boards are intended for interior finished space, so yes, you can paint the boards instead of covering them in drywall. However, I'm not sure the result will be very aesthetically pleasing or durable if this is going to be a finished residential space, which, based on your previous question, I'm guessing it is. But it should work.


Lenovo ideapad s205 suspend/hibernate problem

Question: I'm currently using Ubuntu 11.10 on my laptop. At first the Wifi didn't work so I ran
rfkill unblock wifi
rfkill unblock all
modprobe -r acer_wmi

Now the Wifi works, however when I try to Suspend/Hibernate the computer. It gets stuck.
What should I do?
Update
Whenever I try to run pm-hibernate, the computer goes into hibernation for a split second and comes back.
Comment: The Suspend works in fedora 15, maybe this is because it uses systemd instead of upstart?
Answer: Edit: Just noticed that the acer_wmi module doesn't really have much to do with your suspend problem - more than it's blocking suspend. If you find the module responsible for blocking suspend, just switch out  its name with acer_wmi in the following suggestions, but without finding the responsible module, my suggestions probably aren't going to help you too much.

The traditional way of troubleshooting suspend where there's a known driver issue is to force the unloading of that module before suspend. You'd do that by running
sudoedit /etc/default/acpi-support

And looking for the MODULES="" line and changing it to (in your case):
MODULES="acer_wmi"

But reading the comments at the top of /etc/default/acpi-support, I'm not sure that's still going to work. Give it a go.
If it doesn't, you might find a short script like this fixes things:
#!/bin/sh

rmmod acer_wmi
pm-hibernate
modprobe acer_wmi

That will need to be run as root, so whereever you save it, you'll want to run it like: sudo bash ~/my-suspend-script.
I feel like there should be a good way to hack this into the /etc/pm/sleep.d/ system but I don't know enough about it to say conclusively. Perhaps something like this:
#! /bin/sh

case $1 in
     suspend|suspend_hybrid|hibernate)
        rmmod acer_wmi
        ;;
     resume|thaw)
        modprobe acer_wmi
        ;;
esac

That would be cleanest in terms of integration if editing acpi-support doesn't work.
Answer: Installing the tlp package fixed any problems I had with suspend on my Lenovo S205.
credit
Comment: indeed -- time to delete our comments :)


How do I unlock courses in Mario Kart Wii?

Question: I imagine I have to win some cups in single-player mode.  Can someone be more specific than that?  A link to a site with the info would be fine.  I'm disappointed by the organization of the sites I checked out.  I couldn't find the answer.
Answer: Basically, you just need to get a medal (bronze, silver or gold) in single player Grand Prix mode in each cup.

Star Cup => Finish 3rd or better in Mushroom Cup and Flower Cup
Special Cup => Finish 3rd or better in Star Cup (which means that you
  also finished 3rd or better in Mushroom Cup and Flower Cup)
Leaf Cup => Finish 3rd or better in Shell Cup and Banana Cup
Lightning Cup => Finish 3rd or better in Leaf Cup (which means that you also
  finished 3rd or better in Shell Cup and Banana Cup)
Answer: You have to beat all the different cups on the different classes (50cc, 100cc, etc.)
Answer: star cup: get third place or better in the mushroom cup and flower cup in either 50c,100c, or 150c
special cup: get third or better in the star cup in either 50c,100c, or 150c
leaf cup: get third place or better in the shell cup and the banana cup in either 50c,100c, or 150c
lightning cup: get third place or better in leaf cup in either 50c,100c, or 150c
Comment: This adds nothing that hasn't already been said, I'm afraid.


How do I fix my test function for swap method in rust?

Question: So, I wrote a program to swap two numbers in rust, and I've pasted the code below along with it's test function.  My swap() and main() methods work and correctly swap the values in my program when I run cargo run, but when I run cargo test it won't compile, and I'm not sure how to correct my test function.  Can anyone tell me what I'm missing in my function, or if I wrote it incorrectly entirely?  Thanks!

    fn swap(a: &mut u32, b: &mut u32) {
    let temp: u32 = *a;         // stores value of a in temp
    *a = *b;                    // assigns the value of b to a
    *b = temp;                  // assigns the value of temp (which is a) to b
                                // values are now swapped
}

fn main() {
    let mut a = 26;             // assigns value 26.0 to a
    let mut b = 10;             // assigns value 10.0 to b

    println!{"Before swap: "};
    println!("{}, {}", a, b);   // prints orginal values for a and b

    swap(&mut a, &mut b);       // calls swap funciton

    println!("After swap: ");
    println!("{}, {}", a, b);   // prints the swapped values for a and b (expecting "10, 26")
}

#[test]
fn test_swap() {
    assert!(swap(&mut 26, &mut 10) == 10u32, 26u32);
}

Comment: `swap` doesn't return anything. You can't compare its return value to anything (but `()`, I guess) because there is none.
Answer: Your swap function takes a couple of mutable references, works over there and does not returns anything.
So when your making assert!(swap(...) == 10u32, 26u32) your making assert!( () ==  10u32, 26u32) which have 2 errors.
First left part your trying compare () with something different of ().
And two, but even more fundamentally your writing a bad expression, 10u32, 26u32 are two different members, is like your making something like if true == true, false if 10 == 26, 10. I mean something with this form if left == right, a_third_member_senseless.
Probably your test should looks like this:
#[test]
fn test_swap() {
    let mut a = 10u32;
    let mut b = 26u32;

    swap(&mut a, &mut b);

    assert_eq!(a, 26u32);
    assert_eq!(b, 10u32);
}

You change the value with your function and then, verify the final state of your values.
Comment: actually yes!, I did not realize until now that you comment it


I've changed default shell but my terminal don't get it

Question: Recently I've changed my default shell from bash to zsh like this:
chsh -s /bin/zsh myname

But when I invoke a new terminal (e.g. using ctrl+alt+T) I still have bash loaded:
myname@machine:~$ cat /etc/passwd | grep myname
myname:x:1000:1000:myname,,,:/home/myname:/bin/zsh
myname@machine:~$ echo $SHELL
/bin/bash

zsh is installed and can be explicitly runned with zsh command.
How to deal with that?
Comment: log out and log back in?
Comment: btw.: A useless use of cat. Grep expects a filename, if you don't feed it from stdin: `grep myname /etc/password` would be the natural way to do it.
Answer: Edit /etc/passwd file. In terminal type
gksu gedit /etc/passwd
Find out line containing your user name. Change /bin/bash to /bin/zsh.
Logout and Login again. Now zsh will be default. See the below image
Comment: line with my name is already set to `/bin/zsh` as I showed in second listing
Comment: I just tested in my system. Its working after logout and login
Comment: yes, I've logged out and in, and it's all works. I've got used to instant changes on new terminal window after my edits  of `.bashrc` and forget that this is not working that way with user information.
Comment: If anyone else reaches this page and doesn't want to log in and log out again to see the shell change working, use the command `su - myname` to open a session with the new shell, using an existing terminal window.


Installing a grab bar on a fiberglass shower wall

Question: My elderly mother is coming for a visit and I initially was looking for a suction grab bar but deemed it not reliable so looking for options to install it.  I've seen videos of grab bar installation without studs - they use Wingits and a toggler (snap toggle brand) but looks like they're not compatible with fiberglass. Has anyone installed a grab bar on a fiberglass shower wall?
Updated March 12:
I still have not installed it as I'm waiting on my order (see #1).

I ordered this from Amazon for the fiberglass installation and waiting for the delivery.

In the meantime, I have a studpop that I use to find the location of a stud screw - I detected three studs on my shower wall but decided to install the grab bar ON the middle and right studs (see Using "stud pops" for finding the center of a stud) - helpful tips are very much welcome.
Comment: What type of, and how, a grab bar should be mounted depends a great deal on the specifics of the person(s) it is supposed to help. For one extreme, my 87 year old mother can't "grab" anything with her arthritic hands, but can lean on to bars at appropriate elbow height.
Comment: Yep, forget suction caps. -- Consider alternatives to mounting the grab bar on the shower wall. What about an "inverted dance pole" mounted to the ceiling? Grab bars right outside the shower? If the fiberglass wall is sturdy enough, you could also try special glue to attach the grab bar - you'll probably need mounting plates which provide a large area for the glue and also distribute the forces to a larger portion of the wall. I'd also recommend a shower chair...but you already got one. you don't need two.
Comment: The stud pop finds stud centers only if the nails and screws are centered.  A sheet of drywall has about 30 screws. They don't have to be centered and if some of them miss the stud entirely the sheet will stay put.  You will have six screws and a falling person yanking them out.  You want them all exactly where you want them.  I suggest using monkey hooks or a long 1/8 inch drill in the drywall above the shower to exactly find the edges of the two studs.
Comment: @jay613 thank you - yes I will need to drill 1/8 inch through the fiberglass shower wall and push a wire thru it to find the edges of each of the  studs.

I am not a handy guy but having  installed electronic doorbell and replacing plumbing fixtures, I am hopeful I will be able to do this right.
Answer: I've done a lot of carpentry in senior living environments with rigid ADA requirements (and compassionate supervision in general). Here are some suggestions.

Most fiberglass shower units* do not lay tight against wall framing. Therefore, it's often not possible to simply locate the studs and bolt away. Things will get get bendy at best and crunchy at worst. When force is then applied to the bar there will be movement which can damage the surround finish or result in fastener failure or just a lack of confidence in the user.

Most fiberglass units of higher quality have backing built into them in the way of 3/4" plywood or OSB. This often covers the bulk of the main wall area, but can vary. Therefore, consult an installation manual or the manufacturer for specifics.

Backing of this type is adequate if proper fasteners are used in a proper manner. They need to be large enough and properly piloted. Most ADA-approved bars have #14 screws included. Note that these will typically have a #3 Phillips head, not the #2 found in most household screwdrivers. Don't booger yours up with the wrong bit.

If yours doesn't have backing, or it's not of robust enough quality to support a bar itself, kits can be found which bridge the gap between the shower wall and the wall framing. Read more on that

There's no need for custom-length bars. Bars come in a range of sizes, usually on increments of 8 inches, and they can (and often should) be mounted diagonally to fit framing distances. The advantage of doing so for the user is the availability of support at varying heights. Such bars have a non-slip texture, so the angle doesn't present a problem if a person has reasonable grip strength. (If they don't, bars aren't of much use anyway.)

* As opposed to multi-panel surrounds
Comment: Great advice.    Not worth another answer but I'll throw in that most fiberglass showers do not reach the ceiling, so, you can search for studs in the drywall above the shower and drop vertical lines down the wall to where you need.  You need to be quite precise in finding the stud centers.  You can make small pilot holes in the drywall, that are easy to patch and fairly invisible even without painting.  And if you use the special mounting kit (#4 in this answer) you have flexibility to correct a small amount of error when you first drill into the fiberglass.
Comment: Bendy, crunchy, booger ... there should be a flavorful answer badge!
Comment: If the fiberglass surface is not too thin, and it's hollow behind, use [WingIts](https://www.grab-bar.com/products/the-beast-stainless-steel-grab-bar-wingits-5-screw-gbw50?variant=38990982092) anchors.
Answer: If you buy one of these, they typically come with 3" screws and basically mandate a stud. Otherwise, you wind up with injured people and a damaged shower/bathroom. Fiberglass is just not sturdy enough a material to try this any other way.

My elderly mother is coming for a visit

A better (and probably easier) solution would be a shower chair. You only need this short-term, and shower chairs are easy to source and usually not expensive (buy it online if you can). Install a handheld shower head (also cheap and easy) and she should be set for safety (the chair can be used for stability getting in and out)
Comment: Yes, I do have shower chair for her.  As for the railing… I found a YouTube video on "Solid Mount" product.   I am leaning towards doing it with Solid Mount which could be better for fiberglass shower stalls.
Answer: I had the same problem. I measured the studs and then got a custom length bar from the local box store. Not that much more and I knew they were solid. Mine were horizontal, you can place standard lengths vertical or on an angle.
Comment: You cannot simply bolt through a shower surround into studs. There's usually a gap that needs to be addressed.
Answer: The grab bar must be mounted to studs with appropriate fasteners; the bar likely comes with hardware.  Don't use anchors, you must go directly into the wood.
You may be able to find the studs with an electronic stud finder or strong magnet.  If you can't detect the studs behind the shower tile then you can find a stud next to the shower and measure over, hoping the studs are regularly spaced (usually 16").
It may be possible to determine their location on the other side of the wall.  For example, if behind the shower is a closet, find the location of the studs in the closet, measure, and record the distance from the common perpendicular wall, but don't forget to account for the thickness of the tile when you measure in the shower.
However if you do have access to the wall behind, I would recommend that you remove a section of the drywall and install 2x4s or 2x6s horizontally between studs at the appropriate height (maybe use metal angle brackets).  This will give you some flexibility (left/right) as to where you mount it, rather than trying to hit a narrow stud.
Comment: +1 for the suggestion to open up the other side of the wall to ensure that there is solid wood to anchor into.
Comment: Most fiberglass showers do not lay directly on the framing, and many have backing formed into the surround. This answer is misleading.
Comment: A large rare earth magnet on a piece is thread makes an incredibly sensitive stud finder. Just slide it around the shower enclosure and look for it to react.
Answer: Use good quality stud finder and find the studs.
That would be the only way to make it safe.
Important is to make a good seal so water does not penetrate.
If you have shower and bathtub you need two different hight or one longer one mounted diagonally.
As added on show of love, put a shower stool so she can sit while showering.
Comment: Grab bars have non-slip texture. Diagonal or vertical mounting is common and appropriate.
Comment: *put a shower stool so she can sit while showering* - and if there's space for a stool, you might not even need a grab rail. Some free-standing shower stools are designed to be used for support as well.  It will of course depend on the layout and how she needs to step in
Comment: Most fiberglass showers do not lay directly on the framing, and many have backing formed into the surround. This is not a good answer.
Comment: Diagonal? So she can try to slide down gracefully?
Comment: I got a shower chair for her.  Im thinking of setting up a diagonal railing so the lower end of the railing is about in line with her chest while she is on a sitting position.   That way she has some support when sitting down or standing up.
Comment: she will love it, was my answer good enough for you to upvote or accept


Python DBM Module for Windows?

Question: I would like to use the dbm module on my Windows machine, but it is currently only supported on Unix. http://docs.python.org/library/dbm.html
Does anyone know of a similar module with similar syntax or a workaround to get dmb functional on windows? Being able to access a database written to the hard drive much like how I code to access a dictionary would be great. Thank you for your help!
Comment: Are you using cpython on Windows?
Comment: GNUdbm and ndbm seem not supported on Windows: https://stackoverflow.com/questions/64909747/is-dbm-gnu-not-supported-on-python-3-7-windows
Answer: Actually, after more googling around, I found this:
http://docs.python.org/library/anydbm.html#module-anydbm
I've tried this on windows and it seems to be working fine =)
Comment: If you're benchmarking with Python 2 on Windows, you're in for a treat when you switch to Python 3, as dbm falls back to [dumbdbm](https://docs.python.org/3/library/dbm.html#module-dbm.dumb), which is Python's own self-proclaimedly lame dbm implementation, whereas on Python 2 it supports the much faster [Berkeley DB](https://docs.python.org/2/library/dbhash.html).

To avoid dumbdbm on Py3/Win, I've used both [LMDB](https://github.com/dw/py-lmdb) and [semidbm](https://github.com/jamesls/semidbm), and ended up writing my own workaround, [Petite](https://github.com/h5rdly/Petite-DB)
Comment: https://docs.python.org/3/library/anydbm.html: 404 Not Found. Did they remove it? How to use gnu dbm on windows?
Comment: Try this: https://docs.python.org/3/library/dbm.html
Comment: ["The anydbm module has been renamed to dbm in Python 3"](https://web.archive.org/web/20121025045609/http://docs.python.org/library/anydbm.html)
Answer: Based on the following test on a Windows 7 system using Python 2.7.2 it appears that dbhash is supported on Windows instalations.
<code>import os

import anydbm

import whichdb

file = os.curdir + '/testdbm'   # define a test file name in the current directory

d = anydbm.open(file, 'c')      # create a new database using the test file name

db_type = whichdb.whichdb(file) # get the dbm database type

print(db_type)                  # display the result

'dbhash'
</code>
Comment: This answer is obsolete. `dbhash` was removed in Python 3.
Answer: If Python 3 is of relevance, I'd go for an external k-v solution, as dumbdbm is no joy.
Some pure Python options:

semidbm - A faster alternative to dumbdbm, Python standard library only, pip and go. The one I'd go for if I want to ensure portability and availability to users.
PickleDB - Uses json to serialize data. Standrad library only, I haven't benchmarked but I suspect it's slower than semidbm because of the serialization overhead.
Petite DB - My own simple workaround using Python's zipfile module. Basic testing in the books but it's not production ready.

There are also Python wrappers to LMDB, UnQLite and SQLite4 LSM, all of which support Windows, though the SQLite4 bindings weren't tested.
The latter two are by Charles Leifer, who is both savvy with k-v stores and an avid Python developer (see Peewee).
As far as LMDB, I've tried it for a while. No complaints, but it uses a transactional model, where you can't use it dictionary-style like with other dbm's, unless you subclass/compose/submit a pull request etc.
Also, it explicitly doesn't utilize compression (see also) which was something I was interested in.
So LMDB just didn't quite fit my specific needs. It does seem to be highly capable, the bindings worked fine, and installing them was untroublesome (pip worked for me, had no need to install LMDB seperately or any nuisance to that effect).
Answer: I think anydbm on Windows will only load dumbdbm, since all the other modules appear to be Unix only. According to the Python documentation...

"The dumbdbm module is intended as a last resort fallback for the
  anydbm module when no more robust module is available. The dumbdbm
  module is not written for speed and is not nearly as heavily used as
  the other database modules."

Python DBM Module for Windows?


How to serialize Long epoch date format into date using JSONObject

Question: I have json string payload having date in epoch (long) format.But I have to convert that into yyyyMMddHHmmss format.I'm using custom serializers where I can apply that on particular field.But the serialization is not able to apply on that field.
Test.java
 private static String json = "{

          "dcCountryCode": "US",
          "orderDate": 1517855400000
        }";

    @JsonSerialize(using = CustomLongSerializer.class)
    private static Long date;

    public static void main(String[] args) {

        JSONObject obj = new JSONObject(json);

        String country = obj.getString("dcCountryCode");

        date = obj.getLong("orderDate");

        System.out.println(country);

        System.out.println(date);

    }

CustomLongSerializer.java

    package com.company;

    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.databind.SerializerProvider;
    import com.fasterxml.jackson.databind.ser.std.StdSerializer;

    import java.io.IOException;
    import java.text.SimpleDateFormat;

    // This is for Custom Date serializer
    public class CustomLongSerializer extends StdSerializer<Long> {

        protected CustomLongSerializer(Class<Long> t) {
            super(t);
        }

        protected CustomLongSerializer() {
            this(Long.class);
        }

        private static final long serialVersionUID = 1L;

        @Override
        public void serialize(Long value, JsonGenerator gen, SerializerProvider provider) throws IOException {

            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            gen.writeString(df.format(value));

        }

    }

Expected Out put in yyyyMMddHHmmss format.

But still returning epoch date format.

Can anyone help me with this.

Answer: It may be implemented in a simpler way by disabling SerializationFeature.WRITE_DATES_AS_TIMESTAMPS and setting DateFormatter in the mapper:
public class TestDate {
    private String dcCountryCode;
    private Date date;
// getters/setters
}

// test class
String json = "{\n" +
"          \"dcCountryCode\": \"US\",\n" +
"          \"date\": 1517855400000\n" +
"        }";

ObjectMapper mapper = new ObjectMapper()
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .setDateFormat(new SimpleDateFormat("yyyyMMddHHmmss"));

TestDate test = mapper.readValue(json, TestDate.class);

System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(test));

Output:
{
  "dcCountryCode" : "US",
  "date" : "20180205203000"
}

Comment: I want to make use of JSONObject. I have more fields in payload. Which I don't want to create a pojos for the json schema. I just need to convert the date field alone into "yyyyMMddHHmmss" format.
Comment: In such case I don't understand why you applied @JsonSerialize to some static field - it's better to apply to POJOs.  To convert the date field alone, you did not need any custom serializer, just this: `String strDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(date));`


CSRF Tokens vs Session Cookies

Question: AFAIK, we define CSRF as security vulnerabilities that make the user perform a user-specific action without the user's consent by using various scripts by a malicious attacker. For example, our malicious attacker convinced the user to enter the website where the following code is running to change the user's email address.
<form action="https://examplefornonsafewebsite.com/email/change" method="POST">
    <input type="hidden" name="email" value="firstname.lastname@example.com">
</form>

In such a case, if the website does not have CSRF protection, the user's email address will be changed without the user's consent as a result of an action taken by the user. My question is, "What separates the CSRF token from a session cookie?" How can the session cookie be accessed but not the CSRF token while the malicious attacker is making the user change? After all, since this is done from the user's browser, shouldn't the CSRF token be accessible as well?
Answer: A session cookie should be HttpOnly and is then not accessible via Javascript, but it is automatically included in every request to the examplefornonsafewebsite.com domain from which it was issued.1
To make the examplefornonsafewebsite.com web page safe, it must obtain an CSRF token prior to the making the POST request. This token is valid only in combination with ("is bound to") the session cookie and is obtained

either when the browser loads the <form> by navigating to https://examplefornonsafewebsite.com/email/form and this contains an <input type="hidden" name="X-CSRF-Token" value="..."/>
or by making a GET request with the Javascript command fetch("https://examplefornonsafewebsite.com/email/gettoken") and reading the CSRF token from the response body or a response header. This token must then be included in a subsequent POST request

fetch("https://examplefornonsafewebsite.com/email/change", {
  method: "POST",
  headers: {"Content-Type": "x-www-form-urlencoded"},
  body: "email@example.com&X-CSRF-Token=..."
})

The examplefornonsafewebsite.com web page can use either option to include the CSRF token when it makes an email change request.
But neither option is possible for the attacker: In the first option, the browser has already navigated to the examplefornonsafewebsite.com web page and the attacker's page is no longer involved at all.
In the second option, the attacker's page can make the fetch request, but will not be able to read the response, because this is a cross-origin (CORS) request: It is made by Javascript from the attacker's web page but goes to the different origin https://examplefornonsafewebsite.com/. Then, since the response contains no Access-Control-Allow-Origin header, the fetch request is rejected with a "TypeError: Failed to fetch" and the attacker is not able to read the CSRF token.
Importantly, if the attacker tried to obtain a CSRF token prior to the attack (by making a request to https://examplefornonsafewebsite.com/email/gettoken with their own browser), they might get one, but it would not be bound to the victim's session cookie, so it would be worthless.
To summarize: The session cookie2 cannot be accessed via Javascript, neither by an attacker nor by the legitimate web page, but will be sent by the browser regardless. The CSRF token can be obtained only by the legitimate web page, by virtue of the CORS protocol. Only by combining both do you ensure that

the email change request comes from the user's browser (otherwise it would lack the session cookie) and
the user's browser is currently visiting the legitimate web page examplefornonsafewebsite.com (otherwise the CORS protocol would prevent the CSRF token from being obtained).

The CSRF protection mechanism therefore relies on CORS.
1 This can be restricted by setting the cookie to SameSite=Strict, which prevents cross-site (although not cross-origin) request forgery attacks without the need for a CSRF protection token. But it also prevents users from navigating cross-site just to see their data. See also here.
2 This mechanism works even if the cookie in question is not a session cookie, see Should CSRF protection token be given before authenticating?
Comment: @Ali_MM, CSRF tokens are needed for HTML forms or for HTTP clients other than modern browsers (see https://stackoverflow.com/a/74833259/16462950).
Comment: Does this mean that the X-CSRF-Token is basically useless because the CORS policy is the main protection here? If there was no CORS policy, then having or not having X-CSRF-Token doesn't add any protection?

CSRF Tokens vs Session Cookies


What is a good tutorial for web app UI/UX design?

Question: I'm building a web app, but I'm not a designer, so I rely on a lightweight CSS framework to provide the basic styling and structure of different UI elements. However, I usually struggle with how to structure the web app to provide a good UX.
I googled "web app ux design" (and "ui design"), but most of the results talk about designing a web "site" not a web "app". For example, the main focus seems to be the principles of design, e.g. color/contrast, visual hierarchy, spacing, etc. What I need are things like general app layout, hub & spoke pattern, navigation, side-bars / menus, relationship between conceptual/data model and pages/screens, role-based functionality, record details vs lists/tables, bulk actions, page sections/layout, cards, modal dialogs, in-page actions, form design for simple in-page manipulation vs. complex data entry (multi-step wizards), etc.
Where can I find such a tutorial or guide? I'm willing to even pay for an online course if one is available.
Comment: Hi Khaledh, the purpose of this site is to provide answers and recommendations to UX conundrums. The reason why your question has been down-voted and has two closure votes is that it is too broad. However, your question isn't without UX merit, what you should look at is the fundamentals of what you're users are trying to achieve and THEN look at how they achieve it.
Comment: Thanks for the tip @DarrylGodden, I appreciate the feedback. Since I'm a complete noob to UX design, I needed to start with a broad question to help me narrow down my focus to more specific questions. The issue I'm facing isn't widely discussed online AFAIK, hence me turning to StackExchange.
Answer: Depending on technology is a lot of available libraries or visual systems,
for example:

Human Interface Guidelines -
https://developer.apple.com/design/human-interface-guidelines/
Material Design - https://material.io/design/

You also have ready UI libraries - for start it's good idea to use it:

https://semantic-ui.com/
https://material-ui.com/
https://designrevision.com/react-component-libraries/

If you don't experience in design You can use free ready components and create the whole system from them.
There are different strategies and methodologies, however my experience and intuition evolved a hollistic view of the project and firstly create an architecture & structure of every pages/interactions.
So at the beginning it is worth defining scopes, modules, and then later defining the details
When it comes to pure design aesthetics, you just have to watch a lot good projects.
For tutorials You can visit this article:
https://uxdesign.cc/ultimate-start-guide-for-beginner-ux-ui-designer-b848be089589
I read this few minutes ago and it's a good repository of knowledge for beggining.
Comment: Thanks Piotr. I'm familiar with several UI frameworks like Semantic and Material. However, I think they solve the problem at a _micro_ level (i.e. UI components), while I'm looking for _macro_ level design, i.e. app architecture, and the wisdom behind making certain choices in layout, navigation, workflow design, and task-oriented design. I'll give Apple's design guidelines a closer look.
Answer: I would also recommend checking out Steve Schoger's Refactoring UI work which could be really handy for you. https://refactoringui.com/
He has lots of interesting videos on youtube.
Comment: What a coincidence, I and Steve worked briefly together on the same product several years ago! Thanks for the tip about his site. I will definitely check out his tips and videos.


group generators of $(\mathbb Z_{17}-\{0\},\times)$

Question: How to find generators of $(\mathbb Z_{17}-\{0\},\times)$?
Is there a faster way to find generators than trying every element in the group?
I know that for additive group, if a number say m is relatively prime to n (in this case 17), then it's a generator of that group. Do we have something like this for multiplicative group?
Answer: Since the order of that group is a power of $2$, all you need to do is find a number that is not a quadratic residue modulo $17$
$$\left(\frac{3}{17}\right) = -1,$$
so $3$ is a generator.
Answer: You can read details about this here.  You get a generator when the order, in this case $17$, is either a prime power or twice a prime power.  There's no really good way to find a generator except trial and error; however there are $\phi(\phi(17))=8$ of them, so in this case it shouldn't take too long.
Comment: The order in this case is 16.
Comment: The order of $\mathbb{Z}_{17}$ is $17$; that was the order to which I was referring.
Comment: @vadim123 Can you explain why you have $\phi(\phi(17)) = 8 $?
Comment: @vadim123 I think I get why it's 8 now. But how do you know to this formula to find the number of quadratic nonresiduals?
Comment: You're looking for what's called a [primitive root](http://en.wikipedia.org/wiki/Primitive_root_modulo_n). $\phi$ denotes the Euler totient.  $\phi(17)=16$ and $\phi(16)=8$.


What are these little blue creatures following me?

Question: I have no idea what it is. I'm a level 12 (almost 13) monk. 4 of these little blue guys have been following me since before I defeated the Skeleton King. What are they?
Answer: That's the special effect of the Nagelring
Before patch 2.4, it was possible to get this at lvl 11. It is now a possible drop starting at level 40, wearing it summons up to 4 Fallen Lunatics (pictured below) every few seconds.
Comment: and it will run to enemy and explode, dealing quite a huge damage, very useful for early game to fight boss and farming
Comment: Se0ng11 what do you mean by "farming"? I haven't experienced farming yet.
Comment: Farming in most, if not all loot-based games like Diablo, is killing monsters as quickly and efficiently as possible to get more loot.
Comment: Additionally, due to their aid in farming, this is a great item to have Kanai's Cube absorb the effect from, if you have the Reaper of Souls expansion.