问:
Browser extension, - Accessing the images before rendering
I'm a photographer with a good IT background.

I'm looking to intercept the rendering of images in websites, possibly through a browser extension. My plan is to identify the use of my photos automatically when browsing the web.

So what I need to do - you tell me the best way how please:) - is to intercept the rendering of the image, read the image and possibly modify it.

Are extensions/addOns a good approach? Is there another way? Possibly using c#...

Cheers
Marc

答:
If your photo's are hosted on ImageShack.us for example you wont be able to intercept the rendering. IMHO the closest you could get is using a watermark.

However if you host the images on your server and render them out using a ashx in C# then you can read the image and modify it before its rendered.

Take this code as an example:
http://www.developerfusion.com/code/5223/using-ashx-files-to-retrieve-db-images/

```<code><%@ webhandler language="C#" class="NWEmpPhotoHandler" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
public class NWEmpPhotoHandler : IHttpHandler
{
    public bool IsReusable { get { return true; } }

    public void ProcessRequest(HttpContext ctx)
    {
        string id = ctx.Request.QueryString["id"];

        SqlConnection con = new SqlConnection(<<INSERT CONNECTION STRING HERE>>);
        SqlCommand cmd = new SqlCommand("SELECT Photo FROM Employees WHERE EmployeeID = @EmpID", con);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.Add("@EmpID", id);

        con.Open();
        byte[] pict = (byte[])cmd.ExecuteScalar();
        con.Close();

        ctx.Response.ContentType = "image/bmp";
        ctx.Response.OutputStream.Write(pict, 78, pict.Length - 78);
    }
}
</code>```

So you'd hit the ashx with a url like:  www.Marc.com/Images.ashx?id=123

Alternatively with your browser extension approach, you could have a local repository of images or perhaps specific image names (using GUIDs) and when loading a page detect if any of the images are yours and then do your black magic.

Body:
If your photo's are hosted on ImageShack.us for example you wont be able to intercept the rendering. IMHO the closest you could get is using a watermark.

However if you host the images on your server and render them out using a ashx in C# then you can read the image and modify it before its rendered.

Take this code as an example:
http://www.developerfusion.com/code/5223/using-ashx-files-to-retrieve-db-images/

<%@ webhandler language="C#" class="NWEmpPhotoHandler" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
public class NWEmpPhotoHandler : IHttpHandler
{
    public bool IsReusable { get { return true; } }

    public void ProcessRequest(HttpContext ctx)
    {
        string id = ctx.Request.QueryString["id"];

        SqlConnection con = new SqlConnection(<<INSERT CONNECTION STRING HERE>>);
        SqlCommand cmd = new SqlCommand("SELECT Photo FROM Employees WHERE EmployeeID = @EmpID", con);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.Add("@EmpID", id);

        con.Open();
        byte[] pict = (byte[])cmd.ExecuteScalar();
        con.Close();

        ctx.Response.ContentType = "image/bmp";
        ctx.Response.OutputStream.Write(pict, 78, pict.Length - 78);
    }
}

So you'd hit the ashx with a url like:  www.Marc.com/Images.ashx?id=123

Alternatively with your browser extension approach, you could have a local repository of images or perhaps specific image names (using GUIDs) and when loading a page detect if any of the images are yours and then do your black magic.


来源: stackexchange

问:
React Context Api vs Local Storage
I have some general questions which are bothering me regarding the context API and local storage.

When to use local storage?, when to use the Context API and when would I use both?

I know that to persist data after the refresh I need something like local storage or session storage, so do I ditch the context API entirely and just store everything in the local storage? this way I can not only store data but also keep it on refresh? some insight would be really helpful.

What are some pros and cons?

答:
Context API vs Local storage is apples vs oranges comparison.

Context API is meant for sharing state in the component tree.

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Local Storage is for storing data between sessions.

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.

The right comparison might be Local Storage vs Cookies, Context API vs State-Management Library (not really, since Context is not a state management tool).

While you can store everything on the local storage (although it's not scalable and maintainable) it won't be useful.

It won't be useful because you can't notify your components on state change, you need to use any React's API for it.

Usually local storage is used for session features like saving user settings, favorite themes, auth tokens, etc.

And usually, you read once from local storage on application start, and use a custom hook to update its keys on related data change.

Here is a helpful recipe for useLocalStorage custom hook:

```<code>function useLocalStorage(key, initialValue) {
  // State to store our value
  // Pass initial state function to useState so logic is only executed once
  const [storedValue, setStoredValue] = useState(() => {
    try {
      // Get from local storage by key
      const item = window.localStorage.getItem(key);
      // Parse stored json or if none return initialValue
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If error also return initialValue
      console.log(error);
      return initialValue;
    }
  });

  // Return a wrapped version of useState's setter function that ...
  // ... persists the new value to localStorage.
  const setValue = value => {
    try {
      // Allow value to be a function so we have same API as useState
      const valueToStore =
        value instanceof Function ? value(storedValue) : value;
      // Save state
      setStoredValue(valueToStore);
      // Save to local storage
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      // A more advanced implementation would handle the error case
      console.log(error);
    }
  };

  return [storedValue, setValue];
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: React Context Api vs Local Storage

Body:
Context API vs Local storage is apples vs oranges comparison.

Context API is meant for sharing state in the component tree.

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Local Storage is for storing data between sessions.

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.

The right comparison might be Local Storage vs Cookies, Context API vs State-Management Library (not really, since Context is not a state management tool).

While you can store everything on the local storage (although it's not scalable and maintainable) it won't be useful.

It won't be useful because you can't notify your components on state change, you need to use any React's API for it.

Usually local storage is used for session features like saving user settings, favorite themes, auth tokens, etc.

And usually, you read once from local storage on application start, and use a custom hook to update its keys on related data change.

Here is a helpful recipe for useLocalStorage custom hook:

function useLocalStorage(key, initialValue) {
  // State to store our value
  // Pass initial state function to useState so logic is only executed once
  const [storedValue, setStoredValue] = useState(() => {
    try {
      // Get from local storage by key
      const item = window.localStorage.getItem(key);
      // Parse stored json or if none return initialValue
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If error also return initialValue
      console.log(error);
      return initialValue;
    }
  });

  // Return a wrapped version of useState's setter function that ...
  // ... persists the new value to localStorage.
  const setValue = value => {
    try {
      // Allow value to be a function so we have same API as useState
      const valueToStore =
        value instanceof Function ? value(storedValue) : value;
      // Save state
      setStoredValue(valueToStore);
      // Save to local storage
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      // A more advanced implementation would handle the error case
      console.log(error);
    }
  };

  return [storedValue, setValue];
}


问:
Why input event for value EU citizen does not work
[Input not working ][1]

I added an event with the goal of listening to an event when the value of the input is EU citizen so I added it on the button with id 'submit'
The function does work but when I write EU citizen in the input the message 'You are eligible should show' but nothing happens.

```<code>//1. Listen for submit buttton for Nationality
document.getElementById('submit').addEventListener('click', function(e) {

    e.preventDefault();

})

//UI vars for Nationality

const nationality = document.getElementById('submit')

//show message you are eligible if it evaluates to EU citizen

function checkNationality(input) {
if(input === 'EU citizen') {

    console.log('You are eligible')

} else {

  console.log('You are not eligible')

}
}

</code>```

What am I missing? help, please

答:
Here is an example

var nationalityElement = document.querySelector("select");
document.querySelector("button").onclick = function() {
  if(nationalityElement.value === "EU") {
    console.log("You are eligible");
  }else {
    console.log("You are not eligible");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>Nationality</label><br>
<select>
  <option value="AU">AU</option>
  <option value="EU">EU</option>
  <option value="US">US</option>
  <option value="AS">AS</option>
  <option value="AF">AF</option>
</select><br>
<button>Submit Nationality status</button></code>```

Body:
[Input not working ][1]

I added an event with the goal of listening to an event when the value of the input is EU citizen so I added it on the button with id 'submit'
The function does work but when I write EU citizen in the input the message 'You are eligible should show' but nothing happens.

//1. Listen for submit buttton for Nationality
document.getElementById('submit').addEventListener('click', function(e) {

    e.preventDefault();

})

//UI vars for Nationality

const nationality = document.getElementById('submit')

//show message you are eligible if it evaluates to EU citizen

function checkNationality(input) {
if(input === 'EU citizen') {

    console.log('You are eligible')

} else {

  console.log('You are not eligible')

}
}

What am I missing? help, please

Body:
Here is an example

var nationalityElement = document.querySelector("select");
document.querySelector("button").onclick = function() {
  if(nationalityElement.value === "EU") {
    console.log("You are eligible");
  }else {
    console.log("You are not eligible");
  }
}

<label>Nationality</label><br>
<select>
  <option value="AU">AU</option>
  <option value="EU">EU</option>
  <option value="US">US</option>
  <option value="AS">AS</option>
  <option value="AF">AF</option>
</select><br>
<button>Submit Nationality status</button>


问:
OpenLayer export map to Image
I´m using Angular 8

I´m trying to export a image/blob of my map created with openlayer but i just cant get it to work. I even tryed using ViewChild with html2canvas but then i just get everything inside the div besides the map.

```<code>     @ViewChild('download', { static: false }) public download: ElementRef;

    pdfDownload() {
    let domElement = this.download.nativeElement as HTMLElement;
    console.log(domElement);
    html2canvas(domElement).then(canvas => {
      var imgData = canvas.toDataURL("image/png");
      console.log(imgData); //here i get a blob that has everything from the div like buttons and so on, but not the map itself thats also inside this div
      });
  }
</code>```

I did see some javascript versions with openlayer were they managed to download it without using other libs but i cant manage to translate it to typescript.

Anyone that knows how to get this to work eather just using openlayer or with the html2canvas lib? Or mby even something else?

Also tryed the following with no sucess since its basicly the same thing

```<code> pdfDownload() {
    var cnvs = document.getElementById('map');
    html2canvas(cnvs).then(canvas => {
      var imgData = canvas.toDataURL("image/png");
      console.log(imgData); //here i get a blob that has everything from the div like buttons and so on, but not the map itself thats also inside this div
    });
  }
</code>```

答: You can use ol-ext print control that encapsulate print in a control.</p>

Title: OpenLayer export map to Image

Body:
I´m using Angular 8

I´m trying to export a image/blob of my map created with openlayer but i just cant get it to work. I even tryed using ViewChild with html2canvas but then i just get everything inside the div besides the map.

     @ViewChild('download', { static: false }) public download: ElementRef;

    pdfDownload() {
    let domElement = this.download.nativeElement as HTMLElement;
    console.log(domElement);
    html2canvas(domElement).then(canvas => {
      var imgData = canvas.toDataURL("image/png");
      console.log(imgData); //here i get a blob that has everything from the div like buttons and so on, but not the map itself thats also inside this div
      });
  }

I did see some javascript versions with openlayer were they managed to download it without using other libs but i cant manage to translate it to typescript.

Anyone that knows how to get this to work eather just using openlayer or with the html2canvas lib? Or mby even something else?

Also tryed the following with no sucess since its basicly the same thing

 pdfDownload() {
    var cnvs = document.getElementById('map');
    html2canvas(cnvs).then(canvas => {
      var imgData = canvas.toDataURL("image/png");
      console.log(imgData); //here i get a blob that has everything from the div like buttons and so on, but not the map itself thats also inside this div
    });
  }


问:
Clickable image using Javascript and Facebook graph API
I have this piece of code:

```<code>function fbFetch(){
      //Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
      var url = "http://graph.facebook.com/10150171084863204/photos?limit=3&type=small&callback=?";

        //Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
        $.getJSON(url,function(json){
            var html = "<ul>";
            html += '<li><img src="foto.jpg" /></li>';
                //loop through and within data array's retrieve the message variable.
                $.each(json.data,function(i,fb){

                 html += '<li><img class="fbimg" alt="" src="' + fb.picture + '" /></li>';
                });
            html += '<li><a href=""><img src="fotolain.jpg" border="0" /></a></li>';
            html += "</ul>";

        $('.facebookfeed').html(html);

        });

    };
</code>```

And this image will produce 3 images from the Facebook album. I would like for each image to be clickable and when a user clicks the image, the big image from the Facebook album will be shown.

Now how do I achieve that?

答:
```<code><a href="path-to-your-big-image.jpg"><img src="path-to-your-small-image.jpg"/></a>
</code>```

simple as this. now you can integrate this idea o anyplace. Whether it be the FB api or somewhere else.

ContentLicense: CC BY-SA 3.0

Body:
I have this piece of code:

function fbFetch(){
      //Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
      var url = "http://graph.facebook.com/10150171084863204/photos?limit=3&type=small&callback=?";

        //Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
        $.getJSON(url,function(json){
            var html = "
";
            html += '

';
                //loop through and within data array's retrieve the message variable.
                $.each(json.data,function(i,fb){

                 html += '

';
                });
            html += '

';
            html += "
";

        $('.facebookfeed').html(html);

        });

    };

And this image will produce 3 images from the Facebook album. I would like for each image to be clickable and when a user clicks the image, the big image from the Facebook album will be shown.

Now how do I achieve that?

Body:
<a href="path-to-your-big-image.jpg"><img src="path-to-your-small-image.jpg"/></a>

simple as this. now you can integrate this idea o anyplace. Whether it be the FB api or somewhere else.


问:
basic regex c++ - forward slash and dot
I want to match forward slash / and dot . using c++ regex_match. I read that \/ and \. works. But i get:

warning: unknown escape sequence: '\/',

warning: unknown escape sequence: '\.'

and string doesnt match correctly too

I have tried to set ECMAScript flag for my regex, like this:

```<code>std::regex succes_r("^Sth\/Sth\.Sth).*", std::regex_constants::ECMAScript)
</code>```

but nothing changed.

答:
C++ dont handle unknown escapes like \/ and \..

and should be  "^Sth/Sth\\.Sth).*" which is parsed and handed to

regex engine as ^Sth/Sth\.Sth).*

note that forward slash is not a regex special char.

Title: basic regex c++ - forward slash and dot

Body:
I want to match forward slash / and dot . using c++ regex_match. I read that \/ and \. works. But i get:

warning: unknown escape sequence: '\/',

warning: unknown escape sequence: '\.'

and string doesnt match correctly too

I have tried to set ECMAScript flag for my regex, like this:

std::regex succes_r("^Sth\/Sth\.Sth).*", std::regex_constants::ECMAScript)

but nothing changed.


问:
Parsing an email subject header
I'm using net/mail to read email messages with Go:

```<code>msg, _ := mail.ReadMessage(f)
subject := msg.Header.Get("Subject")
fmt.Printf("Subject = %v", subject)
</code>```

And I'm having trouble figuring out how to decode the subject when it has special characters and the mail provider converts it from plain text into encoded text.

For example, if an email is sent with "It’s a test" -- note that's a right curly quote -- then that subject ultimately gets UTF-8 encoded, I think with hex values, into this:

=?UTF-8?Q?It=E2=80=99s_a_test?=

My questions are:

What's the correct terminology to use for describing the encoding that's going on here?

What library would I uses to decode that string above (=?UTF-8?Q?It=E2=80=99s_a_test?=) back into It’s a test before doing what I need to do with it (display it, put it in a database, etc)

答:
Found the answer by searching golang =?UTF-8?Q? and seeing the functions available in Go's mime package

https://golang.org/pkg/mime/#WordDecoder.DecodeHeader

Title: Parsing an email subject header

Body:
I'm using net/mail to read email messages with Go:

msg, _ := mail.ReadMessage(f)
subject := msg.Header.Get("Subject")
fmt.Printf("Subject = %v", subject)

And I'm having trouble figuring out how to decode the subject when it has special characters and the mail provider converts it from plain text into encoded text.

For example, if an email is sent with "It’s a test" -- note that's a right curly quote -- then that subject ultimately gets UTF-8 encoded, I think with hex values, into this:

=?UTF-8?Q?It=E2=80=99s_a_test?=

My questions are:

What's the correct terminology to use for describing the encoding that's going on here?

What library would I uses to decode that string above (=?UTF-8?Q?It=E2=80=99s_a_test?=) back into It’s a test before doing what I need to do with it (display it, put it in a database, etc)


问:
In Excel VBA get an Error 1004 whilst running a loop in real time, it works fine when I skip through line by line using debugger
I made some code to loop backwards through some records eliminating records where a string concatenating values from several fields indicated duplicate value existing.  It battered my head building the thing but it seemed to work fine when I ran it earlier and also no problems when I stepped through the macro using the debugger but now it won't run properly and I don't understand why.  It gives an error 1004 - Application-defined or Object defined error at the point where I concatenate the contents of several cells to make a string.

I wondered if it might be a system-resource kind of problem but really don't understand how that could be.

```<code>Private Sub RemoveDuplicates(Endrow)
' A sub to remove data where Species, Location (Lat and Long) and accuracy are all the same and to return the most recent year
' whilst ignoring older records.
' This leaves the lowest row number of a set of duplicates since the sheet has been sorted by the previous function to put
' The highest date on the lowest row number.

Endrow = Range("A1").End(xlDown).Row
EndCol = Range("A1").End(xlToRight).Column

Dim iString As String
Dim iPlusString As String
Dim i As Integer

With ActiveSheet
For i = Endrow To 2 Step -1
Startloop:
iString = .Cells(i, 1).Value & .Cells(i, 2).Value & .Cells(i, 3).Value & .Cells(i, 12).Value
iPlusString = .Cells(i + 1, 1).Value & .Cells(i + 1, 2).Value & .Cells(i + 1, 3).Value & .Cells(i + 1, 12).Value

'This was just to watch where the data was to make things easier.
'Rows(i).Select

    If i = Endrow Then
    i = i - 1
    GoTo Startloop
    Else
        If Stringi = iPlusString Then
        Rows(i + 1).Delete
        Else
        i = i - 1
        GoTo Startloop
        End If
    End If
Next
End With
End Sub

</code>```

答:
Perhaps using the RemoveDuplicates method of the Range object would be simpler.

Without your data to test on, something like:

```<code>Option Explicit
Sub RemoveDuplicates()
    Dim endRow As Long, endCol As Long, dtCol As Long
    Dim WS As Worksheet
    Dim rg As Range

Set WS = Worksheets("sheet3")
With WS
    endRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    endCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    Set rg = .Range(.Cells(1, 1), .Cells(endRow, endCol))
    dtCol = rg.Rows(1).Find(what:="Date").Column
End With

'Optional to Sort with most recent date first, if not already sorted this way
rg.Sort key1:=rg.Columns(dtCol), order1:=xlDescending, Header:=xlYes

'remove duplicates
rg.RemoveDuplicates Array(1, 2, 3, 12), xlYes

End Sub
</code>```

Body:
I made some code to loop backwards through some records eliminating records where a string concatenating values from several fields indicated duplicate value existing.  It battered my head building the thing but it seemed to work fine when I ran it earlier and also no problems when I stepped through the macro using the debugger but now it won't run properly and I don't understand why.  It gives an error 1004 - Application-defined or Object defined error at the point where I concatenate the contents of several cells to make a string.

I wondered if it might be a system-resource kind of problem but really don't understand how that could be.

Private Sub RemoveDuplicates(Endrow)
' A sub to remove data where Species, Location (Lat and Long) and accuracy are all the same and to return the most recent year
' whilst ignoring older records.
' This leaves the lowest row number of a set of duplicates since the sheet has been sorted by the previous function to put
' The highest date on the lowest row number.

Endrow = Range("A1").End(xlDown).Row
EndCol = Range("A1").End(xlToRight).Column

Dim iString As String
Dim iPlusString As String
Dim i As Integer

With ActiveSheet
For i = Endrow To 2 Step -1
Startloop:
iString = .Cells(i, 1).Value & .Cells(i, 2).Value & .Cells(i, 3).Value & .Cells(i, 12).Value
iPlusString = .Cells(i + 1, 1).Value & .Cells(i + 1, 2).Value & .Cells(i + 1, 3).Value & .Cells(i + 1, 12).Value

'This was just to watch where the data was to make things easier.
'Rows(i).Select

    If i = Endrow Then
    i = i - 1
    GoTo Startloop
    Else
        If Stringi = iPlusString Then
        Rows(i + 1).Delete
        Else
        i = i - 1
        GoTo Startloop
        End If
    End If
Next
End With
End Sub

Body:
Perhaps using the RemoveDuplicates method of the Range object would be simpler.

Without your data to test on, something like:

Option Explicit
Sub RemoveDuplicates()
    Dim endRow As Long, endCol As Long, dtCol As Long
    Dim WS As Worksheet
    Dim rg As Range

Set WS = Worksheets("sheet3")
With WS
    endRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    endCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    Set rg = .Range(.Cells(1, 1), .Cells(endRow, endCol))
    dtCol = rg.Rows(1).Find(what:="Date").Column
End With

'Optional to Sort with most recent date first, if not already sorted this way
rg.Sort key1:=rg.Columns(dtCol), order1:=xlDescending, Header:=xlYes

'remove duplicates
rg.RemoveDuplicates Array(1, 2, 3, 12), xlYes

End Sub


问:
Node-config won't use variables from custom-environment-variables.json in Heroku
I'm using the node-config module for mongo connection strings and jwt keys.

For example:

```<code>if(!config.get('jwtPrivateKey')){
    throw new Error('FATAL ERROR: jwtPrivateKey is not defined');
</code>```

My custom-environment-variables.json file looks like:

```<code>{
    "jwtPrivateKey": "video-app_jwtPrivateKey",
    "db": "video-app_db"
}
</code>```

default.json

```<code>{
    "db": "default db",
    "jwtPrivateKey": "default key"
}
</code>```

production.json

```<code>{
    "db": "production db",
    "jwtPrivateKey": "production key"
}
</code>```

long story short - although the environment variables are set in heroku, node-config doesn't look at the values set in custom-environment-variables.json. I can alter the NODE_ENV and get the relevant json file's hardcoded values, but the environment variables are never used, which seems to contradict the docs

答:
So, I had the same issue: I deployed my app, set environment variables in Heroku, but nothing worked (unlike my local machine where everything was fine).

Seems like the problem was that I accidentally added all the node_modules folder to git. It happened because I created a .gitignore file after the initial commit was made (if I get it right).

What I did, that worked for me:
I removed node_modules from git and committed/pushed changes to Heroku:

git rm -rf node_modules
```

then commit and push.

This was the error message I got:

Error: /app/node_modules/bcrypt/lib/binding/bcrypt_lib.node: invalid ELF header

I spent two days trying to figure it out.

I hope it's helpful.

Body:
I'm using the node-config module for mongo connection strings and jwt keys.

For example:

if(!config.get('jwtPrivateKey')){
    throw new Error('FATAL ERROR: jwtPrivateKey is not defined');

My custom-environment-variables.json file looks like:

{
    "jwtPrivateKey": "video-app_jwtPrivateKey",
    "db": "video-app_db"
}

default.json

{
    "db": "default db",
    "jwtPrivateKey": "default key"
}

production.json

{
    "db": "production db",
    "jwtPrivateKey": "production key"
}

long story short - although the environment variables are set in heroku, node-config doesn't look at the values set in custom-environment-variables.json. I can alter the NODE_ENV and get the relevant json file's hardcoded values, but the environment variables are never used, which seems to contradict the docs

Body:
So, I had the same issue: I deployed my app, set environment variables in Heroku, but nothing worked (unlike my local machine where everything was fine).

Seems like the problem was that I accidentally added all the node_modules folder to git. It happened because I created a .gitignore file after the initial commit was made (if I get it right).

What I did, that worked for me:
I removed node_modules from git and committed/pushed changes to Heroku:

git rm -rf node_modules

then commit and push.

This was the error message I got:

Error: /app/node_modules/bcrypt/lib/binding/bcrypt_lib.node: invalid ELF header

I spent two days trying to figure it out.

I hope it's helpful.


问:
How to overlap box-shadows on table rows?
I have a table on which I want to highlight a number of successive rows (TR's) by applying a box-shadow around them.

My strategy was to apply a class called "selected-top" to the first row of the selection, classes "selected-middle" for the middle part, and "selected-bottom" for the last row.

However, the shadows of the middle rows bleed over. I tried to rectify this by using z-index (I know that I have to add a relative property with that, so I did), but they seem to have no effect:

Here's the code:

```<code>  tr.selected-top {
    box-shadow: -5px -5px 5px #000, 5px -5px 5px #000;
    position: relative;
    z-index:10;
  }
  tr.selected-middle {
    box-shadow: -5px 0px 5px #000, 5px 0px 5px #000;
    position: relative;
    z-index: -1;
  }
</code>```

The table is just a regular table:

```<code><table>
<tr><td>stuff</td></tr>
<tr class="selected-top"><td>highlighting starts</td></tr>
<tr class="selected-middle"><td>highlighting middle</td></tr>
<tr class="selected-bottom"><td>highlighting end</td></tr>
<tr><td>other stuff</td></tr>
</table>
</code>```

What am I doing wrong?

By the way, I did try to only apply a shadow to only the sides for the middle rows, but that way the shadow is not continuous.

Update: @Aditya Toke, like so: (left is wrong shading, right is correct shading)

答:
You can achieve it using ::before and ::after pseudo elements to mask the top and bottom shadow from "middle" row.

The height of the pseudo elements is set exactly equal to the length of the shadow for masking and is absolute position.

Since the shadow hides the top borders of selected-bottom and it's next sibling element we need to add them back as:

```<code>tr.selected-middle td,
tr.selected-bottom td {
  border-bottom: 1px solid #666;
}
</code>```

body {
  background-color: #1b1b1b;
  margin: 20px;
}
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: auto;
  box-sizing: border-box;
  border: none;
  margin: auto;
}

tr { display: block; }
tr, td {
  height: 50px;
  background: #333;
  color: #eee;
}

td {
  padding-left: 16px;
  min-width: 170px;
  width: 100%;
  border-top: 1px solid #666;
}
tr.selected-top {
    position: relative;
    box-shadow: -5px -5px 5px #000, 5px -5px 5px #000;
}
tr.selected-middle {
    position: relative;
    box-shadow: 0px 0px 5px 5px #000;
}
tr.selected-bottom {
    position: relative;
    box-shadow: 5px 5px 5px #000, -5px 5px 5px #000;

}
tr.selected-middle ::before,
tr.selected-middle ::after {
    pointer-events: none;
    position: absolute;
    content:" ";
    background-color: #333;
    left: 0;
    width: 100%;
}
tr.selected-middle ::before {
    height: 10px;
    top: -10px;
}
tr.selected-middle ::after {
    top: calc(100% + 4px);
    height: 5px;
}

tr.selected-middle td,
tr.selected-bottom td {
  border-bottom: 1px solid #666;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
        <td>Some stuffs</td>
    </tr>
    <tr class="selected-top">
        <td>highlighting starts</td>
    </tr>
    <tr class="selected-middle">
        <td>highlighting middle</td>
    </tr>
    <tr class="selected-bottom">
        <td>highlighting ends</td>
    </tr>
     <tr>
        <td>Some stuffs</td>
    </tr>
  </tbody>
</table></code>```

Body:
I have a table on which I want to highlight a number of successive rows (TR's) by applying a box-shadow around them.

My strategy was to apply a class called "selected-top" to the first row of the selection, classes "selected-middle" for the middle part, and "selected-bottom" for the last row.

However, the shadows of the middle rows bleed over. I tried to rectify this by using z-index (I know that I have to add a relative property with that, so I did), but they seem to have no effect:

Here's the code:

  tr.selected-top {
    box-shadow: -5px -5px 5px #000, 5px -5px 5px #000;
    position: relative;
    z-index:10;
  }
  tr.selected-middle {
    box-shadow: -5px 0px 5px #000, 5px 0px 5px #000;
    position: relative;
    z-index: -1;
  }

The table is just a regular table:

stuff

highlighting starts

highlighting middle

highlighting end

other stuff

What am I doing wrong?

By the way, I did try to only apply a shadow to only the sides for the middle rows, but that way the shadow is not continuous.

Update: @Aditya Toke, like so: (left is wrong shading, right is correct shading)

Body:
You can achieve it using ::before and ::after pseudo elements to mask the top and bottom shadow from "middle" row.

The height of the pseudo elements is set exactly equal to the length of the shadow for masking and is absolute position.

Since the shadow hides the top borders of selected-bottom and it's next sibling element we need to add them back as:

tr.selected-middle td,
tr.selected-bottom td {
  border-bottom: 1px solid #666;
}

body {
  background-color: #1b1b1b;
  margin: 20px;
}
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: auto;
  box-sizing: border-box;
  border: none;
  margin: auto;
}

tr { display: block; }
tr, td {
  height: 50px;
  background: #333;
  color: #eee;
}

td {
  padding-left: 16px;
  min-width: 170px;
  width: 100%;
  border-top: 1px solid #666;
}
tr.selected-top {
    position: relative;
    box-shadow: -5px -5px 5px #000, 5px -5px 5px #000;
}
tr.selected-middle {
    position: relative;
    box-shadow: 0px 0px 5px 5px #000;
}
tr.selected-bottom {
    position: relative;
    box-shadow: 5px 5px 5px #000, -5px 5px 5px #000;

}
tr.selected-middle ::before,
tr.selected-middle ::after {
    pointer-events: none;
    position: absolute;
    content:" ";
    background-color: #333;
    left: 0;
    width: 100%;
}
tr.selected-middle ::before {
    height: 10px;
    top: -10px;
}
tr.selected-middle ::after {
    top: calc(100% + 4px);
    height: 5px;
}

tr.selected-middle td,
tr.selected-bottom td {
  border-bottom: 1px solid #666;
}

<table>
  <tbody>
    <tr>
        <td>Some stuffs</td>
    </tr>
    <tr class="selected-top">
        <td>highlighting starts</td>
    </tr>
    <tr class="selected-middle">
        <td>highlighting middle</td>
    </tr>
    <tr class="selected-bottom">
        <td>highlighting ends</td>
    </tr>
     <tr>
        <td>Some stuffs</td>
    </tr>
  </tbody>
</table>


问:
Errors with freeze table header - HTML
I am trying to enter entries in table inputs for my inventory website. I want to freeze the headers of each column and tried doing it with this -> Freeze the top row for an html table only (Fixed Table Header Scrolling)

window.onload = function(){
  var to_show = '';
  for(var i = 1 ; i < 50 ; i++){
    to_show += '
<input type="text" autocomplete="off" id="product_name_'+ i +'" name="product_name_'+i+'" onkeyup="productSearch(this.value, '+i+')" tabindex="-1" style="font-size:larger;">	';
    to_show += '<input type="text" autocomplete="off" id="location_'+ i +'" name="location_'+ i +'" onkeyup="productSearch(this.value, '+ i +')" tabindex="-1" style="font-size:larger;">
';
  }
  document.getElementById('addInside_tr_20').innerHTML = to_show;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url("https://fonts.googleapis.com/css?family=Montserrat:300,400|Oswald:200,300,400&display=swap");
:root {
  --purple-theme: #091428;
  --lightpurple-theme: #0f3a41;
  --gray-bg-heading: #b8b8b8;
  --gray-bg-sidebar: #dee3e7;
  --lightgreen-theme: #65ffce;
  --green-theme: #46b692;
  --red-theme: #f75b54;
}
/* width */
::-webkit-scrollbar {
  width: 10px;
}
/* Track */
::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px grey;
  border-radius: 0px 0px 10px 10px;
  background: var(--lightpurple-theme);
}
/* Handle */
::-webkit-scrollbar-thumb {
  background: var(--green-theme);
  border-radius: 0 0 10px 10px;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
  background: var(--lightgreen-theme);
}
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
::-moz-selection {
  /* Code for Firefox */
  color: var(--purple-theme);
  background: var(--green-theme);
}
::selection {
  color: var(--purple-theme);
  background: var(--green-theme);
}
input:focus,
option:focus,
select:focus {
  outline-color: var(--lightgreen-theme);
}
body {
  height: 100%;
  background-repeat: no-repeat;
}
a {
  text-decoration: none;
}
table,
select,
input,
a {
  color: whitesmoke;
}
input {
  width: 100%;
  line-height: 5px;
  font-size: 10px;
}
input[type="text"],
input[type="url"],
input[type="number"] {
  height: 30px;
  border: 1px solid var(--green-theme);
  background-color: transparent;
  color: whitesmoke;
  font-size: 15px;
}
input[type="button"],
input[type="reset"],
input[type="submit"] {
  border: 1px solid var(--green-theme);
  background-color: var(--green-theme);
  color: var(--purple-theme);
  text-decoration-style: bold;
  font-size: 15px;
  border-radius: 0px 15px 15px 0px;
}

/* ------grid container------ */
input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
}
input[type="date"] {
  height: 100%;
}
.grid_container {
  display: grid;
  grid-template-columns: repeat(auto, 1fr);
  grid-gap: 10px;
  padding: 10px;
  margin: 0 auto;
  color: whitesmoke;
}
.grid {
  background-color: var(--purple-theme);
  border: 1px solid lightgrey;
  padding: 20px;
}
.inside > span {
  font-family: "Oswald", sans-serif;
  font-weight: 400;
  font-size: 18px;
}
.item1 {
  grid-column: 1 / 3;
}
.item2 {
  grid-column: 3 / 5;
}

.item3 {
  grid-column: 5 / 7;
}
.item4 {
  grid-column: 7 / 9;
}

.item5 {
  grid-column: 1 / 9;
}

.inside {
  padding: 0;
  padding-bottom: 10px;
  border: none;
}

.item2 {
  grid-column: 1 / 9;
  grid-row: 1 / 5;
}
.inside input[type="text"] {
  width: 200px;
}
.item2 select,
.item2 option {
  width: 100%;
  height: 30px;
  background-color: var(--purple-theme);
  border: 1px solid var(--green-theme);
  text-align: center;
}
.item2 select option {
  background: var(--purple-theme);
}
.item2 table {
  width: 100%;
  text-align: center;
  margin-top: 20px;
  font-size: 20px;
}
.details table:nth-child(1) {
  margin-top: -20px;
}
.details {
  margin-top: -20px;
}
.item2 th {
  background-color: var(--green-theme);
  color: var(--purple-theme);
  padding: 15px;
}
.item2 a {
  text-decoration: underline;
}

/* main edit here start */
                      #text-area td:nth-child(1) {
                        width: 80%;
                      }
                      #text-area td:nth-child(2) {
                        width: 20%;
                      }
                      #text-area thead th:nth-child(1) {
                        width: 80%;
                      }
                      #text-area thead th:nth-child(2) {
                        width: 20%;
                      }

                      #text-area thead {
                        display: block;
                      }
                      #text-area tbody {
                        height: 440px;
                        display: block;
                        overflow: auto;
                        width: 100%;
                      }
                      #text-area input {
                        width: 100%;
                      }

                      #text-area input {
                        border: none;
                      }
                      #text-area {
                        border: 1px solid var(--green-theme);
                      }
                      #text-area tr:nth-child(2n + 1) {
                        background: var(--lightpurple-theme);
                      }
                      #text-area td:nth-child(4) {
                        border-right: none;
                      }
                      #text-area td {
                        border-right: 1px solid var(--green-theme);
                      }
/* main edit here ends */
.item2 .inside table * {
  padding-bottom: 20px;
}

.suggestion {
  position: absolute;
  background-color: var(--purple-theme);
  font-size: smaller;
  cursor: pointer;
}
.suggestion_i:hover {
  color: var(--purple-theme);
  background-color: var(--green-theme);
}
.suggestion_i {
  cursor: pointer;
  text-align: center;
  text-justify: center;
  padding: 10px 10px -5px 10px;
}
#sorted_div {
  background-color: var(--purple-theme);
  /*position:absolute;*/
  top: 123px;
}
#sorted_div tr:nth-child(2n + 1) {
  background: var(--lightpurple-theme);
}</code>```

              <form action="php/invoiceFetch.php" method="post" enctype="multipart/form-data" id='myForm' onkeypress="return event.keyCode != 13;">

                    Location :
                    <input type="text" autocomplete="off" name="invoice_name" id="invoice_name" onchange="invoiceSpliter()" onkeyup="customerSearch(this.value)" style="width: 500;">
                    Product Suggestion :

                    Product Name
                    Current Locations

                  <input type="reset" value="Reset" tabindex="-1">
                  <input type="button" onclick="document.getElementById('myModal').style.display = 'block';" value="Submit">

              </form>

```

You can check the code on [codepen]{https://codepen.io/zaidi2293/pen/WNwmJrP} (Ignore most of the css as they are just to replicate what I had so that I don't miss something out)

(Sorry for the extensive code length) The Problem is the "thead" is not aligned with "tbody" as in column perspective because of overflow in vertical direction. I've asked this question before but that doesn't seem to work for me. Also, there will be some more columns added in the future. No custom size width answers please

答:
You could set input box width 100% and add pixels width to th and td, instead of percentages.,
The input box width 100% will help to set it to its parent width and remove its default width. The pixels can help to have a fixed width and alignment problems.

table{
  border: 1px solid;
}
#text-area{
  border: 1px solid;
}

#text-area td:nth-child(1){
  width: 100px;
}
#text-area td:nth-child(2){
  width: 200px;
}
#text-area td:nth-child(3){
  width: 100px;
}
#text-area td:nth-child(4){
  width: 100px;
}

#text-area thead th:nth-child(1){
  width: 100px;
}
#text-area thead th:nth-child(2){
  width: 200px;
}
#text-area thead th:nth-child(3){
  width: 100px;
}
#text-area thead th:nth-child(4){
  width: 100px;
}

#text-area thead{
  display:block;
}
#text-area  tbody{
  height:200px;
  display:block;
  overflow:auto;
}
  #text-area input{
width:100%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="text-area">
  <thead>
    <tr>
      <th><label >Barcode</label></th>
      <th><label >Product Name</label></th>
      <th><label >Count</label></th>
      <th><label >QB-Price / Online Price</label></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="text" value="772696001844"></td>
      <td><input type="text" value="ACTIVATED CHARCOAL (COCONUT BASE) 114g" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696023815"></td>
      <td><input type="text" value="BILBERRY FRUIT POWDER" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696037607"></td>
      <td><input type="text" value="BUCKTHORN BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696044803"></td>
      <td><input type="text" value="CASCARA BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696044803"></td>
      <td><input type="text" value="CASCARA BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696042007"></td>
      <td><input type="text" value="CHAMOMILE FLOWER WHOLE" ></td>
      <td><input type="text" value="6" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696066805"></td>
      <td><input type="text" value="DAMIANA LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696066805"></td>
      <td><input type="text" value="DAMIANA LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696067208"></td>
      <td><input type="text" value="DANDELION LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696067208"></td>
      <td><input type="text" value="DANDELION LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696084007"></td>
      <td><input type="text" value="FRANKINCENSE TEARS" ></td>
      <td><input type="text" value="4" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696087008"></td>
      <td><input type="text" value="GENTIAN ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696087008"></td>
      <td><input type="text" value="GENTIAN ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696108208"></td>
      <td><input type="text" value="HIBISCUS FLOWER WHOLE" ></td>
      <td><input type="text" value="6" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696112809"></td>
      <td><input type="text" value="HYSSOP HERB POWDER" ></td>
      <td><input type="text" value="2" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696124604"></td>
      <td><input type="text" value="LICORICE ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696124604"></td>
      <td><input type="text" value="LICORICE ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
  </tbody>
</table></code>```

Title: Errors with freeze table header - HTML

Body:
I am trying to enter entries in table inputs for my inventory website. I want to freeze the headers of each column and tried doing it with this -> Freeze the top row for an html table only (Fixed Table Header Scrolling)

window.onload = function(){
  var to_show = '';
  for(var i = 1 ; i < 50 ; i++){
    to_show += '
<input type="text" autocomplete="off" id="product_name_'+ i +'" name="product_name_'+i+'" onkeyup="productSearch(this.value, '+i+')" tabindex="-1" style="font-size:larger;">	';
    to_show += '<input type="text" autocomplete="off" id="location_'+ i +'" name="location_'+ i +'" onkeyup="productSearch(this.value, '+ i +')" tabindex="-1" style="font-size:larger;">
';
  }
  document.getElementById('addInside_tr_20').innerHTML = to_show;
}

@import url("https://fonts.googleapis.com/css?family=Montserrat:300,400|Oswald:200,300,400&display=swap");
:root {
  --purple-theme: #091428;
  --lightpurple-theme: #0f3a41;
  --gray-bg-heading: #b8b8b8;
  --gray-bg-sidebar: #dee3e7;
  --lightgreen-theme: #65ffce;
  --green-theme: #46b692;
  --red-theme: #f75b54;
}
/* width */
::-webkit-scrollbar {
  width: 10px;
}
/* Track */
::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px grey;
  border-radius: 0px 0px 10px 10px;
  background: var(--lightpurple-theme);
}
/* Handle */
::-webkit-scrollbar-thumb {
  background: var(--green-theme);
  border-radius: 0 0 10px 10px;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
  background: var(--lightgreen-theme);
}
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
::-moz-selection {
  /* Code for Firefox */
  color: var(--purple-theme);
  background: var(--green-theme);
}
::selection {
  color: var(--purple-theme);
  background: var(--green-theme);
}
input:focus,
option:focus,
select:focus {
  outline-color: var(--lightgreen-theme);
}
body {
  height: 100%;
  background-repeat: no-repeat;
}
a {
  text-decoration: none;
}
table,
select,
input,
a {
  color: whitesmoke;
}
input {
  width: 100%;
  line-height: 5px;
  font-size: 10px;
}
input[type="text"],
input[type="url"],
input[type="number"] {
  height: 30px;
  border: 1px solid var(--green-theme);
  background-color: transparent;
  color: whitesmoke;
  font-size: 15px;
}
input[type="button"],
input[type="reset"],
input[type="submit"] {
  border: 1px solid var(--green-theme);
  background-color: var(--green-theme);
  color: var(--purple-theme);
  text-decoration-style: bold;
  font-size: 15px;
  border-radius: 0px 15px 15px 0px;
}

/* ------grid container------ */
input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
}
input[type="date"] {
  height: 100%;
}
.grid_container {
  display: grid;
  grid-template-columns: repeat(auto, 1fr);
  grid-gap: 10px;
  padding: 10px;
  margin: 0 auto;
  color: whitesmoke;
}
.grid {
  background-color: var(--purple-theme);
  border: 1px solid lightgrey;
  padding: 20px;
}
.inside > span {
  font-family: "Oswald", sans-serif;
  font-weight: 400;
  font-size: 18px;
}
.item1 {
  grid-column: 1 / 3;
}
.item2 {
  grid-column: 3 / 5;
}

.item3 {
  grid-column: 5 / 7;
}
.item4 {
  grid-column: 7 / 9;
}

.item5 {
  grid-column: 1 / 9;
}

.inside {
  padding: 0;
  padding-bottom: 10px;
  border: none;
}

.item2 {
  grid-column: 1 / 9;
  grid-row: 1 / 5;
}
.inside input[type="text"] {
  width: 200px;
}
.item2 select,
.item2 option {
  width: 100%;
  height: 30px;
  background-color: var(--purple-theme);
  border: 1px solid var(--green-theme);
  text-align: center;
}
.item2 select option {
  background: var(--purple-theme);
}
.item2 table {
  width: 100%;
  text-align: center;
  margin-top: 20px;
  font-size: 20px;
}
.details table:nth-child(1) {
  margin-top: -20px;
}
.details {
  margin-top: -20px;
}
.item2 th {
  background-color: var(--green-theme);
  color: var(--purple-theme);
  padding: 15px;
}
.item2 a {
  text-decoration: underline;
}

/* main edit here start */
                      #text-area td:nth-child(1) {
                        width: 80%;
                      }
                      #text-area td:nth-child(2) {
                        width: 20%;
                      }
                      #text-area thead th:nth-child(1) {
                        width: 80%;
                      }
                      #text-area thead th:nth-child(2) {
                        width: 20%;
                      }

                      #text-area thead {
                        display: block;
                      }
                      #text-area tbody {
                        height: 440px;
                        display: block;
                        overflow: auto;
                        width: 100%;
                      }
                      #text-area input {
                        width: 100%;
                      }

                      #text-area input {
                        border: none;
                      }
                      #text-area {
                        border: 1px solid var(--green-theme);
                      }
                      #text-area tr:nth-child(2n + 1) {
                        background: var(--lightpurple-theme);
                      }
                      #text-area td:nth-child(4) {
                        border-right: none;
                      }
                      #text-area td {
                        border-right: 1px solid var(--green-theme);
                      }
/* main edit here ends */
.item2 .inside table * {
  padding-bottom: 20px;
}

.suggestion {
  position: absolute;
  background-color: var(--purple-theme);
  font-size: smaller;
  cursor: pointer;
}
.suggestion_i:hover {
  color: var(--purple-theme);
  background-color: var(--green-theme);
}
.suggestion_i {
  cursor: pointer;
  text-align: center;
  text-justify: center;
  padding: 10px 10px -5px 10px;
}
#sorted_div {
  background-color: var(--purple-theme);
  /*position:absolute;*/
  top: 123px;
}
#sorted_div tr:nth-child(2n + 1) {
  background: var(--lightpurple-theme);
}

              <form action="php/invoiceFetch.php" method="post" enctype="multipart/form-data" id='myForm' onkeypress="return event.keyCode != 13;">

                    Location :
                    <input type="text" autocomplete="off" name="invoice_name" id="invoice_name" onchange="invoiceSpliter()" onkeyup="customerSearch(this.value)" style="width: 500;">
                    Product Suggestion :

                    Product Name
                    Current Locations

                  <input type="reset" value="Reset" tabindex="-1">
                  <input type="button" onclick="document.getElementById('myModal').style.display = 'block';" value="Submit">

              </form>

You can check the code on [codepen]{https://codepen.io/zaidi2293/pen/WNwmJrP} (Ignore most of the css as they are just to replicate what I had so that I don't miss something out)

(Sorry for the extensive code length) The Problem is the "thead" is not aligned with "tbody" as in column perspective because of overflow in vertical direction. I've asked this question before but that doesn't seem to work for me. Also, there will be some more columns added in the future. No custom size width answers please

Body:
You could set input box width 100% and add pixels width to th and td, instead of percentages.,
The input box width 100% will help to set it to its parent width and remove its default width. The pixels can help to have a fixed width and alignment problems.

table{
  border: 1px solid;
}
#text-area{
  border: 1px solid;
}

#text-area td:nth-child(1){
  width: 100px;
}
#text-area td:nth-child(2){
  width: 200px;
}
#text-area td:nth-child(3){
  width: 100px;
}
#text-area td:nth-child(4){
  width: 100px;
}

#text-area thead th:nth-child(1){
  width: 100px;
}
#text-area thead th:nth-child(2){
  width: 200px;
}
#text-area thead th:nth-child(3){
  width: 100px;
}
#text-area thead th:nth-child(4){
  width: 100px;
}

#text-area thead{
  display:block;
}
#text-area  tbody{
  height:200px;
  display:block;
  overflow:auto;
}
  #text-area input{
width:100%
}

<table id="text-area">
  <thead>
    <tr>
      <th><label >Barcode</label></th>
      <th><label >Product Name</label></th>
      <th><label >Count</label></th>
      <th><label >QB-Price / Online Price</label></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="text" value="772696001844"></td>
      <td><input type="text" value="ACTIVATED CHARCOAL (COCONUT BASE) 114g" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696023815"></td>
      <td><input type="text" value="BILBERRY FRUIT POWDER" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696037607"></td>
      <td><input type="text" value="BUCKTHORN BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696044803"></td>
      <td><input type="text" value="CASCARA BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696044803"></td>
      <td><input type="text" value="CASCARA BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696042007"></td>
      <td><input type="text" value="CHAMOMILE FLOWER WHOLE" ></td>
      <td><input type="text" value="6" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696066805"></td>
      <td><input type="text" value="DAMIANA LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696066805"></td>
      <td><input type="text" value="DAMIANA LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696067208"></td>
      <td><input type="text" value="DANDELION LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696067208"></td>
      <td><input type="text" value="DANDELION LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696084007"></td>
      <td><input type="text" value="FRANKINCENSE TEARS" ></td>
      <td><input type="text" value="4" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696087008"></td>
      <td><input type="text" value="GENTIAN ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696087008"></td>
      <td><input type="text" value="GENTIAN ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696108208"></td>
      <td><input type="text" value="HIBISCUS FLOWER WHOLE" ></td>
      <td><input type="text" value="6" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696112809"></td>
      <td><input type="text" value="HYSSOP HERB POWDER" ></td>
      <td><input type="text" value="2" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696124604"></td>
      <td><input type="text" value="LICORICE ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696124604"></td>
      <td><input type="text" value="LICORICE ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
  </tbody>
</table>


问:
SQL query for finding how many books have more than 20 reviews
I am new to SQL queries and I am having trouble to the following problem. We have a table of book reviews (review_id, book_id,...) and a table review_good_bad (review_id, IsGood) that shows if the review is good or not.

Review_id of the table review_good_bad is a foreign key and IsGood is a boolean. I have to find how many books have at least 20 reviews.

I have tried this:

```<code>Select count(dinstict r.book_id)
From reviews r, review_good_bad rgb
Where r.review_id = rgb.review_id
Group by r.book_id
Having count (rgb.IsGood) >= 20
</code>```

However it is not what I am asking for. Any ideas?

Thanks in advance

答:
You can't aggregate on the column that you use in the GROUP BY clause.

Use your query as a subquery and aggregate on that:

```<code>select count(*)
from (
  select r.book_id
  from reviews r inner join review_good_bad rgb
  on r.review_id = rgb.review_id
  group by r.book_id
  having count(rgb.IsGood) >= 20
) t
</code>```

Body:
I am new to SQL queries and I am having trouble to the following problem. We have a table of book reviews (review_id, book_id,...) and a table review_good_bad (review_id, IsGood) that shows if the review is good or not.

Review_id of the table review_good_bad is a foreign key and IsGood is a boolean. I have to find how many books have at least 20 reviews.

I have tried this:

Select count(dinstict r.book_id)
From reviews r, review_good_bad rgb
Where r.review_id = rgb.review_id
Group by r.book_id
Having count (rgb.IsGood) >= 20

However it is not what I am asking for. Any ideas?

Thanks in advance

Body:
You can't aggregate on the column that you use in the GROUP BY clause.

Use your query as a subquery and aggregate on that:

select count(*)
from (
  select r.book_id
  from reviews r inner join review_good_bad rgb
  on r.review_id = rgb.review_id
  group by r.book_id
  having count(rgb.IsGood) >= 20
) t


问:
Gcc-4.2 failed with exit code 1 Error
I am getting this error when i am trying to build my app. In the simulator it works fine but when coming to build for ipa it gives the following error:

Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1

What is causing this error?

Edited

Ld
  build/halalgauge.build/Release-iphoneos/halalgauge.build/Objects-normal/armv6/halalgauge
  normal armv6 cd /Users/admin/Desktop/ShopSavvy setenv
  IPHONEOS_DEPLOYMENT_TARGET 4.2 setenv PATH
  "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
  /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 -arch
  armv6 -isysroot
  /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk
  -L/Users/admin/Desktop/ShopSavvy/build/Release-iphoneos -L/Users/admin/Desktop/ShopSavvy -L/Users/admin/Desktop/ShopSavvy/Classes/ZBarSDK -L/Users/admin/Desktop/ShopSavvy/Classes/ScannerKit-4.0.3 -F/Users/admin/Desktop/ShopSavvy/build/Release-iphoneos -filelist /Users/admin/Desktop/ShopSavvy/build/halalgauge.build/Release-iphoneos/halalgauge.build/Objects-normal/armv6/halalgauge.LinkFileList
  -Xlinker -map -Xlinker /Users/admin/Desktop/ShopSavvy/build/halalgauge.build/Release-iphoneos/halalgauge.build/halalgauge-LinkMap-normal-armv6.txt
  -dead_strip all_load -lstdc++ -miphoneos-version-min=4.2 -framework CoreGraphics -framework AVFoundation -framework CoreVideo -framework
  CoreMedia -framework Foundation -framework AudioToolbox -framework
  QuartzCore -framework UIKit -framework iAd -lsqlite3.0 -framework
  MessageUI -framework AddressBook -framework AddressBookUI -framework
  MapKit -framework CoreLocation -liconv -lScannerKit -framework
  SystemConfiguration -framework MediaPlayer -o
  /Users/admin/Desktop/ShopSavvy/build/halalgauge.build/Release-iphoneos/halalgauge.build/Objects-normal/armv6/halalgauge

arm-apple-darwin10-gcc-4.2.1: all_load: No such file or directory
  Command
  /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2
  failed with exit code 1

答: Restart your Mac, and if all else fails choose either LLVM-GCC or LLVM as a compiler.</p>

Title: Gcc-4.2 failed with exit code 1 Error


问:
Django management command doesn't flush stdout
I'm trying to print to console before and after processing that takes a while in a Django management command, like this:

```<code>import requests
import xmltodict

from django.core.management.base import BaseCommand

def get_all_routes():
    url = 'http://busopen.jeju.go.kr/OpenAPI/service/bis/Bus'

    r = requests.get(url)
    data = xmltodict.parse(r.content)

    return data['response']['body']['items']['item']

class Command(BaseCommand):

    help = 'Updates the database via Bus Info API'

    def handle(self, *args, **options):
        self.stdout.write('Saving routes ... ', ending='')
        for route in get_all_routes():
            route_obj = Route(
                route_type=route['routeTp'], route_id=route['routeId'], route_number=route['routeNum'])
            route_obj.save()
        self.stdout.write('done.')
</code>```

In the above code, Saving routes ... is expected to print before the loop begins, and done. right next to it when the loop completes so that it looks like Saving routes ... done. in the end.

However, the former doesn't print until the loop completes, when both strings finally print at the same time, which is not what I expected.

I found this question, where the answer suggests flushing the output i.e. self.stdout.flush(), so I added that to my code:

```<code>    def handle(self, *args, **options):
        self.stdout.write('Saving routes ... ', ending='')
        self.stdout.flush()
        for route in get_all_routes():
            route_obj = Route(
                route_type=route['routeTp'], route_id=route['routeId'], route_number=route['routeNum'])
            route_obj.save()
        self.stdout.write('done.')
</code>```

Still, the result remains unchanged.

What could have I done wrong?

答:
The thing to keep in mind is you're using self.stdout (as suggested in the Django docs), which is BaseCommand's override of Python's standard sys.stdout. There are two main differences between the 2 relevant to your problem:

The default "ending" in BaseCommand's version of self.stdout.write() is a new-line, forcing you to use the ending='' parameter, unlike sys.stdout.write() that has an empty ending as the default. This in itself is not causing your problem.

The BaseCommand version of flush() does not really do anything (who would have thought?). This is a known bug: https://code.djangoproject.com/ticket/29533

So you really have 2 options:

Not use BaseCommand's self.stdout but instead use sys.stdout, in which case the flush does work

Force the stdout to be totally unbuffered while running the management command by passing the "-u" parameter to python. So instead of running python manage.py <subcommand>, run python -u manage.py <subcommand>

Hope this helps.

Body:
I'm trying to print to console before and after processing that takes a while in a Django management command, like this:

import requests
import xmltodict

from django.core.management.base import BaseCommand

def get_all_routes():
    url = 'http://busopen.jeju.go.kr/OpenAPI/service/bis/Bus'

    r = requests.get(url)
    data = xmltodict.parse(r.content)

    return data['response']['body']['items']['item']

class Command(BaseCommand):

    help = 'Updates the database via Bus Info API'

    def handle(self, *args, **options):
        self.stdout.write('Saving routes ... ', ending='')
        for route in get_all_routes():
            route_obj = Route(
                route_type=route['routeTp'], route_id=route['routeId'], route_number=route['routeNum'])
            route_obj.save()
        self.stdout.write('done.')

In the above code, Saving routes ... is expected to print before the loop begins, and done. right next to it when the loop completes so that it looks like Saving routes ... done. in the end.

However, the former doesn't print until the loop completes, when both strings finally print at the same time, which is not what I expected.

I found this question, where the answer suggests flushing the output i.e. self.stdout.flush(), so I added that to my code:

    def handle(self, *args, **options):
        self.stdout.write('Saving routes ... ', ending='')
        self.stdout.flush()
        for route in get_all_routes():
            route_obj = Route(
                route_type=route['routeTp'], route_id=route['routeId'], route_number=route['routeNum'])
            route_obj.save()
        self.stdout.write('done.')

Still, the result remains unchanged.

What could have I done wrong?


问:
How to dynamically add cardview to grid layout
I am trying to add cardview to GridLayout dynamically. But it is not adding the cardview.

The Hierarchy is ScrollView --> HorizontalScrollView --> LinearLayout --> GridLayout and I want to add to this grid layout. my code is:

```<code>public class MainActivity extends AppCompatActivity {
GridLayout gridLayout;
TextView tc;
CardView newc;
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gridLayout = findViewById(R.id.gridlayout);

   newc = new CardView(getApplicationContext());
   newc.setLayoutParams(new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
   newc.setRadius(8);
   newc.setCardElevation(10);
   tc = new TextView(getApplicationContext());
   tc.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
   tc.setText("This is dynamic");
   newc.addView(tc);
   GridLayout.Spec row = GridLayout.spec(0);
   GridLayout.Spec col = GridLayout.spec(0);
   GridLayout.LayoutParams gridP = new GridLayout.LayoutParams(row, col);
   gridLayout.addView(newc, gridP);

}
}
</code>```

So how to add the views dynamically to GridLayout.

Thank you.

答:
There are some bugs in your code ... use this

```<code>newc = new CardView(getApplicationContext());
newc.setLayoutParams(new CardView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
newc.setRadius(8);
 newc.setCardElevation(10);
tc = new TextView(getApplicationContext());
tc.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tc.setText("This is dynamic");
newc.addView(tc);
gridLayout.setColumnCount(2);
gridLayout.setOrientation(GridLayout.HORIZONTAL);
gridLayout.addView(newc);
</code>```

If you want to add view to spcific row and specific column use this

```<code> GridLayout.Spec row = GridLayout.spec(0); // Mention row index here
   GridLayout.Spec col = GridLayout.spec(0);// Mention column index here
   GridLayout.LayoutParams gridP = new GridLayout.LayoutParams(row, col);
</code>```

In your case, you are always using 0,0 for row and column so what basically happening is views are being added to grid layout but they are overlapping and hence you are unable to see those

Body:
I am trying to add cardview to GridLayout dynamically. But it is not adding the cardview.

The Hierarchy is ScrollView --> HorizontalScrollView --> LinearLayout --> GridLayout and I want to add to this grid layout. my code is:

public class MainActivity extends AppCompatActivity {
GridLayout gridLayout;
TextView tc;
CardView newc;
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gridLayout = findViewById(R.id.gridlayout);

   newc = new CardView(getApplicationContext());
   newc.setLayoutParams(new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
   newc.setRadius(8);
   newc.setCardElevation(10);
   tc = new TextView(getApplicationContext());
   tc.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
   tc.setText("This is dynamic");
   newc.addView(tc);
   GridLayout.Spec row = GridLayout.spec(0);
   GridLayout.Spec col = GridLayout.spec(0);
   GridLayout.LayoutParams gridP = new GridLayout.LayoutParams(row, col);
   gridLayout.addView(newc, gridP);

}
}

So how to add the views dynamically to GridLayout.

Thank you.

Body:
There are some bugs in your code ... use this

newc = new CardView(getApplicationContext());
newc.setLayoutParams(new CardView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
newc.setRadius(8);
 newc.setCardElevation(10);
tc = new TextView(getApplicationContext());
tc.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tc.setText("This is dynamic");
newc.addView(tc);
gridLayout.setColumnCount(2);
gridLayout.setOrientation(GridLayout.HORIZONTAL);
gridLayout.addView(newc);

If you want to add view to spcific row and specific column use this

 GridLayout.Spec row = GridLayout.spec(0); // Mention row index here
   GridLayout.Spec col = GridLayout.spec(0);// Mention column index here
   GridLayout.LayoutParams gridP = new GridLayout.LayoutParams(row, col);

In your case, you are always using 0,0 for row and column so what basically happening is views are being added to grid layout but they are overlapping and hence you are unable to see those


问:
How to reset a flutter Page (Widget) to initial state(state when the app was first Built)
Let's say I have a few sliders and switches on my page, I change their state and modify them, I understand that we do setState to show the changed state of the widget tree and rebuild it, but I would like to know if there's a way to undo all those changes and go back to the initial state (state the app was when it was first built)?
I don't want to call a custom function which manually resets the variables to initial values. Nor the routes should be removed and added back (because it would show the transition)

答:
There are a couple of age-old design patterns that might be useful in this situation. Having a reset option is cool, but what's cooler is undo.

See how the Command and Memento patterns can be implemented in Flutter with these tutorials: Command | Memento


问:
Apply styles all  except elements inside
 or
As I have difficulty reading some websites with a small and peculiar typeface, I'm writing snippets to override stylesheet of website itself. Like below

```<code>body, p, a, span {
  font-size: 18px;
  font-family: "readable sans-serif font" !important;
}
</code>```

but it applies to  inside ``` or  then the monospace font turns to the sans-serif font.
It often occurs with a source code with syntax highlight.

Are there any solutions?

答:
Use combined selectors to reset the font-family to the (inherited) font of the ```</code> or <code><code></code> parent element, like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body, p, a, span {
  font-size: 18px;
  font-family: sans-serif !important;
}
pre span,
code span {
  font-family: inherit !important;
}</code>```

This is a paragraph

This is a span
```This is a pre tag. <span>And this is a span within the "pre" tag</span>```
This is a code tag. And this is a span within the "code" tag```

Note: !important is only necessary here because it's already used in your rule for body, p, a, span, otherwise ìnherit` would be sufficient.

Title: Apply styles all <span> except elements inside <pre> or <code>

Body:
As I have difficulty reading some websites with a small and peculiar typeface, I'm writing snippets to override stylesheet of website itself. Like below

body, p, a, span {
  font-size: 18px;
  font-family: "readable sans-serif font" !important;
}

but it applies to  inside
 or  then the monospace font turns to the sans-serif font.
It often occurs with a source code with syntax highlight.

Are there any solutions?

Body:
Use combined selectors to reset the font-family to the (inherited) font of the <pre> or <code> parent element, like this:

body, p, a, span {
  font-size: 18px;
  font-family: sans-serif !important;
}
pre span,
code span {
  font-family: inherit !important;
}

<p>This is a paragraph</p>
<span>This is a span</span>
<pre>This is a pre tag. <span>And this is a span within the "pre" tag</span></pre>
<code>This is a code tag. <span>And this is a span within the "code" tag</span></code>

Note: !important is only necessary here because it's already used in your rule for body, p, a, span, otherwise ìnherit` would be sufficient.


问:
Is an empty block optimized away? C#
I am developing a game server in C# and a specific packet gets sent to my server 3 to 5 times per second per player. We will call that packet PacketA. I don't do anything with it except make sure that I receive it.

Since this packet gets sent the most, I want to place it first in the switch block so I don't have to make so many unnecessary comparisons. Will the compiler end up optimizing it away anyways (which will cause me to make all the comparisons down the switch block?)

```<code>switch (packetId)
{
    case PacketID.PacketA: // I do not want to do anything here.
        break;             // Just avoid all other packet id comparisons.

    case PacketID.PacketB:
        HandlePacketB(data);
        break;

    case PacketID.PacketC:
        HandlePacketC(data);
        break;

    // ...

    case PacketID.PacketZ:
       HandlePacketZ(data);
       break;
}
</code>```

If the compiler does optimize this away, how can I change my code so I don't have to check all the other packet ids?

答:
Disassemble your code and check if this case is available.
If it is not availablr then compiler optimized it.</p>

Title: Is an empty block optimized away? C#

Body:
I am developing a game server in C# and a specific packet gets sent to my server 3 to 5 times per second per player. We will call that packet PacketA. I don't do anything with it except make sure that I receive it.

Since this packet gets sent the most, I want to place it first in the switch block so I don't have to make so many unnecessary comparisons. Will the compiler end up optimizing it away anyways (which will cause me to make all the comparisons down the switch block?)

switch (packetId)
{
    case PacketID.PacketA: // I do not want to do anything here.
        break;             // Just avoid all other packet id comparisons.

    case PacketID.PacketB:
        HandlePacketB(data);
        break;

    case PacketID.PacketC:
        HandlePacketC(data);
        break;

    // ...

    case PacketID.PacketZ:
       HandlePacketZ(data);
       break;
}

If the compiler does optimize this away, how can I change my code so I don't have to check all the other packet ids?


问:
Basic Go RPC in Docker fails with SIGSEGV
I am trying to get a simple client/server RPC example running between two docker containers using Golang.

When I run them on my local machine, both build and run flawlessly.  I know that building them into docker containers would probably have some communication errors that I would need to work out, but I can't even get to that stage as I am getting a segmentation fault when trying to run my client.

When I run the master (server) container, it works, no problems.  But when I run the worker (client) I get this:

```<code>panic: runtime error: invalid memory address or nil pointer `   `dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x10
pc=0x72425d]

goroutine 1 [running]:
net/rpc.(*Client).send(0x0, 0xc0000d61e0)
        /usr/local/go/src/net/rpc/client.go:72 +0x3d
net/rpc.(*Client).Go(0x0, 0x7e062d, 0xa, 0x7887e0,
0xc0000b04a8, 0x788860, 0xb0c440, 0xc0000aa300,
0xc0000d6190)
        /usr/local/go/src/net/rpc/client.go:316 +0xcc
net/rpc.(*Client).Call(...)
        /usr/local/go/src/net/rpc/client.go:322
main.main()
        /app/worker.go:20 +0x11c
exit status 2
</code>```

My master.go:

```<code>package main

import (
    "fmt"
    "net"
    "net/http"
    "net/rpc"
)

type Args struct {
    Addthis int
}

type Reply struct {
    Ret int
}
type Api int

func (master *Api) Add(args Args, reply *Reply) error {
    out := args.Addthis + 10
    reply.Ret = out
    return nil
}

func main() {
    var master = new(Api)
    rpc.Register(master)
    rpc.HandleHTTP()
    listener, _ := net.Listen("tcp", ":4040")
    fmt.Printf("\nServing on %d\n", 4040)
    http.Serve(listener, nil)
}
</code>```

My Master Dockerfile:

```<code>FROM golang:latest

WORKDIR /app

COPY ./ /app

EXPOSE 4040

ENTRYPOINT go run master.go
</code>```

I build and run master with:

```<code>docker build -t master
docker run --net=testnet --name=master master
</code>```

This works fine.

My worker.go

```<code>package main

import (
    "fmt"
    "net/rpc"
)

type Args struct {
    Addthis int
}

type Reply struct {
    Ret int
}

func main() {
    var reply Reply
    client, _ := rpc.DialHTTP("tcp", ":4040")
    num := Args{215}
    client.Call("master.Add", num, &reply)
    fmt.Println("Here")
    fmt.Printf("\nGot back: %d\n", reply.Ret)
}
</code>```

My worker Dockerfile:

```<code>FROM golang:latest

WORKDIR /app

COPY ./ /app

EXPOSE 4040

ENTRYPOINT go run worker.go
</code>```

I build and run the worker with:

```<code>docker build -t worker .
docker run --net=testnet --name=worker worker
</code>```

THAT'S when I get the above error.

Googling for three hours and nothing helpful seems to come up.  I guess I don't know what search to use.

I know that this probably won't actually communicate as-is, but I would like to debug the communication issues, not deal with segmentation faults.  The code was supplied by my professor, not as part of an assignment, but just because I asked for it.  He claims this works without issue for him, and wasn't helpful with my troubleshooting (I don't think he actually tried deploying it in a container, but I'm not gonna call him out on it.  He's "touchy").  "Try stack exchange!" was all he said, really.

答:
```<code>client, _ := rpc.DialHTTP("tcp", ":4040")
</code>```

This basically means you are trying to connect to port 4040 on the same container however, your master is running in a different container. To connect to your master container you need to connect to {ip that docker has assigned automatically:4040} (for testing) or setup your docker network for proper usage of containers.

Body:
I am trying to get a simple client/server RPC example running between two docker containers using Golang.

When I run them on my local machine, both build and run flawlessly.  I know that building them into docker containers would probably have some communication errors that I would need to work out, but I can't even get to that stage as I am getting a segmentation fault when trying to run my client.

When I run the master (server) container, it works, no problems.  But when I run the worker (client) I get this:

panic: runtime error: invalid memory address or nil pointer `   `dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x10
pc=0x72425d]

goroutine 1 [running]:
net/rpc.(*Client).send(0x0, 0xc0000d61e0)
        /usr/local/go/src/net/rpc/client.go:72 +0x3d
net/rpc.(*Client).Go(0x0, 0x7e062d, 0xa, 0x7887e0,
0xc0000b04a8, 0x788860, 0xb0c440, 0xc0000aa300,
0xc0000d6190)
        /usr/local/go/src/net/rpc/client.go:316 +0xcc
net/rpc.(*Client).Call(...)
        /usr/local/go/src/net/rpc/client.go:322
main.main()
        /app/worker.go:20 +0x11c
exit status 2

My master.go:

package main

import (
    "fmt"
    "net"
    "net/http"
    "net/rpc"
)

type Args struct {
    Addthis int
}

type Reply struct {
    Ret int
}
type Api int

func (master *Api) Add(args Args, reply *Reply) error {
    out := args.Addthis + 10
    reply.Ret = out
    return nil
}

func main() {
    var master = new(Api)
    rpc.Register(master)
    rpc.HandleHTTP()
    listener, _ := net.Listen("tcp", ":4040")
    fmt.Printf("\nServing on %d\n", 4040)
    http.Serve(listener, nil)
}

My Master Dockerfile:

FROM golang:latest

WORKDIR /app

COPY ./ /app

EXPOSE 4040

ENTRYPOINT go run master.go

I build and run master with:

docker build -t master
docker run --net=testnet --name=master master

This works fine.

My worker.go

package main

import (
    "fmt"
    "net/rpc"
)

type Args struct {
    Addthis int
}

type Reply struct {
    Ret int
}

func main() {
    var reply Reply
    client, _ := rpc.DialHTTP("tcp", ":4040")
    num := Args{215}
    client.Call("master.Add", num, &reply)
    fmt.Println("Here")
    fmt.Printf("\nGot back: %d\n", reply.Ret)
}

My worker Dockerfile:

FROM golang:latest

WORKDIR /app

COPY ./ /app

EXPOSE 4040

ENTRYPOINT go run worker.go

I build and run the worker with:

docker build -t worker .
docker run --net=testnet --name=worker worker

THAT'S when I get the above error.

Googling for three hours and nothing helpful seems to come up.  I guess I don't know what search to use.

I know that this probably won't actually communicate as-is, but I would like to debug the communication issues, not deal with segmentation faults.  The code was supplied by my professor, not as part of an assignment, but just because I asked for it.  He claims this works without issue for him, and wasn't helpful with my troubleshooting (I don't think he actually tried deploying it in a container, but I'm not gonna call him out on it.  He's "touchy").  "Try stack exchange!" was all he said, really.

Body:
client, _ := rpc.DialHTTP("tcp", ":4040")

This basically means you are trying to connect to port 4040 on the same container however, your master is running in a different container. To connect to your master container you need to connect to {ip that docker has assigned automatically:4040} (for testing) or setup your docker network for proper usage of containers.


问:
Convert comma separated text to a list of numbers
In Power BI, I have created a DAX query created with a var giving comma-separated text using CONCATENATEX function.

Output like

```<code>Var = "1,2,3,4,5,6"
</code>```

Now I want to search this var into my table column with syntax

```<code>Table[col] in {var}.
</code>```

It is throwing an error.

I even tried converting the column to string with syntax

```<code>Convert(table[col], string)  in {var}
</code>```

The error is removed but the data doesn't match with column data.

答:
I found this Power BI community thread that is essentially the same question.

The solution is to convert the string into a path object.

Here's the code from the link:

```<code>Measure 3 =
VAR mymeasure =
    SUBSTITUTE ( [Measure], ",", "|" )
VAR Mylen =
    PATHLENGTH ( mymeasure )
VAR mytable =
    ADDCOLUMNS (
        GENERATESERIES ( 1, mylen ),
        "mylist", VALUE ( PATHITEM ( mymeasure, [Value] ) )
    )
VAR mylist =
    SELECTCOLUMNS ( mytable, "list", [mylist] )
RETURN
    CALCULATE ( COUNTROWS ( Table1 ), Table1[ID] IN mylist )
</code>```

There's a bit of redundancy in the above, so I'd probably condense it a bit and write it like this:

```<code>SomeMeasureFilteredByVar =
VAR PathVar = SUBSTITUTE ( [Var], ",", "|" )
VAR VarList =
    SELECTCOLUMNS (
        GENERATESERIES ( 1, PATHLENGTH ( PathVar ) ),
        "Item", VALUE ( PATHITEM ( PathVar, [Value] ) )
    )
RETURN
    CALCULATE ( [SomeMeasure], 'Table'[ID] IN VarList )

</code>```

Edit: To just create a calculated table, you can skip the last step:

```<code>TableFromString =
VAR PathVar = SUBSTITUTE ( "1,2,3,4,5,6", ",", "|" )
RETURN
    SELECTCOLUMNS (
        GENERATESERIES ( 1, PATHLENGTH ( PathVar ) ),
        "Item", VALUE ( PATHITEM ( PathVar, [Value] ) )
    )
</code>```

Note that it is not possible to create a calculated table that is dynamically responsive to report filters and slicers. Materialized calculated tables are only calculated once when the data loads, not every time you adjust a filter or slicer.

Therefore, you can use a measure in the table instead of the string "1,2,3,4,5,6" but the table output will be the same regardless of what the measure returns within different filter contexts.

Body:
In Power BI, I have created a DAX query created with a var giving comma-separated text using CONCATENATEX function.

Output like

Var = "1,2,3,4,5,6"

Now I want to search this var into my table column with syntax

Table[col] in {var}.

It is throwing an error.

I even tried converting the column to string with syntax

Convert(table[col], string)  in {var}

The error is removed but the data doesn't match with column data.

Body:
I found this Power BI community thread that is essentially the same question.

The solution is to convert the string into a path object.

Here's the code from the link:

Measure 3 =
VAR mymeasure =
    SUBSTITUTE ( [Measure], ",", "|" )
VAR Mylen =
    PATHLENGTH ( mymeasure )
VAR mytable =
    ADDCOLUMNS (
        GENERATESERIES ( 1, mylen ),
        "mylist", VALUE ( PATHITEM ( mymeasure, [Value] ) )
    )
VAR mylist =
    SELECTCOLUMNS ( mytable, "list", [mylist] )
RETURN
    CALCULATE ( COUNTROWS ( Table1 ), Table1[ID] IN mylist )

There's a bit of redundancy in the above, so I'd probably condense it a bit and write it like this:

SomeMeasureFilteredByVar =
VAR PathVar = SUBSTITUTE ( [Var], ",", "|" )
VAR VarList =
    SELECTCOLUMNS (
        GENERATESERIES ( 1, PATHLENGTH ( PathVar ) ),
        "Item", VALUE ( PATHITEM ( PathVar, [Value] ) )
    )
RETURN
    CALCULATE ( [SomeMeasure], 'Table'[ID] IN VarList )

Edit: To just create a calculated table, you can skip the last step:

TableFromString =
VAR PathVar = SUBSTITUTE ( "1,2,3,4,5,6", ",", "|" )
RETURN
    SELECTCOLUMNS (
        GENERATESERIES ( 1, PATHLENGTH ( PathVar ) ),
        "Item", VALUE ( PATHITEM ( PathVar, [Value] ) )
    )

Note that it is not possible to create a calculated table that is dynamically responsive to report filters and slicers. Materialized calculated tables are only calculated once when the data loads, not every time you adjust a filter or slicer.

Therefore, you can use a measure in the table instead of the string "1,2,3,4,5,6" but the table output will be the same regardless of what the measure returns within different filter contexts.


问:
Convert CameraX Captured ImageProxy to Bitmap
I was working with CameraX and had hard time converting captured ImageProxy to Bitmap. After searching and trying, I formulated a solution. Later I found that it was not optimum so I changed the design. That forced me to drop hours of work.

Since I (or someone else) might need it in a future, I decided to post here as a question and post and answer to it for reference and scrutiny. Feel free to add better answer if you have one.

The relevant code is:

```<code>class ImagePickerActivity : AppCompatActivity() {
    private var width = 325
    private var height = 205

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_picker)

        view_finder.post { startCamera() }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private fun startCamera() {
        // Create configuration object for the viewfinder use case
        val previewConfig = PreviewConfig.Builder().apply {
            setTargetAspectRatio(Rational(1, 1))
            //setTargetResolution(Size(width, height))
            setLensFacing(CameraX.LensFacing.BACK)
            setTargetAspectRatio(Rational(width, height))
        }.build()

        }

        // Create configuration object for the image capture use case
        val imageCaptureConfig = ImageCaptureConfig.Builder()
            .apply {
                setTargetAspectRatio(Rational(1, 1))
                // We don't set a resolution for image capture instead, we
                // select a capture mode which will infer the appropriate
                // resolution based on aspect ration and requested mode
                setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
            }.build()

        // Build the image capture use case and attach button click listener
        val imageCapture = ImageCapture(imageCaptureConfig)
        capture_button.setOnClickListener {

            imageCapture.takePicture(object : ImageCapture.OnImageCapturedListener() {
                override fun onCaptureSuccess(image: ImageProxy?, rotationDegrees: Int) {
                        //How do I get the bitmap here?
                        //imageView.setImageBitmap(someBitmap)
                }

                override fun onError(useCaseError: ImageCapture.UseCaseError?, message: String?, cause: Throwable?) {
                    val msg = "Photo capture failed: $message"
                    Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                    Log.e(localClassName, msg)
                    cause?.printStackTrace()
                }
            })
        }
        CameraX.bindToLifecycle(this, preview, imageCapture)
    }

}
</code>```

答:
There is second version of takePicture method at the moment (CameraX version 1.0.0-beta03). It provides several ways to persist image (OutputStream or maybe File can be useful in your case).

If you still want to convert ImageProxy to Bitmap here is my answer to similar question, which gives the correct implemetation of this conversion.

Body:
I was working with CameraX and had hard time converting captured ImageProxy to Bitmap. After searching and trying, I formulated a solution. Later I found that it was not optimum so I changed the design. That forced me to drop hours of work.

Since I (or someone else) might need it in a future, I decided to post here as a question and post and answer to it for reference and scrutiny. Feel free to add better answer if you have one.

The relevant code is:

class ImagePickerActivity : AppCompatActivity() {
    private var width = 325
    private var height = 205

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_picker)

        view_finder.post { startCamera() }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private fun startCamera() {
        // Create configuration object for the viewfinder use case
        val previewConfig = PreviewConfig.Builder().apply {
            setTargetAspectRatio(Rational(1, 1))
            //setTargetResolution(Size(width, height))
            setLensFacing(CameraX.LensFacing.BACK)
            setTargetAspectRatio(Rational(width, height))
        }.build()

        }

        // Create configuration object for the image capture use case
        val imageCaptureConfig = ImageCaptureConfig.Builder()
            .apply {
                setTargetAspectRatio(Rational(1, 1))
                // We don't set a resolution for image capture instead, we
                // select a capture mode which will infer the appropriate
                // resolution based on aspect ration and requested mode
                setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
            }.build()

        // Build the image capture use case and attach button click listener
        val imageCapture = ImageCapture(imageCaptureConfig)
        capture_button.setOnClickListener {

            imageCapture.takePicture(object : ImageCapture.OnImageCapturedListener() {
                override fun onCaptureSuccess(image: ImageProxy?, rotationDegrees: Int) {
                        //How do I get the bitmap here?
                        //imageView.setImageBitmap(someBitmap)
                }

                override fun onError(useCaseError: ImageCapture.UseCaseError?, message: String?, cause: Throwable?) {
                    val msg = "Photo capture failed: $message"
                    Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                    Log.e(localClassName, msg)
                    cause?.printStackTrace()
                }
            })
        }
        CameraX.bindToLifecycle(this, preview, imageCapture)
    }

}