text:
Q: ANTLR 4: Using custom grammar keywords in input script I'm running into a situation where a keyword from my grammar is used in the input script where the user can essentially type anything (e.g. a variable name).  But ANTLR doesn't like this when it parses the script.
I know most languages have a set of reserved keywords that are pretty much forbidden in the source code because they get in the way of parsing.
But I thought that my grammar rules are clear enough that ANTLR wouldn't get confused.
Here's a simplified version of the grammar:
grammar test;

script : statements EOF ;

statements : statement* ;

statement : (output_statement | variable_statement) ;

output_statement : identifier ('format' column_format) ;

column_format : STRING_LITERAL;

variable_statement : identifier '=' STRING_LITERAL ;

identifier : IDENTIFIER ;

IDENTIFIER : [a-z]+ ;

STRING_LITERAL : '"' ( ~[\\\r\n"] )* '"' ;

WS : [ \t\r\n\u000C]+ -> channel(HIDDEN) ;

The following parses ok:
x = "a"
x format "str"

But this next input text does not parse:
format = "a"
format format "str"

test::script:1:0: mismatched input 'format' expecting EOF
Is there any way to structure my grammar so "format" is permitted as an identifier?
Thanks.

A: Since format is both a keyword and an identifier:
output_statement : identifier (FORMAT column_format) ;
.....
identifier : IDENTIFIER | FORMAT ;
.....
FORMAT     : 'format' ;
IDENTIFIER : [a-z]+ ;
.....


text:
Q: Text won't align under image in CSS I have been trying to follow other guides and working on it myself to see what is interfering with the text being unable to align underneth the image.
Any chance anyone has delt with a similar issue?
HTML

Some text

In the CSS the #cf img is interfering with allowing the text to align below it
CSS
#cf img {
  position:absolute;
  background-color: #bbb;
  left:0;
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
  display: block;
  margin: auto;
  width: 100%
}

Here is the code
https://jsfiddle.net/Kalilath/ry2aoxc5/1/

A: Updated for the updated question: If you want to centre an item above an absolutely positioned element, you can use the following (and make sure the parent element has position:relative as its attribute):
#cf p {
    position: absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
}

If you want to stack your images on top of each other and keep everything in your #cf container centred, use display:flex on your container.
flex-direction set to column will stack everything in your container vertically, and align-items set to center with align everything horizontally in the middle.

#cf {
  display:flex;
  flex-direction:column;
  align-items:center;
}

Some text

redpajama_set_name: RedPajamaStackExchange


text:
Q: When following 12 factor rule, where do I store configs? Here is the link 12 factor
I am confused weather if I should store values inside my app.properties file vs environment variable.
App.properties
Memory_Folder_Test = Test
Memory_Folder_Prod = Production
Memory_Folder_Dev = Development

Strong_threshold = 10
Low_Threshold = 2

Username = FirstUser
Password = PasswordSecret

So theoretically where should I put these values in? application.properties or as environment variables? If I did not read wrong the purpose of 12 factor is to remove putting values in properties file and externalize it.

A: You can store the values in application.properties file, however, spring allows you to override those values using environment variables. Hence, it is a 12 factor compliant.

A: You store the properties externally using something like spring cloud config. You then use the environment properties to define the configurations (like the url) needed to access cloud config from your applications

A: I prefer to store environment variables in files, encrypt the files and check the encrypted files into git, via blackbox: https://github.com/StackExchange/blackbox
Blackbox will handle encryption/decryption so that it makes it rather difficult to check the unencrypted creds into your repo.  Also, the way openpgp works, you can enable teams of devs to encrypt/decrypt the files.
That project is maintained by StackExchange (aka the guys who run this site).  It takes some time figuring out openpgp/gpg (which blackbox depends on), but it has been well worth it for me.  I've been using in linux and also in windows (via the windows linux subsystem).


text:
Q: Horizontal scroll and cut div I have a top bar to put in my blog :
<nav class="top-bar blog">
    STACKOVERFLOWSTACKOVERFLOWSTACKOVERFLOWSTACKOVERFLOWSTACKOVERFLOWSTACKOVERFLOWSTACKOVERFLOWSTACKOVERFLOWSTACKOVERFLOWSTACKOVERFLOWSTACKOVERFLOW
</nav>

<style type="text/css">
    .top-bar.blog {
        width: 100%;
        white-space: no-wrap;
        background: violet;
        ...
    }
    body {
        background: black;
    }
</style>

When I resize my browser window to a small size to see the horizontal bar I get this:

Which is the expected result.
When I scroll horizontally to the right here is the result:

The div is cut.
Strangely, there is the same problem on stackoverflow.com's top-bar.
How can I prevent this so the size can stay adjusted to the right part of the windows instead of being "cut"?

A: This works for me.
Set overflow:hidden width:100% and then just some paddding and margin.

A: If you don't want the top bar to move at all, you could try position: fixed, remove the width and set top, left and right positions. E.g.:
.top-bar.blog {
    position: fixed;
    top: 5px;
    left: 5px;
    right: 5px;
    height: 50px;
    white-space: no-wrap;
    background: violet;
    overflow: hidden;
}
Change the top, left, right, and height numbers to whatever you want.


text:
Q: Change the background color into three areas when we have MANY plots ggplot2 R I have the following code which produces the plot below:
ggplot(data = factor_output, aes(y=F.Difference, x=reorder(Action.Title, F.Difference), fill=Efficacy.Median)) +
  coord_flip() +
  scale_fill_gradient(low = "red", high = "green") +
  geom_bar(stat = "identity") +
  geom_point(aes(y=Factor1, colour="DarkRed"), size=3) +
  geom_point(aes(y=Factor2, colour="DarkBlue"), size=3) +
  scale_color_manual(labels = c("Factor 1", "Factor 2"), values = c("DarkRed", "DarkBlue")) +
  labs(colour="Coefficient Value") +
  annotate("rect", ymin = c(0.3, -0.3, -0.3), ymax = c(Inf, -Inf, 0.3),
           xmin = -Inf, xmax = Inf,
           alpha = 0.1, fill = c("green", "green", "orange")) +
  theme(axis.title.x = element_text(colour = "DarkGreen", size = 18),
        axis.title.y = element_text(colour = "DarkGreen", size = 18),
        axis.text.x = element_text(size = 15),
        legend.title= element_text(size = 15),
        legend.text= element_text(size = 12),
        legend.position = c(0, 1),
        legend.justification = c(0, 1),
        legend.background = element_rect(fill="transparent"),
        plot.title = element_text(colour = "DarkRed", size = 22, hjust = 0.5))

I know from other threads on stackoverflow that I need to start with empty ggplot() and then add annotate. I tried to do that and state the data and aes for each plot, but I got a lot of error messages.
Could you please let me know how I can amend the code above to send the three background areas to the back.

A: I used to get an error message, which reads: 'Error: Discrete value supplied to continuous scale.', when I tried to put annotate before the other plots. However, I managed to solve the problem by using scale_x_discrete() to specify to ggplot2 that I am using a discrete scale for the x axis.
ggplot(data = factor_output) +
  scale_x_discrete() +
  coord_flip() +
  annotate(geom = "rect", ymin = c(0.3, -0.3, -0.3), ymax = c(Inf, -Inf, 0.3),
           xmin = -Inf, xmax = Inf,
           alpha = 0.4, fill = c("LightGreen", "LightGreen", "Orange")) +
  scale_fill_gradient(low = "red", high = "green") +
  scale_y_continuous(breaks=c(-0.75, -0.5, -0.3, 0, 0.3, 0.5, 0.75)) +
  geom_bar(aes(y = F.Difference, x = reorder(Action.Title, F.Difference), fill=Efficacy.Median), stat = "identity") +
  geom_point(aes(x = reorder(Action.Title, F.Difference), y = Factor1, colour="DarkRed"), size = 3) +
  geom_point(aes(x = reorder(Action.Title, F.Difference), y = Factor2, colour="DarkBlue"), size = 3) +
  scale_color_manual(labels = c("Factor 1", "Factor 2"), values = c("DarkRed", "DarkBlue")) +
  labs(colour="Coefficient Value") +
  ggtitle("XXX") +
  xlab("XXX") +
  ylab("XXX") +
  theme_bw() +
  theme(axis.title.x = element_text(colour = "DarkGreen", size = 18),
        axis.title.y = element_text(colour = "DarkGreen", size = 18),
        axis.text.x = element_text(size = 15),
        legend.title = element_text(size = 15),
        legend.text = element_text(size = 12),
        legend.position = c(0, 1),
        legend.justification = c(0, 1),
        legend.background = element_rect(fill = "transparent"),
        plot.title = element_text(colour = "DarkRed", size = 22, hjust = 0.5))

A: Ggplot adds layers on top of each other, so if I understand your question correctly, you can solve this by putting +annotate() before +geom_point() and +geom_bar(), like this:
ggplot(data = factor_output, aes(y=F.Difference, x=reorder(Action.Title, F.Difference), fill=Efficacy.Median)) +
  coord_flip() +
  scale_fill_gradient(low = "red", high = "green") +
  annotate("rect", ymin = c(0.3, -0.3, -0.3), ymax = c(Inf, -Inf, 0.3),
       xmin = -Inf, xmax = Inf,
       alpha = 0.1, fill = c("green", "green", "orange")) +
  geom_bar(stat = "identity") +
  geom_point(aes(y=Factor1, colour="DarkRed"), size=3) +
  geom_point(aes(y=Factor2, colour="DarkBlue"), size=3) +
  scale_color_manual(labels = c("Factor 1", "Factor 2"), values = c("DarkRed", "DarkBlue")) +
  labs(colour="Coefficient Value") +
  theme(axis.title.x = element_text(colour = "DarkGreen", size = 18),
    axis.title.y = element_text(colour = "DarkGreen", size = 18),
    axis.text.x = element_text(size = 15),
    legend.title= element_text(size = 15),
    legend.text= element_text(size = 12),
    legend.position = c(0, 1),
    legend.justification = c(0, 1),
    legend.background = element_rect(fill="transparent"),
    plot.title = element_text(colour = "DarkRed", size = 22, hjust = 0.5))


text:
Q: C# building/resource/publish/create and exe file with database I was wondering how can I create the exe file for the app I made. I tried giving the exe file in the bind/debug folder together with the database (MS Access). But having an error with the filename of the mdb file, it is pointing to my directory.
{
    InitializeComponent();
    connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;
                                        Data Data Source=C:\Users\asdf\Documents\questionbank.mdb;
                                        Persist Security Info=True;
                                        Jet OLEDB:Database Password=asdfasdf";
}

And the error getting is "Windows cannot access the specified device, path, or file. You may not have the appropriate permission to access the item.

A: Put your connection string in a configuration file, eg., by createing a setting in the Settings tab when you right click on your project and go to Properties.
Hard coding your connection details, as you've done, means it cannot change when you deploy your application.


text:
Q: For loop with conditional statements not working as expected (Pandas) #Loop through example dataset
for id in df['val_id']:
        #total assigned value
        df['tot_val'] = 0
        #loop through facilities
        for fac in df['fac_id']:
            if df['product'].isin(['XL', 'CL', 'DL']).all():
                df['row'] = min(df['our_val_amt'] - df['tot_val'], df['val_against'])
            else:
                df['row'] = 0

            df['tot_val'] = df['tot_val'] + df['row']
            df['row'] = df['row'] + 1

Sample to test val_against > val_amt change
# df = pd.DataFrame(data=[["compx","xx1","yy1",424,418,"XL"],["compx","xx1","yy2",424,134,"CL"],["compx","xx2","yy3",472,60,"DL"],["compx","xx2","yy4",472,104,"CL"], ["compx", "xx3", "yy5", 490, 50, "XL"], ["compx", "xx3", "yy6", 490, 500, "CL"], ["compx", "xx3", "yy7", 490, 200, "DL"], ["compx", "xx4", "yy8", 510, 200, "CL"], ["compx", "xx4", "yy9", 510, 300, "CL"], ["compx", "xx4", "yy10", 510, 50, "XL"]], columns=["name","val_id","fac_id","our_val_amt","val_against","product"])

I am trying to in Pandas double loop through the 'val_id' and 'fac_id' column and create a new field from the following conditions.
1.Within each 'val_id' loop if 'product' == 'CL' then min of 'val_against' and 'our_val_amt' e.g. min( val_against (134), our_val_amt (424)) therefore 'NEW FIELD' = 134.  Also if the sum of NEW FIELD exceeds "our_val_amt", then subtract it from "our_val_amt". e.g. for val_id "xx4", (200 + 300 + 50) = 550 which exceeds our_val_amt=510, so NEW FILED = 550 - 510 = 10.
2.If product != 'CL' and is in the same 'val_id' group. The remainder to be subtracted from 'our_val_amt' to be inserted in 'NEW FIELD'. e.g 'our_val_amt' (424) - from step 1 (134) = 290. This inserted above 'NEW FIELD'.
3.Repeat steps for val_id xx2. NEW FIELD calculation for CL = 104 and XL = 472 - 104 = 368.
Dataset with computed fields labeled with **
|  name | val_id | fac_id  | our_val_amt | val_against | product | **row** | **totval**|**Field Want**
| compx |  xx1   |  yy1    |   424       |    418      |   XL    |   290   |     0     |   290
| compx |  xx1   |  yy2    |   424       |    134      |   CL    |   134   |    134    |   134
| compx |  xx2   |  yy3    |   472       |    60       |   DL    |   0     |     0     |   368
| compx |  xx2   |  yy4    |   472       |    104      |   CL    |   104   |   104     |   104
| compx |  xx3   |  yy5    |   490       |    50       |   XL    |
| compx |  xx3   |  yy6    |   490       |    500      |   CL    |
| compx |  xx3   |  yy7    |   490       |    200      |   DL    |
| compx |  xx4   |  yy8    |   510       |    200      |   CL    |
| compx |  xx4   |  yy9    |   510       |    300      |   CL    |
| compx |  xx4   |  yy10   |   510       |    50       |   CL    |

Expected Output
|  name | val_id | fac_id  | our_val_amt | val_against | product | new field |
| compx |  xx1   |  yy1    |   424       |    418      |   XL    | 290       |
| compx |  xx1   |  yy2    |   424       |    134      |   CL    |  134      |
| compx |  xx2   |  yy3    |   472       |    60       |   DL    | 368       |
| compx |  xx2   |  yy4    |   472       |    104      |   CL    |  104      |
| compx |  xx3   |  yy5    |   490       |    50       |   XL    | 0         |
| compx |  xx3   |  yy6    |   490       |    500      |   CL    |  490      |
| compx |  xx3   |  yy7    |   490       |    200      |   DL    | 0         |
| compx |  xx4   |  yy8    |   510       |    200      |   CL    |  200      |
| compx |  xx4   |  yy9    |   510       |    300      |   CL    |  300      |
| compx |  xx4   |  yy10   |   510       |    50       |   CL    |  10       |

The **row** and ** totval** are fields i created trying to create the field that i want with the logic above.
I've tried grouping the variables together and having the 'product' as columns but unfortunately i receive 6000+ columns and have no idea on how to compute the calculation for this scenario.
I've also attempted to loop through but received incorrect outputs / errors
error: Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

A: You can solve this in 2 steps:

*

*In Step 1, compute the new field values for "CL". Following solution assumes 0 value for new_field if computing condition is not met.

*In Step 2, process non-CL records and use values computed in step 1. To handle case where multiple "CL" records may be present in same val_id group, the following code sums them up.

The comments are added before each step to explain what it does.
df = pd.DataFrame(data=[["compx","xx1","yy1",424,418,"XL"],["compx","xx1","yy2",424,134,"CL"],["compx","xx2","yy3",472,60,"DL"],["compx","xx2","yy4",472,104,"CL"],
                        ["compx","xx3","yy5",490,50,"XL"],["compx","xx3","yy6",490,500,"CL"],["compx","xx3","yy7",490,200,"DL"],
                        ["compx","xx4","yy8",510,200,"CL"],["compx","xx4","yy9",510,300,"CL"],["compx","xx4","yy10",510,50,"CL"],
                        ], columns=["name","val_id","fac_id","our_val_amt","val_against","product"])

# Compute tuple of "our_val_amt", "val_against" and "product" for easy processing as one column. It is hard to process multiple columns with "transform()".
df["the_tuple"] = df[["our_val_amt", "val_against", "product"]].apply(tuple, axis=1)

def compute_new_field_for_cl(g):
  # df_g is a tuple ("our_val_amt", "val_against", "product") indexed as (0, 1, 2).
  df_g = g.apply(pd.Series)
  df_g["new_field"] = df_g.apply(lambda row: min(row[0], row[1]) if row[2] == "CL" else 0, axis=1)
  df_g["cumsum"] = df_g["new_field"].cumsum()
  df_g["new_field"] = df_g.apply(lambda row: 0 if row["cumsum"] > row[0] else row["new_field"], axis=1)
  df_g["max_cumsum"] = df_g["new_field"].cumsum()
  df_g["new_field"] = df_g.apply(lambda row: row[0] - row["max_cumsum"] if row["cumsum"] > row[0] else row["new_field"], axis=1)
  return df_g["new_field"]

# Apply above function and compute new field values for "CL".
df["new_field"] = df.groupby("val_id")[["the_tuple"]].transform(compute_new_field_for_cl)

# Re-compute tuple of "our_val_amt", "new_field" and "product".
df["the_tuple"] = df[["our_val_amt", "new_field", "product"]].apply(tuple, axis=1)

def compute_new_field_for_not_cl(g):
  # df_g is a tuple ("our_val_amt", "new_field", "product") indexed as (0, 1, 2).
  df_g = g.apply(pd.Series)
  result_sr = df_g.where(df_g[2] != "CL")[0] - df_g[df_g[2] == "CL"][1].sum()
  result_sr = result_sr.fillna(0) + df_g[1]
  return result_sr

# Apply above function and compute new field values for "CL".
df["new_field"] = df.groupby("val_id")[["the_tuple"]].transform(compute_new_field_for_not_cl)

df = df.drop("the_tuple", axis=1)

print(df)

Output:
    name val_id fac_id  our_val_amt  val_against product  new_field
0  compx    xx1    yy1          424          418      XL      290.0
1  compx    xx1    yy2          424          134      CL      134.0
2  compx    xx2    yy3          472           60      DL      368.0
3  compx    xx2    yy4          472          104      CL      104.0
4  compx    xx3    yy5          490           50      XL        0.0
5  compx    xx3    yy6          490          500      CL      490.0
6  compx    xx3    yy7          490          200      DL        0.0
7  compx    xx4    yy8          510          200      CL      200.0
8  compx    xx4    yy9          510          300      CL      300.0
9  compx    xx4   yy10          510           50      CL       10.0


text:
Q: Access violation at adress... Собственно говоря, вот элемент кода, ошибка при попытке выполнить сроку   setlength(masofFD2, fv2);
procedure FromTo (var Count:integer; var arrofAB : array of string; var arofd : array of string; var Steps : array of integer; var fV : integer; var masofFD : array of integer);
  var
    f2,fv1,q,stt,i,ij,ii,j,jj,ste : integer;
    //// steef = f  stte = f2
    fv2,ff : integer;
    arFr1 : array of integer;
    arTo1 : array of integer;
    foto : integer;
    va1, fromE : boolean;
    ZakS, PosS : ReString;
    stepsV : array of integer;
     masofFD2 : array of integer;
     dpvr : boolean;
     dpvrsh : integer;
     ffv : integer; /// êîë-âî ëèíèé íà êàæîì øàãå.
  begin
  dpvrsh := 0;
  ffv := 0;
  dpvr := false;
  dopver := 430000;
  va1 := false;
  fromE := false;
  setlength(arFr1, count*2);
  setlength(arTo1, count*2);
  foto := 0;
  ff := fv;
  fv2 := fv;
  f2 := 0;
  ste:=0;
  f := 0;
  stt :=0;
  q:=0;
  fv1:=fv;
  setlength(masofFD2, fv);
  for i:=0 to fv1 do
  masofFD2[i]:= masofFD[i];
  setlength(arrofB, Count*2);
  setlength(ZakS, Count*2);
  setlength(PosS, Count*2);
  setlength(arFrom, Count*2);
  setlength(arTo, Count*2);
  setlength(stepsV, count*2);
    for i:=0 to length(arofd)-1 do
    begin
    ZakS := D1(arofd[i]);
    if stt = fV1 then begin
    stepsV[q] := ffv;
    ffv := 0;
     inc(q);
     fv1 := DeleteAndSort(masofFD2, arFr1, arTo1, foto, fv2);
     foto :=0;
     fv2 := fv2 + fv1;
     setlength(masofFD2, fv2);
     for ij:=0 to fv1-1 do begin
      masofFD2[ff]:= masLL[ij];
      ff := ff + 1;
     end;
     f := 0;
     stt:= 0;
    end;

    inc(stt);
      for ii:=0 to st1-1 do
      begin
      if ZakS[ii] = '~' then continue;
      for j:=0 to length(arrofAB)-1 do begin
        PosS := D(arrofAB[j]);
       for jj:=0 to st-1 do  begin
       if PosS[jj] = '~' then continue;
       if ZakS[ii] = PosS[jj] then
        if fromE = false then
        begin
          fromE := true;
          f := j+1;
          arFrom[ste] := f;
          arFr1[foto] := f;
          ffv := ffv + 1;
          if arFrom[ste-1] = arFrom[ste] then
          begin
          dpvrsh := dpvrsh  + 1;
          dpvr := true;
          dopVer:= dopVer+1;
          va1 := true;
          arFrom[ste-1] := dopVer;
          arFr1[foto-1] := dopVer; end;
        end
        else
        begin
          fromE :=false;
          f2 := j+1;
          arTo[ste] := f2;
          arTo1[foto] := f2;
          if (arTo[ste-1] = arTo[ste]) and (va1) then begin arTo1[foto] := dopVer; arTo[ste] := dopVer; va1 := false; end;
          arrofB[ste] := ZakS[ii];
          if ii>0 then
          if ZakS[ii-1] = '~' then arrofB[ste] := ZakS[ii-1]+ZakS[ii];
          ste := ste +1;
          foto := foto + 1;
          f := f+1;
          end;
          end;
        end;
       end;
    end;
    RepAndInv(arrofB);
    if (dpvr) then
    drawdopV(dpvrsh);
    drawLine(arFrom, arTo, cordinateX, cordinateY);
  end;

Никак не могу понять, почему возникает ошибка (возникает на конкретном шаге, т.к.
когда
masofFD2 = ('1','4','3','8');

а
fv2  = 9;

p.s. глобальные
    var
      dopVer : integer;
      smewpripost : integer; /// Ñìåùåíèå ïðè ïîñòðîåíèè âåðøíè
      masALLB : array of integer;
      iformasallb : integer;
      cordinateX : array of integer;
      cordinateY : array of integer;
      f,l, yV, iii : integer;
      arofLb : array of TLabel;
      arrofB : array of string; /// Ôàêòû ( òî ÷òî ïèøåì íà äóãàõ
      arFrom : array of integer;
      arTo : array of integer;
      arofLbDis : array of TLabel;
      arofIm : array of TImage;
      arofX : array of integer;
      arrofIDis : array of string;
      arofY : array of integer;
      txfF : array of string;
      txfL : array of string;
      arrd : array of string;
      masLL : repetedi; // ìàññèâ âåðøèí íà êàæäîì øàãå.
      IFB,st, st1 : integer;
      arrofDis : array of string;

Вот функция deleteandsort ( p.s. Спасибо за ответы )
function DeleteAndSort(masF : array of integer; masA : array of integer;var masB : array of integer; var ste,count : integer):integer;/// Сортирует и удаляет повторяющиеся элементы
  var
    n : integer;
    ii : integer;
    i : integer;
    j : integer;
    elem : integer;
    st : integer;
    masL : array of integer;
    masofNS : array of integer;
  begin
  setlength(masofNS, ste*2);
  setlength(masL, ste*2);
  st:=0;
  elem :=0;
    for i:=0 to count-1 do
     begin
       elem := masF[i];
       for ii:=0 to ste-1 do
        begin

      if elem = masA[ii]
      then masA[ii] := 0;
      if elem = masB[ii]
      then masB[ii] := 0;
    end;
 end;
 for i:=0 to ste-1 do
  begin
    if masA[i] <> 0 then
      begin
        masL[st]:= masA[i];
        st := st + 1;

      end;
     if masB[i] <> 0 then
      begin
        masL[st]:= masB[i];
        st := st + 1;
      end;
  end;
  masLL := DeleteRepeted(masL,st);
  n := length(masLL);
  masLL := DeleteRepeted(masLL, n);
  // Можно вписать фукцию для отрисовки вершин
  drawaLLV(masLL);
  //
  result := length(masLL);

end;
A: Если ошибочка в цикле вылетает,
  fv1:=fv;
  setlength(masofFD2, fv);
  for i:=0 to fv1 do
    masofFD2[i]:= masofFD[i];

то я бы решил что дело в том что переменная fv <> Length(masofFD)
Попробуйте включить проверку на границы и отлавливайте RangeException? И как то очень сложно у Вас - я бы архитектуру бы поменял бы. И подразбил бы на методы. И сократил бы количество переменных раз в десять минимум.
Да, ещё можете в дебагере по адресу по которому аксесс виолайшен лезет посмотреть в каком массиве это происходит.
P.S.
А не ту строчку посмотрел :-)
Если именно падает на установке длинны массива - то проверьте значение у переменной fv2  - может отрицательное вдруг?
A: пишу на тот случай если автор вопроса все еще не нашел ответа на свой вопрос... и не отчаялся его искать...:)
во первых...
возможно опечатка автора вопроса...

masofFD2 : array of integer;
Никак не могу понять, почему возникает
ошибка (возникает на конкретном шаге,
т.к. когда masofFD2 =
('1','4','3','8');

во вторых...
попытаюсь описать последовательность "интересных" строк кода, из-за которой setlength(masofFD2, fv2) ругается.
в функции DeleteAndSort используешь переменную ste, она же при вызове является переменной foto, которая
foto := 0;

вернувшись к функции DeleteAndSort, обратим внимание на участок кода:
for ii:=0 to ste-1 do begin
    if elem = masA[ii] then
        masA[ii] := 0;
    if elem = masB[ii] then
        masB[ii] := 0;
end;

т.е. здесь ii:= 0 to -1,... и куда запишем значение 0? masA[-1]?masB[-1]?
та же проблема в следующем цикле for, который формирует masL,
далее она используется (кстати setlength(masL, ste *2) и для чего в функции masofNS):
masLL := DeleteRepeted(masL,st);

где masLL глобальная переменная типа repetedi (repetedi??)
и результат функции
result := length(masLL)

который влияет на устанавливаемую длину masofFD2
fv1 := DeleteAndSort(masofFD2, arFr1, arTo1, foto, fv2)
fv2 := fv2 + fv1;
setlength(masofFD2, fv2);

p.s. не увидел ни одного try_except`а
p.p.s. желательно вначале тела функции дать ей значение по умолчанию (result:=0)*
p.p.p.s. много переменных
A: setlength если с 2умя значениями, то он первую переменную требует в формате string
если с 3емя значениями (с целью установить длину массива) то нужно указывать 3 значения)


text:
Q: how to print array in underscore.js template? I am using underscore.js's templating library, and I am not sure how to go about using a logic inside of a template. for example, I would like to print an array of tags in a template. What is the best approach for this?
Javascript:
bunny_data = {
  name: "sprinkles",
  age: 1,
  tags: ['fuzzy','wuzzy']
};

bunny_view = $("#bunny-template").html();
$(body).append(_.template(bunny_view,bunny_data));

Template:

A: It looks like you are not setting bunny_data properly in your JavaScript.
Instead of:
$(body).append(_.template(bunny_view,bunny_data));

Try:
$(body).append(_.template(bunny_view, { bunny_data: bunny_data }));

Print the data in your template (notice I removed the space after % in <%= name %>):

Hopefully that helps.

A: Also join will do the trick, so in html you'll have

<%= tags.join('

') %>

Check it at jsFiddle.

A: You don't need to encapsulate bunny_data as @Ken suggests, you were on the right track. Whether or not you want to call _. functions or just use plain Javascript constructs is up to you, but there's no built-in flow constructs in Underscore templates, to do that you just embed code (you might want to look into eco or Mustache or something if you want that).
My example looks like this (almost the same as you own):

with the following Javascript:
bunny_data = {
  name: "sprinkles",
  age: 1,
  tags: ['fuzzy','wuzzy']
};

bunny_view = $("#bunny-template").html();
$(body).append(_.template(bunny_view, bunny_data));

You can verify that it runs here.
(On a personal preference note, I'm a heavy user of all of Underscore except the templates for this reason, I'm not comfortable with the amount of code you must put in them if you have a more complicated use case).


text:
Q: How to make the entire menu appear when hovering over a single menu item? I am trying to make the entire menu including submenu items for every menu item appear whenever I hover over one of the menu items. This is a menu design popular in Korea but I cannot find an explanation online on how to do it. Can anyone offer some advice or pointers on how to do this? Thank you.
This is one of the websites that uses the design I mention: https://www.saga121.com/

A: a sample example.
hover over list 2,appear submenu.

li{
  float:left;
  list-style:none;
  width: 30px;
  margin: 10px;
  text-align: center;
}

.ul2{
  display:none;
}

.li2{
  cursor: pointer;
}

.li2:hover .ul2{
  display:block;
}

1

2

3

4


text:
Q: sending xcode application to a friend Hey, although i am not done with my application and have alot of learning to do, i want to know is it possable to send it via email to a friend?
i have tried to send something very simple to just show my friend what i'm doing.
in gmail i composed a message and attached a file, "my project" but it said something about could not send because firewall or something.. so i made sure it was http: and not https, still no luck.. do i have to activate or publish my project to send it? and if so how?
i thought after you clicked build and run in xcode, that was the finished project, save to desktop.. it opens when i click it from desktop just cant send it.. please help.
thanks in advanced!!!

A: It may be too big to send. Did you zip it? Just share it via Dropbox.


text:
Q: Can not get value from API after insert the data into database I created an api for an web message-board application. When I click submit, the data is inserted into the database, then show the list of result in the page. Why I can not get the the create time on the page? If I want to get the create time, I have to press reload page and the create time would show on the page. Is there any part of the API should be revised? Thank you!

const siteKey = 'oscar';
const loadMorebtn = "<button class='load_btn btn'>Load More</button>";
const msgSection = $('.msg_section');
let lastId = null;
let isEnd = false;

function encodeHTML(input) {
  return input.replace(/\&/g, '&')
    .replace(/\</g, '<')
    .replace(/\>/g, '>')
    .replace(/\"/g, '"')
    .replace(/\'/g, ''')
    .replace(/\//g, '/')
}

function appendMsgToDOM(container, msg, isPrepend) {
  const htmlContent = `

${encodeHTML(msg.nickname)}

${encodeHTML(msg.content)}

${msg.created_at}

  `
  if (isPrepend) {
    container.prepend(htmlContent);
  } else {
    container.append(htmlContent);
  }
}

// Only for get message
function getMsgsAPI(siteKey, before, cb) {
  let url = `http://localhost/w12/hw1/api_message.php?site_key=${siteKey}`;
  if (before) {
    url += '&before=' + before
  }
  $.ajax({
    url,
  }).done((data) => {
    cb(data);
  })
}

function getMsgs() {
  $('.load_btn').hide();
  if (isEnd) return;
  getMsgsAPI(siteKey, lastId, (data) => {
    if (!data.result) {
      alert(data.message);
      return;
    }
    const messages = data.messages;
    for (let msg of messages) {
      appendMsgToDOM(msgSection, msg)
    }

    if (messages.length === 0) {
      isEnd = true
    } else {
      lastId = messages[messages.length - 1].id;
      msgSection.append(loadMorebtn)
    }
  })
}

$(document).ready(() => {
  getMsgs();
  msgSection.on('click', '.load_btn', () => {
    getMsgs();
  })

  $('.add_msg_form').submit((e) => {
    e.preventDefault();
    const newMsgData = {
      'site_key': 'Oscar',
      'nickname': $('input[name=nickname]').val(),
      'content': $('textarea[name=content]').val()
    };

    $.ajax({
      type: 'POST',
      url: 'http://localhost/w12/hw1/api_add_message.php',
      data: newMsgData
    }).done(function (data) {
      if (!data.result) {
        alert(data.message);
        return;
      }
      $('input[name=nickname]').val('');
      $('textarea[name=content]').val('');
      appendMsgToDOM(msgSection, newMsgData, true);
    })
  });
})

API for showing the data
<?php
  require_once('./conn.php');

  // Make sure the format of response is json
  header('Content-type:application/json;charset=utf-8');
  // CORS
  header('Access-Control-Allow-Origin: *');

  if(empty($_GET['site_key'])) {
    $json = array(
      'result'=>false,
      'message'=>'Please input the site_key in URL'
    );
    // covert the response to json format
    $response = json_encode($json);
    echo $response;
    die();
  }

  $site_key = $_GET['site_key'];

  $sql = "SELECT * FROM oscar_msgboard WHERE site_key = ? " .
    (empty($_GET['before'])? '':'and id < ?') .
    " ORDER BY id DESC LIMIT 5";
  $stmt = $conn->prepare($sql);
  if(empty($_GET['before'])) {
    $stmt->bind_param('s', $site_key);
  } else {
    $stmt->bind_param('si', $site_key, $_GET['before']);
  }
  $result = $stmt->execute();
  if(!$result) {
    $json = array(
      'result'=>false,
      'message'=>'fail to connect to the server'
    );
    // covert the response to json format
    $response = json_encode($json);
    echo $response;
    die();
  }

  $result = $stmt->get_result();
  $messages = array();
  while($row = $result->fetch_assoc()) {
    array_push($messages, array(
      'id'=>$row['id'],
      'nickname'=>$row['nickname'],
      'content'=>$row['content'],
      'created_at'=>$row['created_at']
    ));
  }
  $json = array(
      'result'=>true,
      'messages'=>$messages
    );
    $response = json_encode($json);
    echo $response;
?>

API for insert the data
<?php
  require_once('./conn.php');

  // Make sure the representation of response is json
  header('Content-type:application/json;charset=utf-8');
  header('Access-Control-Allow-Origin: *');

  if(empty($_POST['nickname'])|| empty($_POST['site_key']) || empty($_POST['content'])) {
    $json = array(
      'result'=>false,
      'message'=>'Please input a message'
    );
    // covert the response to json format
    $response = json_encode($json);
    echo $response;
    die();
  }

  $nickname = $_POST['nickname'];
  $site_key = $_POST['site_key'];
  $content = $_POST['content'];

  $sql = "INSERT into oscar_msgboard (site_key, nickname, content) values (?, ?, ?)";
  $stmt = $conn->prepare($sql);
  $stmt->bind_param('sss', $site_key, $nickname, $content);
  $result = $stmt->execute();
  if(!$result) {
    $json = array(
      'result'=>false,
      'message'=>'fail to connect to the server'
    );
    // covert the response to json format
    $response = json_encode($json);
    echo $response;
    die();
  }

  $json = array(
      'result'=>true,
      'message'=>'Success!'
    );

  $response = json_encode($json);
  echo $response;
?>


text:
Q: Best way to group strings according to action With "Best Way" I mean, maybe, without many If, clean code.
I have a function that receives as parameters (string currentVersion, string action)
and it should return a string versionToBe = "";
For action = "installOldVersion"
-------------if "currentVersion"----------------: -------------OldversionToInstall--------------

*

*"windows10(pro)", "windows10(pro)(education)" : "windows81(pro)"

*"windows10(enterprise)", "windows10(enterpise)(lstb)" : "windows81(enterprise)"

*"windows7(home)", "windows7(home)(basic)", "windows7(basic)", "windows7": "windowsVista(starter)"

*"windowsXP(starter)", "windowsXP(starter)(home)", "windowsXP(home)", "windowsXP": "windows2000(professional)"

*"windowsNT(workstation)", "windowsNT": "windows95(sp1)"

For action = "installNewVersion"
-------------if "currentVersion"----------------: -------------NewVersionToInstall--------------

*

*"windows81(pro)", "windows81(pro)(education)" : "windows10(pro)"

*"windows81(enterprise)", "windows81(enterprise)(education)" : "windows10(enterprise)"

*"windowsVista(starter)", "windowsVista(starter)(package)", "windowsVista(package)", "windowsVista": "windows7(home)"

*"windowsVista(starter)", "windowsVista(starter)(praok)", "windowsVista(praok)", "windowsVista": "windowsXP(starter)"

*"windows95(sp1)", "windows95(sp1)(versionE)", "windows95": "windowsNT(workstation)"

So,for example, everytime the string name comes like: "windows10(pro)" or "windows10(pro)(education)" it should return: "windows81(pro)".
I know this can get done with lots of if like:
if (version.Equals("windows10(pro)") || version.Equals("windows10(pro)(education)"))
            {
                versionToBe = "windows81(pro)";
            }

and the same for the rest of them, anding with 10 If statements in Total.
But If there's a better way to do it, I'd want to know.
Another restriction, or other thing to consider:

*

*if the action is "installOldVersion", versionToBe is OldversionToInstall,
            and if the action is "installNewVersion", versionTobe would be NewVersionToInstall.

A: You could create a list of objects with CurrentVersion, Old Version and New Version and then extract the one you want from the list.
Example Instruction Class Definition
public class VersionInformation
{
    public string CurrentVersion {get; set;}
    public string NewVersion {get; set;}
    public string OldVersion {get; set;}
}

then in your program, have a list of them, either hard coded or loaded from file or whatever datastore you want and do your version check as follows:
private List<VersionInformation> _versionInformation = //Load your list from wherever;

public void DoVersionCheck(string version)
{
    var currentversionInfo = _versionInformation.Single(x=> x.CurrentVersion == version);

    //Do Whatever you want with the upgrades and downgrades here based on whatever action you are doing
}

A: Set yourself up a dictionary and perform a lookup.
As an exercise for the reader:

*

*You could drive the dictionary contents from some configuration or other...even from a database if you want.

*You'd presumably want to set up your dictionary as a static and initialize it only once.

*You'll want some handling for when there is no dictionary entry - you don't specify a default in your question.
Dictionary, string> ActionMatrix = new Dictionary, string>();
ActionMatrix.Add(Tuple.Create ("windows10(pro)", "installOldVersion"), "windows81(pro)");
ActionMatrix.Add(Tuple.Create ("windows10(pro)(education)", "installOldVersion"), "windows81(pro)");
ActionMatrix.Add(Tuple.Create ("windows10(enterprise)", "installOldVersion"), "windows81(enterprise)");
ActionMatrix.Add(Tuple.Create ("windows10(enterpise)(lstb)", "installOldVersion"), "windows81(enterprise)");
// etc
ActionMatrix.Add(Tuple.Create("windows81(pro)", "installNewVersion"), "windows10(pro)");
ActionMatrix.Add(Tuple.Create("windows81(pro)(education)", "installNewVersion"), "windows10(pro)");
ActionMatrix.Add(Tuple.Create("windows81(enterprise)", "installNewVersion"), "windows10(enterprise)");
ActionMatrix.Add(Tuple.Create("windows10(enterpise)(education)", "installNewVersion"), "windows10(enterprise)");
// etc
public string VersionToBe (string currentVersion, string action)
{
    return ActionMatrix[Tuple.Create(currentVersion, action)];
}

A: A simple object with it's own list should do the trick and is visually better to follow.
    public class VersionData
    {
        private static List<VersionData> VersionDatas { get; set; } = new List<VersionData>()
        {
            new VersionData( "OldversionToInstall", new [] {"windows10(pro)", "windows10(pro)(education)" }.ToList(), "windows81(pro)" ),
            new VersionData( "OldversionToInstall", new [] {"windows10(enterprise)", "windows10(enterpise)(lstb)" }.ToList(), "windows81(enterprise)" )
        };

        public string Action { get; set; } = "";
        public List<string> CurrentVersions { get; set; } = new List<string>();
        public string Version { get; set; } = "";

        public VersionData(string action, List<string> currentVersions, string version)
        {
            Action = action;
            CurrentVersions = currentVersions;
            Version = version;
        }

        public static string GetVersion(string action, string currentVersion)
        {
            return VersionDatas.FirstOrDefault(o => o.Action == action && o.CurrentVersions.Any(x => x == currentVersion)).Version;
        }
    }

and to call it's as simple as :
var oldVersion = VersionData.GetVersion("OldversionToInstall", "windows10(enterpise)(lstb)");


text:
Q: 4-layer PCB from Stackup manager but inner layers are not used I am trying to arrange for fabrication of a design which is set up for 4 layers in Altium. But the 2 middle layers in this stack up are not used at all. In the generated Gerber files for these inner layers (*.G1 and *.G2), both files have a size of 1 kB.
When I sent it to the fabrication company (PCBway), it was mentioned to me that these files are not recognised at all and was asked if I only needed a 2-layer PCB. My stackup is described below:

(This stackup is taken from the following template: https://s3.amazonaws.com/mfprodpublic/datasheets/MacroFab+Stackup+Report.pdf)
Would it be okay to just remove the 2 middle layers and go with a 2-layer PCB in this scenario? Or is there anything else I need to check other than knowing that no vias make use of the inner layers.

A: Yes, you can submit the job as 2 layers with the appropriate overall thickness.
As was mentioned, you could modify the Altium stackup to match what you really are doing, to avoid confusion down the road.

A: Depends if you used controlled impedance.
In this case the 4-layer preset from Altium included Power Planes by default in inner layers. Altium 2D solver calculates the impedance based on spacing between outer and inner layers (0.23mm in your case). If you have controlled impedance traces then you will need to stick with 4 layers (or go for 2 layers but change the trace width for 50ohms). Then what you need to do after routing traces is to change the setting for the inner layer to "signal" in the stackup manager and place polygons associated to GND nets.
If you don't use any kind of high speed circuitry and you have a complete GND plane on bottom layer (without any tracks routed on) then you will be fine with 2 layers.


text:
Q: Concatenate tensors of different rank into a single tensor I'm looking to feed an autoencoder my features, as both training and target data. Majority of the features have rank 1; are a single column of values like [1,2,3,4]. Some have been put through one hot encoding so the tensors are of rank 2 and have X columns, with X being the number of categorical values in the one hot encoder, so something like:
['a', 'a, 'b', c'] -> [[1,0,0], [1,0,0], [0,1,0], [0,0,1]]

For some reason keras's Model.fit don't accept y values if the training data are generators or datasets. So I have to provide my training data as a tuple of (features, targets), and in this case targets=features, but at the same time, features is a dictionary of tensors so I must concatenate all of the tensors in features into a single tensor.
I can do tf.concat across all of my feature columns except the one-hot encoded columns, which have rank 2 (instead of 1). How can I somehow turn the one-hot encoded features in X individual tensors and then concat them together?

Same issue here where the OP solved his issue using tf.concat, but I can't do that here.

A: I was trying to comment your question to ask for a couple of details, but I can't do that because I don't have reputation score (I am new to stack overflow and this is my first post ever). So I will try to explain based on what I understood of your problem - hope it helps.
You can use Pandas to hot-encode your categorical features.
Example Dataset
import pandas as pd
import random
import numpy as np

dataset = {'feature_A': np.random.randint(10, size=10),
           'feature_B': np.random.randint(10, size=10),
           'feature_C': np.random.randint(10, size=10),
           'categorical_feature': np.array([chr(97 + random.randint(0, 2)) for i in range(10)])}

print(dataset)

{'feature_A': array([6, 8, 2, 0, 4, 8, 6, 4, 3, 8]),
 'feature_B': array([0, 6, 8, 6, 7, 3, 4, 6, 1, 6]),
 'feature_C': array([0, 7, 7, 3, 7, 4, 0, 3, 2, 7]),
 'categorical_feature': array(['a', 'a', 'c', 'b', 'c', 'c', 'a', 'a', 'c', 'c'], dtype='<U1')}

Pandas DataFrame
Transform the dataset into a Pandas DataFrame
df = pd.DataFrame(dataset)
print(df)

   Feature_A  Feature_B  Feature_C Categorical_Feature
0          1          9          9                   e
1          9          9          8                   c
2          5          8          3                   c
3          3          5          7                   c
4          9          8         10                   d
5          6          9          6                   c
6          1          4          5                   d
7          9          5          2                   e
8          3          9          2                   c
9          3          8         10                   a

One-hot & concatenate
One-hot encode the categorical features and concatenate to the main DataFrame (and drop original categorical feature column)
df = pd.concat((df, pd.get_dummies(df['categorical_feature'])), axis=1).drop('categorical_feature', axis=1)

print(df)

   feature_A  feature_B  feature_C  a  b  c
0          0          0          1  0  0  1
1          5          7          0  0  0  1
2          9          2          6  0  1  0
3          1          1          4  0  0  1
4          5          8          8  0  0  1
5          9          1          8  1  0  0
6          5          6          8  1  0  0
7          9          5          0  1  0  0
8          9          4          5  1  0  0
9          8          3          5  1  0  0

NumPy array
Then you can simply get the values of the DataFrame as a numpy array by using the attribute .values. Each row now is one training example that comprises of all the value features + the categorical features as hot encoded vector.
You can use the numpy array directly into your model or, if you wish, you can also transform it into tensorflow tensor by using tf.data.Dataset.from_tensor_slices().
dataset = df.values

print(dataset)

array([[0, 0, 1, 0, 0, 1],
       [5, 7, 0, 0, 0, 1],
       [9, 2, 6, 0, 1, 0],
       [1, 1, 4, 0, 0, 1],
       [5, 8, 8, 0, 0, 1],
       [9, 1, 8, 1, 0, 0],
       [5, 6, 8, 1, 0, 0],
       [9, 5, 0, 1, 0, 0],
       [9, 4, 5, 1, 0, 0],
       [8, 3, 5, 1, 0, 0]], dtype=int32)


text:
Q: I have found a system of 3 variables that lead to a quadratic equation, so how do I find the answer?/ $$p^2 + q^2 = 81$$
$$p^2 + (q-x)^2 = 225$$
$$(p-x)^2 + q^2 = 144$$
So these are the 3 equations.

A: Let $(p,q)=9(\cos t,\sin  t)$, then
\begin{align}
  81+x^2-18x\sin t &= 225 \\
  81+x^2-18x\cos t &= 144 \\
  (18x)^2 &= (x^2-144)^2+(x^2-63)^2 \\
  0 &= 2x^4-738x^2+24705 \\
  x &= \pm 3\sqrt{\frac{41 \pm 3\sqrt{119}}{2}} \\
  p &= 9\cos t \\
  &= \frac{x^2-63}{2x} \\
  q &= 9\sin t \\
  &= \frac{x^2-144}{2x}
\end{align}

A: \begin{align}
p^2+q^2 &= 81
\tag{1}\label{1}
,\\
p^2+q^2-2qx+x^2 &= 225
\tag{2}\label{2}
,\\
p^2-2px+x^2+q^2 &= 144
\tag{3}\label{3}
.
\end{align}
Subtract \eqref{1} from \eqref{2} and \eqref{3}
to get $p$ and $q$ in terms of $x$,
\begin{align}
p &= \tfrac12\,\frac{x^2-63}x
\tag{4}\label{4}
,\\
q &= \tfrac12\,\frac{x^2-144}x
\tag{5}\label{5}
,
\end{align}
then substitute \eqref{4} \eqref{5} into \eqref{1}
to get biquadratic equation in $x$
\begin{align}
2\,(x^2)^2-738\,x^2+24705
&=0
,
\end{align}
which gives
\begin{align}
x^2&=\tfrac{369}2\pm\tfrac{27}2\,\sqrt{119}
\end{align}
and hence, four solutions for $x$:
\begin{align}
x_1&=\tfrac32\,\sqrt{82+6\sqrt{119}}
,\\
x_2&=-\tfrac32\,\sqrt{82+6\sqrt{119}}
,\\
x_3&=\tfrac32\,\sqrt{82-6\sqrt{119}}
,\\
x_4&=-\tfrac32\,\sqrt{82-6\sqrt{119}}
.
\end{align}


text:
Q: Comparing two lists in excel and extracting values missing from 2nd list - cannot be duplicated (also over two sheets) Im working on a project report for work and I'm trying to find a way to compare two lists of project codes i.e "123456" and see whether the 2nd list is missing any new values that would've been entered into the first list. The lists are thousands of records long and so far people have been doing it manually (it hurts me knowing this) so I'm trying to make it automatic.
What I have tried is using an Array with a Index(Match(CountIF))) formula but I just cant seem to get it working.

My problem is that when I get the array to fill with what i want I then can't get it to not duplicate values (I need it to check the masterlist so it doesnt output something more than once into the output list).
I've also tried to give it a go with other formulas - but the lists can be thousands of records long so I cant do a cell for cell match as the list would be huge (that or my excel knowledge isnt good enough to know the easy solution).
Any help would be hugely appreciated.

*

*Array might not be the best solution

*I've checked quite a few other solutions but they don't quite deal with my issue and I don't have the skill to adapt them.

A: Here is one approach using VBA and arrays which is quicker than doing via the sheet. It checks each item in H to see it is present in J (and not the other way round). I assume that's what you want.
Sub x()

Dim v1, v2, v3(), i As Long, j As Long

v1 = Range("H2", Range("H" & Rows.Count).End(xlUp)).Value
v2 = Range("J2", Range("J" & Rows.Count).End(xlUp)).Value

ReDim v3(1 To UBound(v1, 1))

For i = LBound(v1) To UBound(v1)
    If IsError(Application.Match(v1(i, 1), v2, 0)) Then
        j = j + 1
        v3(j) = v1(i, 1)
    End If
Next i

Range("K2").Resize(j) = Application.Transpose(v3)

End Sub

Using an input box
Sub x()

Dim v1, v2, v3(), i As Long, j As Long

v1 = Application.InputBox("First list", Type:=8)
v2 = Application.InputBox("Second list", Type:=8)

ReDim v3(1 To UBound(v1, 1))

For i = LBound(v1) To UBound(v1)
    If IsError(Application.Match(v1(i, 1), v2, 0)) Then
        j = j + 1
        v3(j) = v1(i, 1)
    End If
Next i
Range("K2").Resize(j) = Application.Transpose(v3)

End Sub

A: A formula solution.
Note that I turned the first two ranges into Tables and changed the names.  The formula is using structured references.  This enables the formula to auto update if you add rows in the future.
=IFERROR(INDEX(ProjList1[#Data],AGGREGATE(15,6,1/ISNA(MATCH(ProjList1[#Data],ProjList2[#Data],0))*ROW(ProjList1[#Data]),ROWS($1:1))-ROW(ProjList1[#Headers])),"")

How does it work?   Briefly:

*

*MATCH generates an array of #NA! errors or a number.

*ISNA turns that into an array of TRUE/FALSE where TRUE indicates an entry in table 1 that is NOT in table 2

*Multiplying that array by the array of project list rows returns an array of error message vs row number

*AGGREGATE small function ignores the error returns to give an ascending list of row numbers

*INDEX then returns the appropriate entry from Table 1

*ROW(ProjList1[#Headers]) is a correction so that the table may be located anyplace on the worksheet, and still return the correct row.

A: Not sure if you're trying to set this up so it will autoupdate in future, but as a stopgap:
Countif column next to list 1 that checks whether they appear in list 2...
... Feeding into a pivot that only shows those where the countif value is 0, in the "row" field to remove duplication?


text:
Q: Share multiple message with UIActivityViewController I'm a new at iOS development and I'm trying to use UIActivityViewController. I have tried to look for this answer for over 3 hours. I saw some answers that didn't work for me, here's my problem:
I would like to use UIActivityViewController to share 2 messages
I have used the following code without any success:
  NSArray* sharedObjects=[NSArray arrayWithObjects:msgOne, msgTwo,  nil];
  UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:sharedObjects applicationActivities:nil];
  activityViewController.popoverPresentationController.sourceView = self.view;
  [self presentViewController:activityViewController animated:YES completion:nil];

Unfortunately, it sends one message with a concatenation of the two strings, what I would like is two separate messages (of course without prompting the user twice).
Is that possible and if yes, how can I achieve this?
Thanks!


text:
Q: fetch and async/await without try/catch I'm trying to get async await to work without try/catch
  return await fetch(url, options)
    .then(res => res.json())
    .catch(err => {
      throw new Error(err)
    })

Here is how I make the call:
    const response = await makeApiRequest('/reset', {
        password: password1,
        code
    }, {
        noauth: true
    }).catch(err => {
        debugger;
        msg = err.message;
    });

    if (response) {
        navigateTo('/');
    }

The problem is none of the catch blocks are working. The code is expired and serving a 401.

A: This is what I got to work:
  return fetch(url, options)
    .then(async res => {
      if (!res.ok) {
        const err = await res.json()
        throw err.message || res.statusText
      }

      return res.json()
    })
    .catch(err => {
      throw new Error(err)
    })

You can call it like this:
        const response = await myFetch('/forgot', {
            email
        }, {
            headers: {
                'x-contact': 'hello@puump.com'
            }
        }).catch(err => {
            msg = err.message;
            return;
        });

        if (response) {
            push('/');
        }

A: Fetch API fails only if it can't make a request. And if it can, fetch will be executed successfully even if it has a bad status.
Because throw new Error(err) never been called, it just be call when you try to parse a invalid string content to a json object (res.json()). I guest, in 401 case your server return a valid json string like {message: "Unauthorized"}, then res.json() working fine, and does not have any error has been throw.
If you want to catch http error, then http status code of res object is a right way:
  return await fetch(url, options)
    .then(res => {
      if (res.status >= 300) { // error http status code range
        throw new Error(res.status) // throw a error to the catch block
      }
      return res.json();
    })
    .catch(err => {
      throw new Error(err) // catch and throw to the error of previous `.then` block
    })

Then try again.


text:
Q: Custom searches in WordPress I need to create multiple search fields that each search different content in WordPress. I know about Search Everything, which is helpful with specifying what is searched, but doesn't allow multiple, unique instances with their own search parameters.
Any help is appreciated!

A: For custom searching categories, you add a hidden input field to the search form, I'm sure there is a variation for content types.
<input type="hidden" name="cat" value="22" />

Possibly
<input type="hidden" name="post_type" value="your content type slug / name" />


text:
Q: Plot multiple quantile regression lines with lattice and quantreg I want to plot several quantile regression lines (quantreg package) like this:
 library(quantreg)
 data(engel)
 attach(engel)
 plot(income, foodexp, cex = 0.25, type = "n",
      xlab = "Household Income", ylab = "Food Expenditure")
 points(income, foodexp, cex = 0.5, col = "blue")
 abline(rq(foodexp ~ income, tau = 0.5), col = "blue")
 abline(lm(foodexp ~ income), lty = 2, col = "red")
 taus <- c(0.05, 0.1, 0.25, 0.75, 0.9, 0.95)
 for (i in 1:length(taus)) {
   abline(rq(foodexp ~ income, tau = taus[i]),
          col = "gray")
 }
 detach(engel)

but using lattice, I tried with only one regression but doesn't work:
require(lattice)
xyplot(foodexp~income , data =engel,
   type = c("g"),
   auto.key=list(x=.8,y=.35,cex=.8,cex.title=.8, title="", points=TRUE),
   scales=list(tck=-1),ylab=list("Food Expenditure",font=3),
   xlab=list("Household Income",font=3),
   panel=function(x,y){
     panel.xyplot(x,y)
     panel.grid()
     panel.abline(rq(foodexp ~ income, tau = 0.5))}
)

A: Using lattice you should just use y and x within the panel function.

xyplot(foodexp~income , data =engel,
       type = c("g"),
       auto.key=list(x=.8,y=.35,cex=.8,cex.title=.8, title="", points=TRUE),
       scales=list(tck=-1),ylab=list("Food Expenditure",font=3),
       xlab=list("Household Income",font=3),
       panel=function(x,y,...){
         panel.xyplot(x,y)
         panel.grid()
         panel.abline(rq(y ~ x, tau = 0.5))
         panel.points(x, y, cex = 0.5, col = "blue")
         panel.abline(rq(y ~ x, tau = 0.5), col = "blue")
         panel.abline(lm(y ~ x), lty = 2, col = "red")
         taus <- c(0.05, 0.1, 0.25, 0.75, 0.9, 0.95)
         for (i in 1:length(taus)) {
           panel.abline(rq(y ~ x, tau = taus[i]),
                  col = "gray")
         }

       }
)


text:
Q: SQL - Pick one record from group if TRUE, all records if FALSE I can brute force this, but feel like there's a more efficient way. For each group ID below, I want to return the ONE record flagged as TRUE. Or if NO record in the group is flagged as TRUE, then I want to return ALL the FALSE records. I'm using the latest version of SQL Server.
select 500 id, 100 group_id, 0 flag into #y
union select 501, 100, 0
union select 502, 100, 0
union select 503, 100, 0
union select 504, 100, 1
union select 505, 101, 0
union select 506, 101, 0
union select 507, 101, 0
union select 508, 102, 0
union select 509, 102, 1
union select 510, 102, 0

The desired results would return ID's 504 and 509 (the single TRUE record in groups 100 and 102 respectively) and ID's 505, 506, 507 (all records in group 101 because no TRUE record exists in the group).
select * from #y where id in (504, 505, 506, 507, 509)

I tried some things with subqueries and window functions but feel like there's a more straightforward way. Thank you.

A: It can quite easily be done with an OR condition, as follows:
SELECT *
FROM   #y
WHERE  flag = 1
OR     group_id NOT IN (SELECT group_id FROM #y WHERE flag = 1)

Results:
504 100 1
505 101 0
506 101 0
507 101 0
509 102 1

Working demo: DB Fiddle

A: A simple approach to this would be (assuming a group_id can only have a single row where flag = 1):
SELECT
   *
FROM table
WHERE flag = 1
UNION ALL
SELECT
   *
FROM table
WHERE group_id NOT IN (SELECT group_id FROM table WHERE flag = 1)

A: One solution using window functions would be to use Row_number to rank the rows, and Max to determine if no rows in a partition have a flag:
with cte as (
  select *,
  case when
    Max(flag) over(partition by group_id) = 0 then 1
  else
    Row_Number() over(partition by group_id order by flag desc)
  end rn
from #y
)
select Id, Group_id, Flag
from cte
where rn = 1;

See Demo Fiddle
Result:

Note, if you have more than 1 "true" per group then you can use dense_rank instead.

A: You can use NOT EXISTS:
SELECT t1.*
FROM #y t1
WHERE t1.flag = 1
   OR NOT EXISTS (
     SELECT *
     FROM #y t2
     WHERE t2.group_id = t1.group_id AND t2.flag = 1
   );

Or, with RANK() window function:
WITH cte AS (
  SELECT *, RANK() OVER (PARTITION BY group_id ORDER BY flag DESC) rn
  FROM #y
)
SELECT id, group_id, flag FROM cte WHERE rn = 1;

See the demo.

A: use union all
select * from #y where flag=1
union all
select * from #y
where (select sum(flag) from #y)=0

demo link


text:
Q: Array PHP para Json eu tenho essa consulta, eu preciso exibir cada coluna em uma div do HTML. Bom, preciso retornar os dados num array PHP, passar esse array php para um array em JS para conseguir manipular e exibir eles nas suas respectivas divs, a consulta ta funcionando perfeitamente, mas como passo isso pro Jquery? Preciso usar Json, certo? Eu tentei usar um Json encode, mas não funcionou.
    <?php

$equipe1 = $_POST['equipe1'];//Pega o Nome da equipe
$equipe2 = $_POST ['equipe2'];//Pega o Nome da equipe
$dificuldade = $_POST ['dificuldade'];//Define a dificuldade das perguntas que seram selecionadas
$rodada = $_POST ['rodada'];//Número de perguntas que serão retornadas

echo $equipe1;
echo $equipe2;

switch ($dificuldade) {
  case '1':
    $dificuldade = "Facil";
    break;
  case '2':
    $dificuldade = "Medio";
    break;
  case '3':
    $dificuldade = "Dificil";
    break;
}

switch ($rodada) {
  case '1':
    $rodada = "10";
    break;
  case '2':
    $rodada = "15";
    break;
  case '3':
    $rodada = "20";
    break;
}
    try{
     $conexao = new PDO ("mysql:host=localhost; dbname=teocratico; charset=utf8","root","");
     } catch (PDOException $erro){
       echo $erro->getmessage();
       //header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
     }

$consulta = $conexao -> query ("SELECT id_pergunta, pergunta, resposta, desafio FROM perguntas
           where dificuldade ='$dificuldade' ORDER BY rand() LIMIT $rodada ");

// Mostrando a Consulta
$consulta->fetch(PDO::FETCH_ASSOC);
   while($row = $consulta->fetch(PDO::FETCH_ASSOC)) {
    echo  $row['id_pergunta']. ' - '. $row['pergunta'] . ' - ' . $row['resposta'] .' - '. $row ['desafio'].' <BR /> ';
  }

?>

A: Vou aproveitar que estou com a mão na massa para explicar para você.
Quando você tem um array em php nesse formato (executando um var_dump($array) no servidor):

object(stdClass)#6394 (59) { ["id_customer"]=> string(1) "1"
  ["fk_customer_civilstatus"]=> string(1) "1" ["hashed_id"]=> string(6)
  "xxxxxx" ["name"]=> string(17) "Marcelo" ["cpf"]=> NULL
  ["phone"]=> string(15) "" ["email"]=> string(28)
  "mb@mail.com" ["password"]=> string(60)
  "" ["gender"]=> string(1) "M" ["birthdate"]=> string(10)
  "0000-00-00" ["id_google"]=> NULL ["id_facebook"]=> NULL
  ["avatar_url"]=> NULL ["changekey"]=> NULL ["last_access"]=>
  string(19) "2017-01-25 02:45:17" ["created_at"]=> NULL
  ["updated_at"]=> NULL ["idusuario"]=> string(6) "xxxxxx"
  ["id_address"]=> string(1) "1" ["postal_code"]=> string(9) "00000-000"
  ["country"]=> string(6) "Brasil" ["street"]=> string(25) "" ["state"]=> string(2) "SP" ["city"]=> string(10) "São
  Paulo" ["number"]=> string(2) "99" ["district"]=> string(12) "" ["complement"]=> string(0) "" ["id_creditcard"]=> NULL
  ["creditcard"]=> NULL ["total_price"]=> string(4) "1490"
  ["id_coupons"]=> NULL ["coupon_name"]=> NULL ["coupon_code"]=> NULL
  ["discount"]=> NULL ["duration_months"]=> NULL ["start_date"]=> NULL
  ["end_date"]=> NULL ["id_sales_order_item"]=> string(1) "1"
  ["fk_sales_order"]=> string(1) "1" ["fk_product"]=> string(2) "22"
  ["contract_sl_id"]=> NULL ["fk_sales_order_item_status"]=> string(1)
  "1" ["fk_sales_order_item_cancellation"]=> NULL ["fk_shipping"]=> NULL
  ["original_unit_price"]=> string(4) "1490" ["final_unit_price"]=>
  string(4) "1490" ["trial_start"]=> string(19) "0000-00-00 00:00:00"
  ["trial_end"]=> string(19) "0000-00-00 00:00:00" ["active_from"]=>
  NULL ["active_until"]=> NULL ["id_subscription_status_type"]=>
  string(1) "3" ["status"]=> string(9) "congelado"
  ["id_payment_method"]=> NULL ["method"]=> NULL
  ["id_sales_order_item_cancellation"]=> NULL ["request_date"]=> NULL
  ["cancellation_date"]=> NULL ["reason"]=> NULL }

Ao alterar o formato de retorno executando: json_encode($array) você obtêm:

{"id_customer":"1","fk_customer_civilstatus":"1","hashed_id":"xxxxxx","name":"Marcelo","cpf":null,"phone":"","email":"mb@mail.com","password":"","gender":"M","birthdate":"0000-00-00","id_google":null,"id_facebook":null,"avatar_url":null,"changekey":null,"last_access":"2017-01-25
  02:45:17","created_at":null,"updated_at":null,"idusuario":"7Z2PZ6","id_address":"1","postal_code":"00000-000","country":"Brasil","street":"","state":"SP","city":"S\u00e3o
  Paulo","number":"99","district":"","complement":"","id_creditcard":null,"creditcard":null,"total_price":"1490","id_coupons":null,"coupon_name":null,"coupon_code":null,"discount":null,"duration_months":null,"start_date":null,"end_date":null,"id_sales_order_item":"1","fk_sales_order":"1","fk_product":"22","contract_sl_id":null,"fk_sales_order_item_status":"1","fk_sales_order_item_cancellation":null,"fk_shipping":null,"original_unit_price":"1490","final_unit_price":"1490","trial_start":"0000-00-00
  00:00:00","trial_end":"0000-00-00
  00:00:00","active_from":null,"active_until":null,"id_subscription_status_type":"3","status":"congelado","id_payment_method":null,"method":null,"id_sales_order_item_cancellation":null,"request_date":null,"cancellation_date":null,"reason":null}

Verifique que este segundo formato é um json valido (ferramenta online que verifica se um json é valido, jogue a string acima e teste).
Agora na parte do client-side que requisita esta consulta você pode montar um script que trabalhe com ajax dessa forma:
jQuery.ajax({
  url: "/api/user/",
  type: "POST",
  data: data,
  success: function(returnjson) {
    alert(returnjson.id_customer);
  },
  error: function(returnjson) {
    if (returnjson.status == 500) {
      alert("Erro interno do servidor, tente novamente ou entre em contato com o suporte técnico.");
    } else {
      alert(returnjson.responseJSON.msg);
    }
  }
});

Dentro do alert(returnjson.id_customer); você terá impresso o valor que retornou do seu json.
Vale lembrar que no servidor também é importante definir o header correto: header('Content-Type: application/json');

No seu caso você pode trabalhar sua pagina php da seguinte maneira:
header('Content-Type: application/json');
$equipe1 = $_POST['equipe1'];//Pega o Nome da equipe
$equipe2 = $_POST ['equipe2'];//Pega o Nome da equipe
$dificuldade = $_POST ['dificuldade'];//Define a dificuldade das perguntas que seram selecionadas
$rodada = $_POST ['rodada'];//Número de perguntas que serão retornadas
switch ($dificuldade) {
    case '1':
    $dificuldade = "Facil";
    break;
    case '2':
    $dificuldade = "Medio";
    break;
    case '3':
    $dificuldade = "Dificil";
    break;
}
switch ($rodada) {
    case '1':
    $rodada = "10";
    break;
    case '2':
    $rodada = "15";
    break;
    case '3':
    $rodada = "20";
    break;
}
try{
    $conexao = new PDO ("mysql:host=localhost; dbname=teocratico; charset=utf8","root","");
} catch (PDOException $erro){
    echo $erro->getmessage();
    //header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}
$consulta = $conexao->query ("SELECT id_pergunta, pergunta, resposta, desafio FROM perguntas
where dificuldade ='$dificuldade' ORDER BY rand() LIMIT $rodada ");
// Mostrando a Consulta
$db_data = $consulta->fetch(PDO::FETCH_ASSOC);
die(json_encode($db_data));


text:
Q: How to set Maximum provisioned capacity for DynamoDB using cloud formation yaml config? I am using yaml config file to create dynamo DB table and set some configurations:
ProvisionedThroughput:
    ReadCapacityUnits: 1
    WriteCapacityUnits: 1

This sets the desired minimum number of consistent reads/writes. If it is possible, how can I set the Maximum provisioned capacity for read/write?

A: In the example you have used you are not setting the minimum provisioned capacity within auto scaling, you are setting the provision capacity.
To configure an auto-scaling resource you should use AWS::ApplicationAutoScaling::ScalableTarget
Which has this structure:
Type: "AWS::ApplicationAutoScaling::ScalableTarget"
Properties:
  MaxCapacity: Integer
  MinCapacity: Integer
  ResourceId: String
  RoleARN: String
  ScalableDimension: String
  ScheduledActions:
    - ScheduledAction
  ServiceNamespace: String

And here is a DynamoDB example:
Resources:
  DDBTable:
    Type: "AWS::DynamoDB::Table"
    Properties:
      AttributeDefinitions:
        -
          AttributeName: "ArtistId"
          AttributeType: "S"
        -
          AttributeName: "Concert"
          AttributeType: "S"
        -
          AttributeName: "TicketSales"
          AttributeType: "S"
      KeySchema:
        -
          AttributeName: "ArtistId"
          KeyType: "HASH"
        -
          AttributeName: "Concert"
          KeyType: "RANGE"
      GlobalSecondaryIndexes:
        -
          IndexName: "GSI"
          KeySchema:
            -
              AttributeName: "TicketSales"
              KeyType: "HASH"
          Projection:
            ProjectionType: "KEYS_ONLY"
          ProvisionedThroughput:
            ReadCapacityUnits: 5
            WriteCapacityUnits: 5
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
  WriteCapacityScalableTarget:
    Type: "AWS::ApplicationAutoScaling::ScalableTarget"
    Properties:
      MaxCapacity: 15
      MinCapacity: 5
      ResourceId: !Join
        - /
        - - table
          - !Ref DDBTable
      RoleARN: !GetAtt ScalingRole.Arn
      ScalableDimension: dynamodb:table:WriteCapacityUnits
      ServiceNamespace: dynamodb
  ScalingRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          -
            Effect: "Allow"
            Principal:
              Service:
                - application-autoscaling.amazonaws.com
            Action:
              - "sts:AssumeRole"
      Path: "/"
      Policies:
        -
          PolicyName: "root"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              -
                Effect: "Allow"
                Action:
                  - "dynamodb:DescribeTable"
                  - "dynamodb:UpdateTable"
                  - "cloudwatch:PutMetricAlarm"
                  - "cloudwatch:DescribeAlarms"
                  - "cloudwatch:GetMetricStatistics"
                  - "cloudwatch:SetAlarmState"
                  - "cloudwatch:DeleteAlarms"
                Resource: "*"
  WriteScalingPolicy:
    Type: "AWS::ApplicationAutoScaling::ScalingPolicy"
    Properties:
      PolicyName: WriteAutoScalingPolicy
      PolicyType: TargetTrackingScaling
      ScalingTargetId: !Ref WriteCapacityScalableTarget
      TargetTrackingScalingPolicyConfiguration:
        TargetValue: 50.0
        ScaleInCooldown: 60
        ScaleOutCooldown: 60
        PredefinedMetricSpecification:
          PredefinedMetricType: DynamoDBWriteCapacityUtilization


text:
Q: Is it possible to use server flow auth as a fallback for client side auth on Google Drive for browser that do not support the JavaScript libraries? The list of supported browsers for the Google API JavaScript library used to implement Google Drive functionality directly in JavaScript doesn't officially support IE 7- or Opera, of note.
If I wanted to use the JS library, with a server-based fallback for unsupported browsers, is that possible?
The obvious issue is that separate API keys for the client and server flow auth would be needed, so if the scopes were limited to files opened and created by the Drive app, would a file created in IE 7 using the server auth open in Chrome using the client?

A: 'hybrid' auth using both client-flow and server-flow works OK. The JS client and CORS endpoints aren't all in place yet, so I use JS where I can, but proxy through my servlets where necessary.
I use a single client-id for both.


text:
Q: How can I execute a cmd line command passing excel data as an argument? We have a large list of user IDs in excel and would like to be able to click the user ID and have it execute the following command and display the results:  net user /domain <user ID>
I would imagine that call shell is the correct way to go... I'm just not familiar with using VB and excel.
Any ideas?

A: Try this sub. This sub works for general DOS/batch command.
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect(Target, Range("A:A")) Is Nothing Then
       'Call Shell("CMD.EXE /c " & Target.Value)
       Call Shell("cmd.exe /c net user /domain " & Target.Value)
    End If
End Sub

Assuming your User Name's are in Column A Double click on any cell which have User Name then press ENTER or TAB key
This is a screenshot which working 100% (For your clarification).

A: You could hook it into the selection change event of the worksheet, the code would sit in the worksheet module.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Column = 1 Then 'assuming your ID's are in column A
        Call Shell("cmd.exe" & "rest of your command")
    End If
End Sub


text: Q: GitHub pull request associated file and comments I am looking for an easy way to find GitHub pull request associated file and comments? If you have suggestions or any recommendations, then please feel free to share your experience.


text:
Q: Use wkhtml2pdf in asp.net core docker image I'm working on an asp.net core 3 project, and I use Rotativa to generate pdf files.
When I run on Windows, wkhtml2pdf.exe works fine, but when I try to run the app in a linux docker image, I have this error :
Exception: /app/Rotativa/wkhtmltopdf: error while loading shared libraries: libjpeg.so.8: cannot open shared object file: No such file or directory

I use the default Dockerfile (generated by Visual Studio).
I think I have to install libjpeg in the image, but I don't know how to do it.
I tried to install it with apt-get in the Dockerfile, but there's an error :
The command '/bin/sh -c apt-get install -y libjpeg-dev' returned a non-zero code: 100

How can I make wkhtml2pdf work in my docker image ?


text:
Q: NTBackup skips files inconsistently I've got a server that runs a full ntbackup once a week.  Every week, it will log about a dozen files with the following messages:
WARNING: Portions of "\OBJECTS\SERVER\STORAGE\DOCS101\SomeFile.000" cannot be read.  The backed up data is corrupt or incomplete.
This file will not restore correctly.
Warning: Unable to open "E:\OBJECTS\SERVER\STORAGE\DOCS101\SomeFile.001" - skipped.
Reason: The system cannot find the file specified.

Warning: Unable to open "E:\OBJECTS\SERVER\STORAGE\DOCS101\SomeFile.002" - skipped.
Reason: The system cannot find the file specified.

...

Warning: Unable to open "E:\OBJECTS\SERVER\STORAGE\DOCS101\SomeFile.012" - skipped.
Reason: The system cannot find the file specified.

Could not access portions of directory E:\OBJECTS\SERVER\STORAGE\DOCS101.
You may not have permission to open the file, or the directory may be missing or damaged.
Please contact the owner or administrator.

The thing is, it's never the same files.  It's always a different, seemingly entirely random group of consecutive files.  And it's not new files either.  I've seen documents that are from as far back as 2006 show up on this list.  I've checked, and all of the files are in the paths shown in the log file, and I am able to view them without problems. Any idea why this would be happening?
EDIT: This has been an ongoing problem for almost three years now, and I'm totally stumped.

A: Something else has those files locked. Do you have antivirus scan or is something indexing the file system (locally or over a share)? I assume chkdsk comes up clean?
The error is misleading, something has the files open. Try this right before the backup kicks off.
 net files > opensharedfiles.txt
 handle > handleList.txt

(handle.exe is a tool from sysinternals which you can download for here).
opensharedfiles.txt will show you is someone still has a file open remotely, handleList.txt will show you all handles on the machine, allowing you to locate which local process might have it open.
Shamelessly stolen from Fulgan@Arstechnica


text:
Q: How can i pass the selected data objects to another page
HEllo, how can i pass the selected object data when I want to select more than one and pass it into another page and put it as a list. How can i achieve this ?
But how can i pass the parameter when i select more than one object ?

A: add your products to an array first
productList = [] as any[];

productList.push(product);

this.navCtrl.push(OrderPage,{ productList: productList});

A: In angular, you can pass different ways to pass data to other pages

by Query Parameters(if parameters are not secret);

from ts file
this.router.navigate(
   ['/path'],
   { queryParams: { key1: valu1, key2: value2, key3: value3 }
});

from html file
<a [routerLink]="['/path']"
   [queryParams]="{ key1: value1, key2: value2, key3: value3 }">
  Something    </a>

path will be like http://localhost:4200/path?key1=value1&key2=value2&key3=value3
You can get by
constructor(private route: ActivatedRoute) {
this.sub = this.route.queryParams.subscribe(params => {
       this.id = +params['id']; // (+) converts string 'id' to a number
    });
}

by Linking to Routes with Parameters

this.router.navigate(['/path', {key1: value1, key2: value2}]);

check the parameters by
constructor(private route: ActivatedRoute) {
this.sub = this.route.params.subscribe(params => {
       this.id = +params['id']; // (+) converts string 'id' to a number
    });
}


text:
Q: Searching Path through grid in 2-dimensions with condition Lets Assume we have a Grid {a,b} with entries |b-a| for n <= a,b < N  and |b-a| > 0.
How can I design a path through all entries, where I visit the highest values of b-a first?
The problem arises for me when we coming across the border a==b, because I need to visit all entries and at that border I have to go back.
My first idea was the following:
paths = {}
for a in range(n,N-1):
    for b in range(a+1,N):
        if b-a not in paths:
            paths[b-a] = [(a,b)]
        else:
            paths[b-a] += [(a,b)]

for p in reversed(list(paths.key())):
    for q in paths[p]:
        visit(q)

The Problem is that this solution takes far too much memory for big N. I was thinking of a similar solution which uses only iterators and not a dictionary, but I am not able to reformulate the problem properly for using iterators.
Any suggestions?
//edit: I solved it, for anyone who is interested:
class period_iter:
    def __init__(self,t0,t1):
        self.t0 = t0
        self.t1 = t1
    def __iter__(self):
        self.i = -1
        self.j = 0
        return self
    def __next__(self):
        self.i += 1
        if self.i > self.j:
            self.i =  0
            self.j += 1
        if self.j == (self.t1 - self.t0):
            raise StopIteration
        ti = t0 + self.i
        tf = self.t1-(self.j-self.i)
        return (ti,tf,tf-ti)


text:
Q: Aggregate with subselect or subquery I'm trying to make a query that returns how much I can produce based on the lowest value of a sum of component units from different warehouses.
Data come from tables like these:
e.table
-------
codartp    codartc      unicompo
REF1       BLISTER1       1
REF1       BOX1           1
REF1       CHARGER1       2
REF2       BLISTER2       1
REF2       BOX2           1

s.table
------
codart      unidades      codalm
BLISTER1      100           4
BLISTER1      150           1
BOX1          100           1
BOX1          100           4
BOX1          200           2
CHARGER1      50            3
CHARGER1      50            4
BLISTER2      500           1
BLISTER2      300           4
BOX2          150           2

I would need to sum how much I have from every component (blister, box, charger...) in total:
BLISTER1: 250
BOX1: 400
CHARGER1: 100
And then return the lowest value divided by the unicompo (the number of components I need). With my stock of components, I could only produce 50 units of REF1: 100/2
Here is my subselect:
(select min(val) from (select sum(s1.unidades/e.unicompo) as val
    from __STOCKALMART s1
    left join escandallo e on e.codartc = s1.codart
    where s1.codalm not in (0,9999) and e.codartp = l.codart) t) as PRODUCIBLE

The expected result would be something like this:
l.codart  producible
REF1          50
REF2          150

But I only managed to call either the min (in some warehouses is 0) or the sum of components, not min after the sum. I don't know if I'm explaining myself. Ask if I need to clarify anything
Thanks for your help

A: As long as there is no overlap between your product compositions (so no two products share a common component, otherwise you are looking at something way more complex), then the query below should give you a solution.
Sample data
create table ProductComponent
(
  codartp nvarchar(4),  -- product
  codartc nvarchar(10), -- component
  unicompo int          -- amount
);

insert into ProductComponent (codartp, codartc, unicompo) values
('REF1', 'BLISTER1', 1),
('REF1', 'BOX1'    , 1),
('REF1', 'CHARGER1', 2),
('REF2', 'BLISTER2', 1),
('REF2', 'BOX2'    , 1);

create table ComponentInventory
(
  codart nvarchar(10), -- component
  unidades int,        -- amount
  codalm int           -- warehouse
);

insert into ComponentInventory (codart, unidades, codalm) values
('BLISTER1', 100, 4),
('BLISTER1', 150, 1),
('BOX1'    , 100, 1),
('BOX1'    , 100, 4),
('BOX1'    , 200, 2),
('CHARGER1', 50 , 3),
('CHARGER1', 50 , 4),
('BLISTER2', 500, 1),
('BLISTER2', 300, 4),
('BOX2'    , 150, 2);

Solution
Using some common table expressions (CTE's) to:

*

*Sum up all the inventory components across the warehouses.

*Divide the previous sums according to the product composition.

This gives:
with cti as -- component inventory total
(
  select ci.codart,
         sum(ci.unidades) as unidades
  from ComponentInventory ci
  group by ci.codart
),
pci as -- product component inventory
(
  select pc.codartp,
         cti.unidades / pc.unicompo as maxPart
  from ProductComponent pc
  join cti
    on cti.codart = pc.codartc
)
select pci.codartp,
       min(pci.maxPart) as producibleAmount
from pci
group by pci.codartp
order by pci.codartp;

Result
codartp producibleAmount
------- ----------------
REF1    50
REF2    150

Fiddle to see it in action with intermediate CTE results.


text:
Q: Asp MVC 2: Obfusicate Entity-IDs Project type: Asp MVC 2/NHibernate/C#
Problem
If you have an edit page in an web application you will come to the problem that you have to send and then receive the id of the entity you're editing, the IDs of sub-entities, entities that can be selected by dropdownmenus,...
As it is possible to modify a form-post, an evil user could try to send back another ID which maybe would grant him more rights (if i.e. that ID was related to a security entity).
My approach

*

*Create a GUID and associate it with the ID

*Save the association in the http session

*Wait for the response and extract the real ID out of the received GUID.

Question:
What techniques do you use to obfusicate an entity-ID?

A: If you're doing that much for GUIDs, why not just use GUIDs for the identity of the entity itself that's actually stored in the database (though I'd advise against it)?
Or you could have a server side encryption scheme that encrypts and then subsequently decrypts the id (this is a long the same lines as what you're doing except you're not storing anything random like this in the session (yuck :) ).
You could even forget trying to do this at all since a lot of sites are "affected" by this issue, and it's obviously not a problem (StackOverflow for example). The overhead is just too much.
Also, if you're worried about security, why don't you have some sort of granular permissions set on the individual action/even entity level. This would solve some problems as well.
EDIT:
Another problem with your solution is inconsistent unique identifiers. If a user says "ID as23423he423fsda has 'invalid' data", how do you know which ID it belongs to if it's changing on every request (assuming you're going to change the id in the URL as well)? You'd be much better of with an encryption algorithm that always hashes to the same value therefore, you can easily perform a lookup (if you need it) and also the user has consistent identifiers.

A: Your controllers should be immune to modified POST data. Before displaying or modifying records belonging to a user, you should always check whether the records in question belong to the authenticated user.


text:
Q: How to detect duplicate php Array I have this array:-
Array ( [0] => Prefectorial Board/Prefect/2011 [1] => Prefectorial Board/Head Prefect/2011 [2] => Class Positions/Head Prefect/2011 [3] => Prefectorial Board/Head Prefect/2011 )

How to detect this array have duplicate value and I want the participant to re-fill in his data.
I have try to use this method to detect:-
$max  = max(array_values($lr_str));
$keys = array_keys($lr_str, $max);

but it seem like not work for me.
any idea on this?
thanks for advance.

A: Are you looking for array_unique?

A: You can use array_unique() to remove duplicate values.  If no values were removed then the returned array should have the same number of items as the original:
if(count($lr_str) == count(array_unique($lr_str))){
    //tell participant to re=fill their data
}

A: I do not know if I understand you correctly, but you can test the array has duplicated values by using this:
if (count($your_array) === count(array_unique($your_array)) {
    // array has no duplicated values
} else {
    // array has duplicated values - see compared arrays
}


text:
Q: Show that I is a confidence Interval im working on the following problem:
$X_1$,....,$X_n$ are random variables, iid and uniformly distributed on the Interval $(0,\theta)$. Show that for all $\lambda_1$,$\lambda_2$ with $0<\lambda_1<\lambda_2<1$ and $\lambda_2^n - \lambda_1^n = 1-\alpha$
the interval $[\frac{M}{\lambda_2},\frac{M}{\lambda_1}]$ is a $1-\alpha$ confidence interval for $\theta$ ( with $M=max(X_1,...,X_n)$).
Ive only done this kind of problem for explicit values, applying the definition is a little bit too much for me at the moment.
What ive done so far is to use the CLT to calculate the actual interval based on mean and variance. Since a uniform distribution is given here, that should not be too much of a problem.
My main problem is to show that (given the interval)
$P(I) \geq 1- \alpha $.
Thanks in advance


text:
Q: \flushmaketitle not defined I'm really sorry to ask this question but I find myself unable to answer it for myself, with little idea of what went wrong:
I created a template for my CV using LaTeX, which worked fine for a year, but I let it untouched for 2 months. I had to recently upgrade my linux distribution and lost a number of libraries in the process (I mention it without a clue whether it's relevant or not). The end of the story is that now, I can't compile my .tex code.
Among various warnings, I see the error:

! LaTeX Error: \flushmaketitle undefined.
See the LaTeX manual or LaTeX Companion for explanation. Type  H
    for immediate help.  ...
                                               l.24

\renewcommand*{\flushmaketitle}

Another maybe relevant warning is

LaTeX Warning: You have requested package moderncvheadiii', but the package providesmoderncvheadiii'.
LaTeX Warning: You have requested package moderncvbodyiii', but the package providesmoderncvbodyiii'.

Here is a cleared version of the .tex file:
\documentclass[11pt,a4paper]{moderncv}
    \moderncvstyle{banking}
    \moderncvcolor{black}
\usepackage[utf8]{inputenc}
\usepackage[hscale=0.8, vscale=1, top=2.5cm]{geometry}
%\usepackage{libertine}
%\usepackage[sfdefault, light]{roboto}  %% Option 'sfdefault' only if the base font of the document is to be sans serif
\usepackage[T1]{fontenc}
\usepackage[skins]{tcolorbox}
\renewcommand{\sfdefault}{phv}
\renewcommand{\seriesdefault}{l}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usetikzlibrary{calc}
\usetikzlibrary{patterns}
\usepackage{booktabs}

\definecolor{color0}{rgb}{0.,0.,0.}
\definecolor{color1}{rgb}{0., 0.6, 0.8}

            \makeatletter
                \renewcommand{\familydefault}{\sfdefault}

                \renewcommand*{\flushmaketitle}{%
                  \strut\usebox{\maketitlebox}%
                  \savebox{\maketitlebox}{}%
                  \savebox{\maketitletempbox}{}%
                  \setlength{\maketitleboxwidth}{0pt}}

                \renewcommand*{\maketitle}{
                  \setlength{\maketitlewidth}{0.7\textwidth}
                  \parbox{\maketitlewidth}{
                    \raggedright

                    \namestyle{\@firstname~\@lastname}\\
                    \vspace{0.2cm}
                    \addressfont\color{color2}%
                    \vspace{0.1cm}
                    \ifthenelse{\isundefined{\@addressstreet}}{}{\addtomaketitle{\addresssymbol\@addressstreet}%
                      \ifthenelse{\equal{\@addresscity}{}}{}{\addtomaketitle[~--~]{\@addresscity}
                     %
                     \flushmaketitle
                     \@firstmaketitleelementtrue}
                     }
                     %}
                    \addtomaketitle{\emaillink{\@email}}

                    \collectionloop{phones}{\addtomaketitle{\@mobile}}
                    \vspace{0.1cm}

                    \ifthenelse{\isundefined{\@extrainfo}}{}{\addtomaketitle{\@extrainfo}}%
                    \ifthenelse{\isundefined{\@title}}{}{\addtomaketitle{\@title}}%
                    %\ifthenelse{\isundefined{\@fax}}{}{\addtomaketitle{\@fax}}%
                                    \vspace{0.1cm}
                    \flushmaketitle}\\[2.5em]}

                \newcommand{\cfbox}[2]{%
                    \colorlet{currentcolor}{.}%
                    {\color{#1}%
                        \fbox{\color{currentcolor}#2}}%
                }

            %   \patchcmd{\maketitle}{\\[2.5em]}{\hfill\raisebox{-1.5cm}{\cfbox{color1}{\includegraphics[width=80pt]{/home/pierre/Documents/Personnel/CVFR/moi1}}}\\[2.5em]}
            \makeatother

\firstname{Pierre}
\familyname{Doe}
\address{Street}{Lane}
\mobile{+60669412}
\email{pierre.doe@gmail.com}
\extrainfo{age\hspace{7pt}}
\title{\hspace{1pt}}
\fax{}

\begin{document}
    \makecvtitle
\nopagenumbers{}

% this puts a dashed thing on the header
%   \begin{tikzpicture}
%   \fill[pattern=dots, pattern color=color1, overlay] (-0.2,0.2) rectangle (17,4.4);
%   \end{tikzpicture}

    \begin{tikzpicture}[radius=1cm,delta angle=180, overlay]
    \node[circle,draw=color1,inner sep=1.3cm,fill overzoom image=/home/pierre/Documents/.jpg] (A) at (15cm,2.8cm) {};
    \end{tikzpicture}

\vspace{0pt}\section{Formation}\vspace{4pt}
    \cventry{something}{something}{}{}{}{}\vspace{-12pt}

\end{document}

A: Well, in the new version 2.0 of moderncv there was a renaming from old version flushmaketitle to  flushmakeheaddetails.
That means you can try to change the error causing command \renewcommand to \newcommand (because the following command has to be defined new now) like
% <=====================================================================
\newcommand*{\flushmaketitle}{%  new version 2.0 flushmaketitle -> flushmakeheaddetails

That compiles for me, but I do not know what you expect and it could be there are other errors now.  Please check that with the following MWE:
\documentclass[11pt,a4paper]{moderncv}

\moderncvstyle{banking}
\moderncvcolor{black}

\usepackage[utf8]{inputenc}
\usepackage[hscale=0.8, vscale=1, top=2.5cm]{geometry}
%\usepackage{libertine}
%\usepackage[sfdefault, light]{roboto}  %% Option 'sfdefault' only if the base font of the document is to be sans serif
\usepackage[T1]{fontenc}
\usepackage[skins]{tcolorbox}
\renewcommand{\sfdefault}{phv}
\renewcommand{\seriesdefault}{l}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usetikzlibrary{calc}
\usetikzlibrary{patterns}
\usepackage{booktabs}

\definecolor{color0}{rgb}{0.,0.,0.}
\definecolor{color1}{rgb}{0., 0.6, 0.8}

\makeatletter
\renewcommand{\familydefault}{\sfdefault}

% <=====================================================================
\newcommand*{\flushmaketitle}{%  new version 2.0 flushmaketitle -> flushmakeheaddetails
  \strut\usebox{\maketitlebox}%
  \savebox{\maketitlebox}{}%
  \savebox{\maketitletempbox}{}%
  \setlength{\maketitleboxwidth}{0pt}%
}

\renewcommand*{\maketitle}{
  \setlength{\maketitlewidth}{0.7\textwidth}
  \parbox{\maketitlewidth}{
    \raggedright

  \namestyle{\@firstname~\@lastname}\\
  \vspace{0.2cm}
  \addressfont\color{color2}%
  \vspace{0.1cm}
  \ifthenelse{\isundefined{\@addressstreet}}{}{%
    \addtomaketitle{\addresssymbol\@addressstreet}%
    \ifthenelse{\equal{\@addresscity}{}}{}{\addtomaketitle[~--~]{\@addresscity}
    %
    \flushmaketitle
    \@firstmaketitleelementtrue}
  }
                     %}
                    \addtomaketitle{\emaillink{\@email}}

                    \collectionloop{phones}{\addtomaketitle{\@mobile}}
                    \vspace{0.1cm}

                    \ifthenelse{\isundefined{\@extrainfo}}{}{\addtomaketitle{\@extrainfo}}%
                    \ifthenelse{\isundefined{\@title}}{}{\addtomaketitle{\@title}}%
                    %\ifthenelse{\isundefined{\@fax}}{}{\addtomaketitle{\@fax}}%
                                    \vspace{0.1cm}
                    \flushmaketitle}\\[2.5em]}

\newcommand{\cfbox}[2]{%
  \colorlet{currentcolor}{.}%
  {\color{#1}%
  \fbox{\color{currentcolor}#2}}%
}

%\patchcmd{\maketitle}{\\[2.5em]}{\hfill\raisebox{-1.5cm}{\cfbox{color1}{\includegraphics[width=80pt]{/home/pierre/Documents/Personnel/CVFR/moi1}}}\\[2.5em]}
\makeatother

\firstname{Pierre}
\familyname{Doe}
\address{Street}{Lane}
\mobile{+60669412}
\email{pierre.doe@gmail.com}
\extrainfo{age\hspace{7pt}}
\title{\hspace{1pt}}
\fax{}

\begin{document}
\makecvtitle
\nopagenumbers{}

% this puts a dashed thing on the header
%   \begin{tikzpicture}
%   \fill[pattern=dots, pattern color=color1, overlay] (-0.2,0.2) rectangle (17,4.4);
%   \end{tikzpicture}

    \begin{tikzpicture}[radius=1cm,delta angle=180, overlay]
    \node[circle,draw=color1,inner sep=1.3cm,fill overzoom image=example-image-a.jpg] (A) at (15cm,2.8cm) {}; % image=/home/pierre/Documents/.jpg
    \end{tikzpicture}

\vspace{0pt}\section{Formation}\vspace{4pt}
    \cventry{something}{something}{}{}{}{}\vspace{-12pt}

\end{document}

I changed the image file name too and get then the result:

Is that close to that what you need?  If not the only chance is to install the old version of moderncv or change your code to be able to use verion 2.0 (that would be better in my eyes ...)


text:
Q: Log in log out session php I have here the code of my login  and logout can you guys check if the session I placed is correct?
Login code:
<?php
session_start();

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Content-Type: text/html');

$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("store_data", $connection);

if(isset($_POST['login'])){
    $admin=$_POST['user'];
    $pass=$_POST['pass'];
    $select_user = mysql_query("SELECT admin_name FROM admin");
    $select_pass = mysql_query("SELECT admin_pass FROM admin");
    $result_1 = mysql_fetch_assoc($select_user);
    $result_2 = mysql_fetch_assoc($select_pass);

    if($admin !=$result_1['admin_name'] || $pass!=$result_2['admin_pass']){
        echo "<script >alert('Invalid password or username')</script>";
        header("refresh:0; url=administrator.php" );
    }

Logout code:
<?php

session_destroy();
header("Location: administrator.php");

?>

A: Before session_destroy you need session_start
<?php
session_start();
session_destroy();
header("Location: administrator.php");
?>

A: Errors

*

*session_start() missing in logout

*You not check $admin and $pass value in your query

*Your Argument is wrong in the set session

*And you not setting any session to destroy it

*Don't use MySQL Function Its depreciated now
In logout
<?php
    session_start(); //add this
    session_destroy();
    header("Location: administrator.php");
?>

In login
<?php

    session_start();

    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header('Content-Type: text/html');

    $connection = mysql_connect("localhost", "root", "");
    $db = mysql_select_db("store_data", $connection);

    if(isset($_POST['login']))
    {
        $admin=$_POST['user'];
        $pass=$_POST['pass'];

        $query = mysql_query("SELECT * FROM admin where admin_name='$admin' AND admin_pass = '$pass' ");

        $result = mysql_fetch_assoc($query);
        $count = count($result);

        if(!empty($count))
        {
            $_SESSION["admin_name"] = $admin;
            header("refresh:0; url=administrator.php" );
        }
        else
        {
            echo "Invalid User";
        }
    }


text:
Q: Alternatives to ScriptApp scope usage in GMail Add-on I'm trying to publish a GMail Add-on with a scheduler functionality and using the Google Apps Script's built in trigger functions to achieve the goal. However when I try to deploy the add-on I get the below error message.
Gmail add-ons may not request the https://www.googleapis.com/auth/script.scriptapp scope.

Is this the intended behaviour? Are there any workarounds to achieve the same without using trigger?
Without the scheduler the add-on would be pretty much useless...


text:
Q: How to change partition size on Ubuntu and Windows dual boot system? I asked a friend to install Ubuntu 14 and Windows 8 installed on my laptop. The partitioning was done as follows:
NAME   FSTYPE   SIZE MOUNTPOINT            LABEL
sda           931.5G
├─sda1 ntfs     300M                       Recovery
├─sda2 vfat     100M /boot/efi
├─sda3          128M
├─sda4 ntfs   126.4G
├─sda5 ntfs   341.8G /mnt/C6E4BB0FE4BB00AB
├─sda6 ntfs   443.2G
├─sda7 swap     1.9G [SWAP]
└─sda8 ext4    17.6G /
Ubuntu is installed on sda8, with size 17.6 GB. I need more space on my ubuntu as I now carry out most of my work there.
Is there a way to alter the size of the partitions, or should I reinstall?


text:
Q: App crashes on startup giving null pointer exception. how can i change the code to start the next activity if user is logged in? Trying to create an app login page. however, it keeps giving me an error
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object reference
the problematic code is here
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(activity_login);

    FirebaseAuth mAuth;

    mEmail = findViewById(R.id.input_email);
    mPassword = findViewById(R.id.input_password);
    String Email = mEmail.getText().toString().trim();
    String Password = mPassword.getText().toString().trim();
    if(fAuth.getCurrentUser() != null){
        startActivity(new Intent(getApplicationContext(),MainActivity.class));
        finish();
    }

A: Try using this...
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(activity_login);

    FirebaseAuth fAuth = FirebaseAuth.getInstance();

    mEmail = findViewById(R.id.input_email);
    mPassword = findViewById(R.id.input_password);
    //Avoid these lines
    //String Email = mEmail.getText().toString().trim();
    //String Password = mPassword.getText().toString().trim();
    //This should be done only after user enter data preferably on button click
    if(fAuth.getCurrentUser() != null){
        startActivity(new Intent(getApplicationContext(),MainActivity.class));
        finish();
    }