问:
How to redirect in JavaScript to another website after establishing an authenticated session using PHP (Codeigniter)

SOLVED

The title wasn't enough for the question, I'll elaborate here.

The Problem

I have two systems lets call them system A and system B. System A is a Petite-vue/Codeigniter stack. System B could be a Codeigniter or Laravel back-end (front-end could vary).
Here is a graph showing the setup (R1 and R2 will be explained below).

NOTE: In the graph below R2 is sent from the back-end to system B.

In system A, I am making an asynchronous Fetch request, lets call this request R1, from the JavaScript (petite-vue) code to the PHP (Codeigniter), which is in the same system (it being system A). (Code below)

      function Connect_To_System(url){
        fetch("<?= base_url("connect") ?>",
                {
                  method: "POST",
                  body: JSON.stringify( {URL: url} )
                })
                .then(res => res.json())
                .then(data => {
                  // do something with response data like showing a message
                })
      }
```
<p><strong><code>R1</code></strong> is handled in the PHP (Codeigniter) code, which establishes an authenticated session with <strong><code>system B</code></strong> by sending a cURL request, lets call this request <strong><code>R2</code></strong>, to <strong><code>system B</code></strong>. After <strong><code>R2</code></strong> response returns an HTTP 200 status, I want to redirect the user from <strong><code>system A</code></strong> to <strong><code>system B</code></strong> in a new tab. (Code below, note that I'm using REST_Controller)</p>
<pre class="lang-php prettyprint-override"><code>    public function connect_post(){
        $data = json_decode($this->post()[0]);
        $url = $data->URL;
        $url_login = $url.'/auth/login';
        $token = $this->session->tempdata('token');
        $username = $this->current_user['emp_no'];
        $digest = md5($username.$token);

        $params= array(
            "username" => $username,
            "token" => $token
        );
        $result = $this->postCURL($url_login, $params);
        // Redirect in a new tab when status is 200 somehow
        // Return a response to the JavaScript
    }
</code>```

The problem is that I can't redirect the user to another page from the PHP (Codeigniter), because it was called by R1. Thus, I must redirect the user from the View that made R1 using JavaScript.

However, the solution to first problem doesn't work because the session that was established by R2 is tied to PHP (Codeigniter), or cURL I can't really tell, in other words it's the server that established the session not the user. And redirecting the user using JavaScript will tie the redirection to the user, or whatever the redirect method is.

Possible Solution (Not Preferred EDIT: It is preferred)

The only functional solution is to establish the session with system B from the JavaScript and then redirect the user, which is what I'm currently doing. But the problem is that I'm exposing the authentication data to whom ever simply decides to open the browser inspect. That's why I'm trying to keep all the important data in the back-end PHP code.

The Main Goal

All I want is a way to keep the authentication data hidden, whatever the method may be, if that's possible really.

Thank you in advance.

答: As it turns out, the proposed solution in the question actually is preferred. Since the token of the user is so personalized and it is even stored in the server session and stored in the database, it would so difficult to authenticate you're self using someone else's authentication data. Thus, there is no major security vulnerability. The idea of exposed data scared me that it blinded me from seeing that exposing the token isn't a huge security vulnerability.</p>

Body:
SOLVED

The title wasn't enough for the question, I'll elaborate here.

The Problem

I have two systems lets call them system A and system B. System A is a Petite-vue/Codeigniter stack. System B could be a Codeigniter or Laravel back-end (front-end could vary).
Here is a graph showing the setup (R1 and R2 will be explained below).

NOTE: In the graph below R2 is sent from the back-end to system B.

In system A, I am making an asynchronous Fetch request, lets call this request R1, from the JavaScript (petite-vue) code to the PHP (Codeigniter), which is in the same system (it being system A). (Code below)

      function Connect_To_System(url){
        fetch("<?= base_url("connect") ?>",
                {
                  method: "POST",
                  body: JSON.stringify( {URL: url} )
                })
                .then(res => res.json())
                .then(data => {
                  // do something with response data like showing a message
                })
      }

R1 is handled in the PHP (Codeigniter) code, which establishes an authenticated session with system B by sending a cURL request, lets call this request R2, to system B. After R2 response returns an HTTP 200 status, I want to redirect the user from system A to system B in a new tab. (Code below, note that I'm using REST_Controller)

    public function connect_post(){
        $data = json_decode($this->post()[0]);
        $url = $data->URL;
        $url_login = $url.'/auth/login';
        $token = $this->session->tempdata('token');
        $username = $this->current_user['emp_no'];
        $digest = md5($username.$token);

        $params= array(
            "username" => $username,
            "token" => $token
        );
        $result = $this->postCURL($url_login, $params);
        // Redirect in a new tab when status is 200 somehow
        // Return a response to the JavaScript
    }

The problem is that I can't redirect the user to another page from the PHP (Codeigniter), because it was called by R1. Thus, I must redirect the user from the View that made R1 using JavaScript.

However, the solution to first problem doesn't work because the session that was established by R2 is tied to PHP (Codeigniter), or cURL I can't really tell, in other words it's the server that established the session not the user. And redirecting the user using JavaScript will tie the redirection to the user, or whatever the redirect method is.

Possible Solution (Not Preferred EDIT: It is preferred)

The only functional solution is to establish the session with system B from the JavaScript and then redirect the user, which is what I'm currently doing. But the problem is that I'm exposing the authentication data to whom ever simply decides to open the browser inspect. That's why I'm trying to keep all the important data in the back-end PHP code.

The Main Goal

All I want is a way to keep the authentication data hidden, whatever the method may be, if that's possible really.

Thank you in advance.


来源: stackexchange

问:
LevelDB asserts when deleting the LevelDB instance
I get some super annoying asserts when I try to delete the leveldb instance and I'm not sure why it's happening!

The assert is happening in the version_set.cc file:

```<code>void VersionSet::AppendVersion(Version* v) {
  // Make "v" current
  assert(v->refs_ == 0); // <---??? how do I avoid this assertion?
  // the rest of the source code is available in the link to version_set.cc
}
</code>```

Additionally, it asserts in another place in the same file:

```<code>Version::~Version() {
  assert(refs_ == 0); // <-- Again... how do I avoid this one too?
  // the rest of the source code is available in the link to version_set.cc
}
</code>```

Here is more background details on the usage in my system, I have a:

class ExtStorage (Extended Storage) which has a LevelDB::DB instance.

class EextStorageDotNet, which is the C++/CLI wrapper around the ExtStorage.

class AltStorage, which holds a pointer to an ExtStorage class (passed through the constructor):

class AltStorageDotNet, which is the C++/CLI wrapper around the AltStorage.

The alternate storage class looks like this:

```<code>class AltStorage{
    ExtStorage* instance;
public:
    AltStorage(ExtStorage* extStorage):instance(extStorage){}

    ~AltStorage(){
        delete instance;
        instance = NULL;
    }
};
</code>```

The ExtStorage class looks like this:

```<code>class ExtStorage{
    leveldb::DB* mydb;
public:
    ExtStorage(/*some parameters*/){
         mydb = new leveldb::DB(/*parameters*/);
    }

    // Destructor
    ~ExtStorage() {
        Close();
    }

    // deletes the leveldb::DB instance
    void Close() {
        if(mydb == NULL) {
            delete mydb; // <-- Asserts every time I get here when using with the AltStorageDotNet
            mydb= NULL;

            // Close the L1 and L2 caches
            // only once (
        }
    }
}
</code>```

The AltStorageDotNet class looks like this:

```<code>public ref class AltStorageDotNet{
    AltStorage* altInstance;
    ExtStorageDotNet^ extInstance;
public:
    AltStorageDotNet() {
        ExtStorage extStorage = new ExtStorage(/*params*/);
        altInstance = new AltStorage(extStorage);
        extInstance = gcnew ExtStorageDotNet(extStorage);
    }

    ~AltStorageDotNet(){
        delete altInstance;
        altInstance = NULL;
        // no need to delete extInstance since it was created with gcnew
    }

    !AltStorageDotNet(){
        delete altInstance;
        altInstance = NULL;
        // no need to delete extInstance since it was created with gcnew
    }

    inline ExtStorageDotNet^ GetExtInstance(){return extInstance;}
};
</code>```

The DotNet wrappers look like this:

```<code>public ref class ExtStorageDotNet{
private:
    ExtStorage* instance;
public:
    ExtStorageDotNet(ExtStorage* extStorage){
        instance = extStorage;
    }

    ~ExtStorageDotNet(){
        delete instance;
        instance = NULL;
    }

    !ExtStorageDotNet(){
        delete instance;
        instance = NULL;
    }

    void Close(){instance->Close();}
};
</code>```

Whenever I use the ExtStorageDotNet wrapper in my C# application everything works good and there are no asserts. However, when I use the AltStorageDotNet wrapper and I access the ExtStorageDotNet wrapper, then I get the asserts when closing the database. This is all part of a test suite in which I initialize an instance for each test case and close it after each test case; the associated database files get deleted before a new test case begins. I don't see any reason why it should happen and the assertion is not helpful in tracking down the problem.

答:
I don't know whether it's related to your asserts or not, but this code is guaranteed to cause memory corruption. Both ExtStorageDotNet and AltStorageDotNet are disposable and finalizable, and both (directly or indirectly) delete the instance of ExtStorage -- invariably, one will delete it after the other already has.

Also, as I said in my comment, the comment in your code saying no need to delete extInstance since it was created with gcnew is way off -- see this answer for details. (I assume you know C# and thus about IDisposable; if you don't, then you really need to do some reading.)

ContentLicense: CC BY-SA 3.0

Body:
I get some super annoying asserts when I try to delete the leveldb instance and I'm not sure why it's happening!

The assert is happening in the version_set.cc file:

void VersionSet::AppendVersion(Version* v) {
  // Make "v" current
  assert(v->refs_ == 0); // <---??? how do I avoid this assertion?
  // the rest of the source code is available in the link to version_set.cc
}

Additionally, it asserts in another place in the same file:

Version::~Version() {
  assert(refs_ == 0); // <-- Again... how do I avoid this one too?
  // the rest of the source code is available in the link to version_set.cc
}

Here is more background details on the usage in my system, I have a:

class ExtStorage (Extended Storage) which has a LevelDB::DB instance.

class EextStorageDotNet, which is the C++/CLI wrapper around the ExtStorage.

class AltStorage, which holds a pointer to an ExtStorage class (passed through the constructor):

class AltStorageDotNet, which is the C++/CLI wrapper around the AltStorage.

The alternate storage class looks like this:

class AltStorage{
    ExtStorage* instance;
public:
    AltStorage(ExtStorage* extStorage):instance(extStorage){}

    ~AltStorage(){
        delete instance;
        instance = NULL;
    }
};

The ExtStorage class looks like this:

class ExtStorage{
    leveldb::DB* mydb;
public:
    ExtStorage(/*some parameters*/){
         mydb = new leveldb::DB(/*parameters*/);
    }

    // Destructor
    ~ExtStorage() {
        Close();
    }

    // deletes the leveldb::DB instance
    void Close() {
        if(mydb == NULL) {
            delete mydb; // <-- Asserts every time I get here when using with the AltStorageDotNet
            mydb= NULL;

            // Close the L1 and L2 caches
            // only once (
        }
    }
}

The AltStorageDotNet class looks like this:

public ref class AltStorageDotNet{
    AltStorage* altInstance;
    ExtStorageDotNet^ extInstance;
public:
    AltStorageDotNet() {
        ExtStorage extStorage = new ExtStorage(/*params*/);
        altInstance = new AltStorage(extStorage);
        extInstance = gcnew ExtStorageDotNet(extStorage);
    }

    ~AltStorageDotNet(){
        delete altInstance;
        altInstance = NULL;
        // no need to delete extInstance since it was created with gcnew
    }

    !AltStorageDotNet(){
        delete altInstance;
        altInstance = NULL;
        // no need to delete extInstance since it was created with gcnew
    }

    inline ExtStorageDotNet^ GetExtInstance(){return extInstance;}
};

The DotNet wrappers look like this:

public ref class ExtStorageDotNet{
private:
    ExtStorage* instance;
public:
    ExtStorageDotNet(ExtStorage* extStorage){
        instance = extStorage;
    }

    ~ExtStorageDotNet(){
        delete instance;
        instance = NULL;
    }

    !ExtStorageDotNet(){
        delete instance;
        instance = NULL;
    }

    void Close(){instance->Close();}
};

Whenever I use the ExtStorageDotNet wrapper in my C# application everything works good and there are no asserts. However, when I use the AltStorageDotNet wrapper and I access the ExtStorageDotNet wrapper, then I get the asserts when closing the database. This is all part of a test suite in which I initialize an instance for each test case and close it after each test case; the associated database files get deleted before a new test case begins. I don't see any reason why it should happen and the assertion is not helpful in tracking down the problem.


问:
Outlook addin: how to get current search text box value
I have an Outlook COM addin and would like to be able to read the current search box text value that the user has enter. How do I do that?</p>

答:
The Outlook object model doesn't provide anything for retrieving the search criteria. The best what you could do is to get the filter string for the current view of the folder or explorer window. The Explorer.CurrentView property returns or sets a View object representing the current view. And the Folder.CurrentView property returns a View object representing the current view. For example:

```<code>Private Sub FilterViewToLastWeek()
 Dim objView As View
 ' Obtain a View object reference to the current view.
 Set objView = Application.ActiveExplorer.CurrentView
 ' Set a DASL filter string, using a DASL macro, to show
 ' only those items that were received last week.
 objView.Filter = "%lastweek(""urn:schemas:httpmail:datereceived"")%"
 ' Save and apply the view.
 objView.Save
 objView.Apply
End Sub
</code>```

The View object allows you to create customizable views that allow you to better sort, group and ultimately view data of all different types. There are a variety of different view types that provide the flexibility needed to create and maintain your important data.

The table view type (olTableView) allows you to view data in a simple field-based table.

The Calendar view type (olCalendarView) allows you to view data in a calendar format.

The card view type (olCardView) allows you to view data in a series of cards. Each card displays the information contained by the item and can be sorted.

The icon view type (olIconView) allows you to view data as icons, similar to a Windows folder or explorer.

The timeline view type (olTimelineView) allows you to view data as it is received in a customizable linear time line.

Views are defined and customized using the View object's XML property. The XML property allows you to create and set a customized XML schema that defines the various features of a view.

The View.Filter property returns or sets a string value that represents the filter for a view.

The value of this property is a string, in DAV Searching and Locating (DASL) syntax, that represents the current filter for the view. For more information about using DASL syntax to filter items in a view, see Filtering Items.

Also you may find a similar post helpful.

ContentLicense: CC BY-SA 4.0

Body:
The Outlook object model doesn't provide anything for retrieving the search criteria. The best what you could do is to get the filter string for the current view of the folder or explorer window. The Explorer.CurrentView property returns or sets a View object representing the current view. And the Folder.CurrentView property returns a View object representing the current view. For example:

Private Sub FilterViewToLastWeek()
 Dim objView As View
 ' Obtain a View object reference to the current view.
 Set objView = Application.ActiveExplorer.CurrentView
 ' Set a DASL filter string, using a DASL macro, to show
 ' only those items that were received last week.
 objView.Filter = "%lastweek(""urn:schemas:httpmail:datereceived"")%"
 ' Save and apply the view.
 objView.Save
 objView.Apply
End Sub

The View object allows you to create customizable views that allow you to better sort, group and ultimately view data of all different types. There are a variety of different view types that provide the flexibility needed to create and maintain your important data.

The table view type (olTableView) allows you to view data in a simple field-based table.

The Calendar view type (olCalendarView) allows you to view data in a calendar format.

The card view type (olCardView) allows you to view data in a series of cards. Each card displays the information contained by the item and can be sorted.

The icon view type (olIconView) allows you to view data as icons, similar to a Windows folder or explorer.

The timeline view type (olTimelineView) allows you to view data as it is received in a customizable linear time line.

Views are defined and customized using the View object's XML property. The XML property allows you to create and set a customized XML schema that defines the various features of a view.

The View.Filter property returns or sets a string value that represents the filter for a view.

The value of this property is a string, in DAV Searching and Locating (DASL) syntax, that represents the current filter for the view. For more information about using DASL syntax to filter items in a view, see Filtering Items.

Also you may find a similar post helpful.


问:
Quarter function in Snowflake
I have written the "select" query for the quarter function in SAP HANA.

```<code>select QUARTER (CURRENT_DATE, 8) FROM DUMMY;

output: 2021-Q3
</code>```

Can someone please help me with the equivalent query in Snowflake?

答:
Try any of these:

SELECT DATE_TRUNC('QUARTER', CURRENT_TIMESTAMP())
     , QUARTER(CURRENT_TIMESTAMP())
     , YEAR(CURRENT_TIMESTAMP()) || '-Q' || QUARTER(CURRENT_TIMESTAMP());
```

Title: Quarter function in Snowflake

Body:
I have written the "select" query for the quarter function in SAP HANA.

select QUARTER (CURRENT_DATE, 8) FROM DUMMY;

output: 2021-Q3

Can someone please help me with the equivalent query in Snowflake?


问:
Finding contradictory semantic sentences through natural language processing
I'm working on a project that aims to find conflicting Semantic Sentences (NLP - Semantic Search )
For example

Our text is: "I ate today. The lunch was very tasty. I was an honest guest."

Query: "I had lunch with my friend"

Do we want to give the query model and find the meaning of the sentences with a certain point in terms of synonyms and antonyms?

The solution that came to my mind was to first find the synonymous sentences and extract the key words from the synonymous sentences and then get the semantic opposite words and then find the semantic synonymous sentences based on these opposite words.
Do you think this idea is possible? If you have a solution or experience in this area, please reply

Thanks

答:
You have not mentioned the exact use case for your problem so I am not sure if the solution I know will help your cause. But there is an approach in NLP (using Deep learning) which helps to find whether two sentences are correlated, unrelated or contradictory.

Below is the information about the pretrained model which is trained specifically for this task ->
https://huggingface.co/facebook/bart-large-mnli

The dataset on which the above model is trained is given here ->
https://huggingface.co/datasets/glue/viewer/mnli/train

You can check the dataset to verify if your use case is related to the classification task performed on the dataset.
Since the model is already pretrained, you do not need to perform any training and can jump straight to evaluation. Once you can somewhat satisfied with the results, you can fine tune the model a bit for your specific problem.

We can talk in comments if you need more clarification.


问:
Why is memset() incorrectly initializing int?
Why is the output of the following program 84215045?

```<code>int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}
</code>```

答:
You haven't actually said what you want your program to do.

Assuming that you want to set each of the first 100 elements of grid to 5 (and ignoring the 100 vs. 110 discrepancy), just do this:

```<code>for (int i = 0; i < 100; i ++) {
    grid[i] = 5;
}
</code>```

I understand that you're concerned about speed, but your concern is probably misplaced.  On the one hand, memset() is likely to be optimized and therefore faster than a simple loop.  On the other hand, the optimization is likely to consist of writing more than one byte at a time, which is what this loop does.  On the other other hand, memset() is a loop anyway; writing the loop explicitly rather than burying it in a function call doesn't change that.  On the other other other hand, even if the loop is slow, it's not likely to matter; concentrate on writing clear code, and think about optimizing it if actual measurements indicate that there's a significant performance issue.

You've spent many orders of magnitude more time writing the question than your computer will spend setting grid.

Finally, before I run out of hands (too late!), it doesn't matter how fast memset() is if it doesn't do what you want.  (Not setting grid at all is even faster!)

Body:
Why is the output of the following program 84215045?

int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}

Body:
You haven't actually said what you want your program to do.

Assuming that you want to set each of the first 100 elements of grid to 5 (and ignoring the 100 vs. 110 discrepancy), just do this:

for (int i = 0; i < 100; i ++) {
    grid[i] = 5;
}

I understand that you're concerned about speed, but your concern is probably misplaced.  On the one hand, memset() is likely to be optimized and therefore faster than a simple loop.  On the other hand, the optimization is likely to consist of writing more than one byte at a time, which is what this loop does.  On the other other hand, memset() is a loop anyway; writing the loop explicitly rather than burying it in a function call doesn't change that.  On the other other other hand, even if the loop is slow, it's not likely to matter; concentrate on writing clear code, and think about optimizing it if actual measurements indicate that there's a significant performance issue.

You've spent many orders of magnitude more time writing the question than your computer will spend setting grid.

Finally, before I run out of hands (too late!), it doesn't matter how fast memset() is if it doesn't do what you want.  (Not setting grid at all is even faster!)


问:
AppSpreadsheet (GAS): avoid some problems with sistematic tested data
In my current job with spreadsheet, all inserted data passes through a test, checking if the same value is found on the same index in other sheets. Failing, a caution message is put in the current cell.

```<code>//mimimalist algorithm
function safeInsertion(data, row_, col_)
{
  let rrow = row_ - 1; //range row
  let rcol = col_ - 1; // range col
  const active_sheet_name = getActiveSheetName(); // do as the its name suggest
  const all_sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

  //test to evaluate the value to be inserted in the sheet
  for (let sh of all_sheets)
  {
    if (sh.getName() === active_sheet_name)
      continue;
    //getSheetValues do as its name suggest.
    if( getSheetValues(sh)[rrow][rcol] === data )
      return "prohibited insertion"
  }
  return data;
}
// usage (in cell): =safeInsertion("A scarce data", ROW(), COLUMN())
</code>```

The problems are:

cached values confuse me sometimes. The script or data is changed but not perceived by the sheet itself until renewing manually the cell's content or refreshing all table. Is there any relevant configuration available to this issue?

Sometimes, at loading, a messing result appears. Almost all data are prohibited, for example (originally, all was fine!).

What can I do to obtain a stable sheet using this approach?

PS: The original function does more testing on each data insertion. Those tests consist on counting the frequency in the actual sheet and in all sheets.

EDIT:

In fact, I can't create a stable sheet. For test, a let you a copy of my code with minimal adaptations.

```<code>function safelyPut(data, max_onesheet, max_allsheet, row, col)
{
  // general initialization
  const data_regex = "\^\s*"+data+"\s*$"
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const activesheet = spreadsheet.getActiveSheet();
  const active_text_finder = activesheet.createTextFinder(data_regex)
                                        .useRegularExpression(true)
                                        .matchEntireCell(true);
  const all_text_finder = spreadsheet.createTextFinder(data_regex)
                                     .useRegularExpression(true)
                                     .matchEntireCell(true);
  const all_occurrences = all_text_finder.findAll();

  //test general data's environment
  const active_freq = active_text_finder.findAll().length;
  if (max_onesheet <= active_freq)
    return "Too much in a sheet";
  const all_freq = all_occurrences.length;
  if (max_allsheet <= all_freq)
    return "Too much in the work";

  //test unicity in a position
  const active_sname = activesheet.getName();
  for (occurrence of all_occurrences)
  {
    const sname =  occurrence.getSheet().getName();

    //if (SYSTEM_SHEETS.includes(sname))
      //continue;

    if (sname != active_sname)
    if (occurrence.getRow() == row && occurrence.getColumn() == col)
    if (occurrence.getValue() == data)
    {
      return `${sname} contains same data with the same indexes.`;
    };
  }

  return data;
}
</code>```

Create two or three cells and put randomly in a short range short range a value following the usage

=safeInsertion("Scarce Data", 3; 5; ROW(), COLUMN())

Do it, probably you will get a unstable sheet.

答:
About cached values confuse me sometimes. The script is changed but not perceived by the sheet until renewing manually the cell's content or refreshing all table. No relevant configuration available to this issue?, when you want to refresh your custom function of safeInsertion, I thought that this thread might be useful.

About Sometimes, at loading, a messing result appears. Almost all data are prohibited, for example (originally, all was fine!). and What can I do to obtain a stable sheet using this approach?, in this case, for example, how about reducing the process cost of your script? I thought that by reducing the process cost of the script, your situation might be a bit stable.

When your script is modified by reducing the process cost, how about the following modification?

Modified script:

function safeInsertion(data, row_, col_) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const range = ss.createTextFinder(data).matchEntireCell(true).findNext();
  return range && range.getRow() == row_ && range.getColumn() == col_ && range.getSheet().getSheetName() != ss.getActiveSheet().getSheetName() ? "prohibited insertion" : data;
}
```

The usage of this is the same with your current script like =safeInsertion("A scarce data", ROW(), COLUMN()).

In this modification, TextFinder is used. Because I thought that when the value is searched from all sheets in a Google Spreadsheet, TextFinder is suitable for reducing the process cost.

References:

createTextFinder(findText) of Class Spreadsheet

findNext()

Body:
In my current job with spreadsheet, all inserted data passes through a test, checking if the same value is found on the same index in other sheets. Failing, a caution message is put in the current cell.

//mimimalist algorithm
function safeInsertion(data, row_, col_)
{
  let rrow = row_ - 1; //range row
  let rcol = col_ - 1; // range col
  const active_sheet_name = getActiveSheetName(); // do as the its name suggest
  const all_sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

  //test to evaluate the value to be inserted in the sheet
  for (let sh of all_sheets)
  {
    if (sh.getName() === active_sheet_name)
      continue;
    //getSheetValues do as its name suggest.
    if( getSheetValues(sh)[rrow][rcol] === data )
      return "prohibited insertion"
  }
  return data;
}
// usage (in cell): =safeInsertion("A scarce data", ROW(), COLUMN())

The problems are:

cached values confuse me sometimes. The script or data is changed but not perceived by the sheet itself until renewing manually the cell's content or refreshing all table. Is there any relevant configuration available to this issue?

Sometimes, at loading, a messing result appears. Almost all data are prohibited, for example (originally, all was fine!).

What can I do to obtain a stable sheet using this approach?

PS: The original function does more testing on each data insertion. Those tests consist on counting the frequency in the actual sheet and in all sheets.

EDIT:

In fact, I can't create a stable sheet. For test, a let you a copy of my code with minimal adaptations.

function safelyPut(data, max_onesheet, max_allsheet, row, col)
{
  // general initialization
  const data_regex = "\^\s*"+data+"\s*$"
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const activesheet = spreadsheet.getActiveSheet();
  const active_text_finder = activesheet.createTextFinder(data_regex)
                                        .useRegularExpression(true)
                                        .matchEntireCell(true);
  const all_text_finder = spreadsheet.createTextFinder(data_regex)
                                     .useRegularExpression(true)
                                     .matchEntireCell(true);
  const all_occurrences = all_text_finder.findAll();

  //test general data's environment
  const active_freq = active_text_finder.findAll().length;
  if (max_onesheet <= active_freq)
    return "Too much in a sheet";
  const all_freq = all_occurrences.length;
  if (max_allsheet <= all_freq)
    return "Too much in the work";

  //test unicity in a position
  const active_sname = activesheet.getName();
  for (occurrence of all_occurrences)
  {
    const sname =  occurrence.getSheet().getName();

    //if (SYSTEM_SHEETS.includes(sname))
      //continue;

    if (sname != active_sname)
    if (occurrence.getRow() == row && occurrence.getColumn() == col)
    if (occurrence.getValue() == data)
    {
      return `${sname} contains same data with the same indexes.`;
    };
  }

  return data;
}

Create two or three cells and put randomly in a short range short range a value following the usage

=safeInsertion("Scarce Data", 3; 5; ROW(), COLUMN())

Do it, probably you will get a unstable sheet.

Body:
About cached values confuse me sometimes. The script is changed but not perceived by the sheet until renewing manually the cell's content or refreshing all table. No relevant configuration available to this issue?, when you want to refresh your custom function of safeInsertion, I thought that this thread might be useful.

About Sometimes, at loading, a messing result appears. Almost all data are prohibited, for example (originally, all was fine!). and What can I do to obtain a stable sheet using this approach?, in this case, for example, how about reducing the process cost of your script? I thought that by reducing the process cost of the script, your situation might be a bit stable.

When your script is modified by reducing the process cost, how about the following modification?

Modified script:

function safeInsertion(data, row_, col_) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const range = ss.createTextFinder(data).matchEntireCell(true).findNext();
  return range && range.getRow() == row_ && range.getColumn() == col_ && range.getSheet().getSheetName() != ss.getActiveSheet().getSheetName() ? "prohibited insertion" : data;
}

The usage of this is the same with your current script like =safeInsertion("A scarce data", ROW(), COLUMN()).

In this modification, TextFinder is used. Because I thought that when the value is searched from all sheets in a Google Spreadsheet, TextFinder is suitable for reducing the process cost.

References:

createTextFinder(findText) of Class Spreadsheet

findNext()


问:
Query or filter pandas dataframe on multiple columns and cell values
I've tried to figure this one out, but all methods end up with errors.

Quick background info: I have a dataframe with US states and info when a state has adopted a new law. In addition, the dataframe tells which are the neighbouring states. Here's a quick mockup:

(df: treated_states)

```<code>| year     | state |BC_law |n_ipo |Neighbor1 |Neighbor2 |Neighbor3 |Treated|
| -------- | ----- |-------|------|----------|----------|----------|-------|
| 1980     | AZ    |1999   |100   |CA        |AK        |WV        |1      |
| 1999     | AZ    |1999   |50    |CA        |AK        |WV        |1      |
</code>```

(df: not_treated)

```<code>| year     | state |BC_law |n_ipo |Neighbor1 |Neighbor2 |Neighbor3 |Treated|
| -------- | ----- |-------|------|----------|----------|----------|-------|
| 1980     | WV    |0      |100   |CA        |AK        |WV        |0      |
| 1999     | AK    |0      |80    |CA        |AK        |WV        |0      |
</code>```

In reality the dataframe includes all US states and all their neighbouring states in separate columns. There are data points before and and after the change in legislation.

I have filtered states that have adopted the new BC_law (df: treated_states) and those that haven't (df: not_treated). Now I should find out if the adoption of the new law affects the neighbouring states.

My problem:
I should filter and store into a new dataframe the treated_states dataframes' Neighbor1, Neighbor2, Neighbor3 that exist in the dataframe not_treated

In case you wonder why I need to filter those:
I'll do a difference-in-difference regression to determine if adopting the new law affects the neighboring states that don't adopt the BC_law.

答:
I managed to write this and it seems to work... Maybe it helps someone and a better coder can suggest a more efficient and elegant way to solve this</p>
```<code>#creating a list of states that have not adopted the new legislation
not_treated_list = not_treated.STATE

#df with states that have not adopted the new legislation, that are also neighbouring states that have adopted the new legislation
neighbour = treated_states[(treated_states.Neigh1.isin(not_treated_list)) | (treated_states.Neigh2.isin(not_treated_list)) |(treated_states.Neigh3.isin(not_treated_list)) | (treated_states.Neigh4.isin(not_treated_list)) | (treated_states.Neigh5.isin(not_treated_list)) | (treated_states.Neigh6.isin(not_treated_list)) | (treated_states.Neigh7.isin(not_treated_list)) | (treated_states.Neigh8.isin(not_treated_list)) ]

neighbour
</code>```

Body:
I've tried to figure this one out, but all methods end up with errors.

Quick background info: I have a dataframe with US states and info when a state has adopted a new law. In addition, the dataframe tells which are the neighbouring states. Here's a quick mockup:

(df: treated_states)

| year     | state |BC_law |n_ipo |Neighbor1 |Neighbor2 |Neighbor3 |Treated|
| -------- | ----- |-------|------|----------|----------|----------|-------|
| 1980     | AZ    |1999   |100   |CA        |AK        |WV        |1      |
| 1999     | AZ    |1999   |50    |CA        |AK        |WV        |1      |

(df: not_treated)

| year     | state |BC_law |n_ipo |Neighbor1 |Neighbor2 |Neighbor3 |Treated|
| -------- | ----- |-------|------|----------|----------|----------|-------|
| 1980     | WV    |0      |100   |CA        |AK        |WV        |0      |
| 1999     | AK    |0      |80    |CA        |AK        |WV        |0      |

In reality the dataframe includes all US states and all their neighbouring states in separate columns. There are data points before and and after the change in legislation.

I have filtered states that have adopted the new BC_law (df: treated_states) and those that haven't (df: not_treated). Now I should find out if the adoption of the new law affects the neighbouring states.

My problem:
I should filter and store into a new dataframe the treated_states dataframes' Neighbor1, Neighbor2, Neighbor3 that exist in the dataframe not_treated

In case you wonder why I need to filter those:
I'll do a difference-in-difference regression to determine if adopting the new law affects the neighboring states that don't adopt the BC_law.

Body:
I managed to write this and it seems to work... Maybe it helps someone and a better coder can suggest a more efficient and elegant way to solve this

#creating a list of states that have not adopted the new legislation
not_treated_list = not_treated.STATE

#df with states that have not adopted the new legislation, that are also neighbouring states that have adopted the new legislation
neighbour = treated_states[(treated_states.Neigh1.isin(not_treated_list)) | (treated_states.Neigh2.isin(not_treated_list)) |(treated_states.Neigh3.isin(not_treated_list)) | (treated_states.Neigh4.isin(not_treated_list)) | (treated_states.Neigh5.isin(not_treated_list)) | (treated_states.Neigh6.isin(not_treated_list)) | (treated_states.Neigh7.isin(not_treated_list)) | (treated_states.Neigh8.isin(not_treated_list)) ]

neighbour


问:
Best way to run different versions of a project on GIT?
I have to add an additional version of my project for a new customer.

The goals are:

One main version of the project that keeps common code and a
group of customer-oriented versions with specific additions for
every customer.

Be able to upload changes from common version.

The best way would be to break project into independent modules, but I am limited in time and can't stick to that option atm. I am considering 2 options

Fork

Multiple branches withing the same repo

Are there better way to do it? What are the cons and pros?
Thanks.

答:
You could use a branch naming strategy as follows.

<customer_name>/<branch_name>

eg: customer1/get-products

The only caveat in this naming strategy is that when you make paths such as a/b/c as branch names in git, you cannot later have a/b or a, so you cannot have a branch named as customer and another branch named as customer/dev, git wont allow that.

However you can keep branches such as customer/dev, customer/uat, customer/master and have feature branches such as customer/feature1 etc

Your common functionality can still be in your main branches such as dev, uat, master, etc and you can merge those branches to the individual customer branches when needed.


问:
Invalid header signature; IOException with Apache POI on excel document
I'm getting:

java.io.IOException: Invalid header signature; read
  0x000201060000FFFE, expected 0xE11AB1A1E011CFD0

when trying to add some custom properties to an Excel document using apache POI HPSF.

I'm completely sure the file is Excel OLE2 (not HTML, XML or something else that Excel doesn't complain about).

This is a relevant part of my code:

```<code>try {
     final POIFSFileSystem poifs = new POIFSFileSystem(event.getStream());
     final DirectoryEntry dir = poifs.getRoot();
     final DocumentEntry dsiEntry = (DocumentEntry)
             dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);

     final DocumentInputStream dis = new DocumentInputStream(dsiEntry);
     final PropertySet props = new PropertySet(dis);
     dis.close();
     dsi = new DocumentSummaryInformation(props);
    }
    catch (Exception ex) {
        throw new RuntimeException
            ("Cannot create POI SummaryInformation for event: " + event +
              ", path:" + event.getPath() +
              ", name:" + event.getPath() +
              ", cause:" + ex);
    }
</code>```

I get the same error when trying with word and power point files (also OLE2).

I'm completely out of ideas so any help/pointers are greatly appreciated :)

答:
If you flip the signature number round, you'll see the bytes of the start of your file:

0x000201060000FFFE -> 0xFE 0xFF 0x00 0x00 0x06 0x01 0x02 00

The first two bytes look like a Unicode BOM, 0xFEFF means 16 bit little endian. You then have some low control bytes, the hex codes for 0 then 258 then 2, so maybe it isn't a text file after all.

That file really isn't an OLE2 file, and POI is right to give you the error. I don't know what it is, but I'm guessing that perhaps it might be part of an OLE2 file without it's outer OLE2 wrapper? If you can open it with office, do a save-as and POI should be fine to open that. As it stands, that header isn't an OLE2 file header so POI can't open it for you.

Body:
I'm getting:

java.io.IOException: Invalid header signature; read
  0x000201060000FFFE, expected 0xE11AB1A1E011CFD0

when trying to add some custom properties to an Excel document using apache POI HPSF.

I'm completely sure the file is Excel OLE2 (not HTML, XML or something else that Excel doesn't complain about).

This is a relevant part of my code:

try {
     final POIFSFileSystem poifs = new POIFSFileSystem(event.getStream());
     final DirectoryEntry dir = poifs.getRoot();
     final DocumentEntry dsiEntry = (DocumentEntry)
             dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);

     final DocumentInputStream dis = new DocumentInputStream(dsiEntry);
     final PropertySet props = new PropertySet(dis);
     dis.close();
     dsi = new DocumentSummaryInformation(props);
    }
    catch (Exception ex) {
        throw new RuntimeException
            ("Cannot create POI SummaryInformation for event: " + event +
              ", path:" + event.getPath() +
              ", name:" + event.getPath() +
              ", cause:" + ex);
    }

I get the same error when trying with word and power point files (also OLE2).

I'm completely out of ideas so any help/pointers are greatly appreciated :)


问:
Breakpoints and debugging statements open "read-only inlined content"

Context:

I am working on a React.js app that uses Webpack, and I'm using VS Code as my editor.

The Webpack config is specifying inline-source-map as its devtool option. but I am using hot reloading, too. So, source maps actually come into the browser via this webpack:// protocol.

I am using the following launch.json config:

```<code>{
    "name": "Launch in Chrome",
    "type": "chrome",
    "request": "launch",
    "url" : "https://myapp.local/", // This is not the real app URL
    "trace" : true,
    "sourceMaps": true,
    "webRoot": "${workspaceRoot}/build",
    "sourceMapPathOverrides": {
        "webpack:///*" : "${webRoot}/*"
    },
    "preLaunchTask" : "development",
    "internalConsoleOptions": "openOnSessionStart",
    "smartStep": true,
    "skipFiles": [
        "node_modules/**",
        "extensions:"
    ]
}
</code>```

and I'm using this tasks.json.

Problem

So this mostly works well, except when I put a breakpoint somewhere, it opens the tab in a new tab marked as read-only inlined content from source map:

I just want to be able to debug and work on my files directly!

答:
I was running into the same issue remote debugging Python, thanks the two above answers I was able to solve it.

as SimbalCoder suggested I saved the workspace. I suppose this is needed to set your workspace folder path.

I then modified my launch.json as such:

```<code>{
            "name": "Python: Remote Attach",
            "type": "python",
            "request": "attach",
            "connect": {
                "host": "localhost",
                "port": 5678
            },
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}/Scripts/MyScripts/"
                }
            ],
        }
</code>```

Now the pathMappings are pointing to the correct file and upon debugger entry it is opening the correct file.

Body:
Context:

I am working on a React.js app that uses Webpack, and I'm using VS Code as my editor.

The Webpack config is specifying inline-source-map as its devtool option. but I am using hot reloading, too. So, source maps actually come into the browser via this webpack:// protocol.

I am using the following launch.json config:

{
    "name": "Launch in Chrome",
    "type": "chrome",
    "request": "launch",
    "url" : "https://myapp.local/", // This is not the real app URL
    "trace" : true,
    "sourceMaps": true,
    "webRoot": "${workspaceRoot}/build",
    "sourceMapPathOverrides": {
        "webpack:///*" : "${webRoot}/*"
    },
    "preLaunchTask" : "development",
    "internalConsoleOptions": "openOnSessionStart",
    "smartStep": true,
    "skipFiles": [
        "node_modules/**",
        "extensions:"
    ]
}

and I'm using this tasks.json.

Problem

So this mostly works well, except when I put a breakpoint somewhere, it opens the tab in a new tab marked as read-only inlined content from source map:

I just want to be able to debug and work on my files directly!

Body:
I was running into the same issue remote debugging Python, thanks the two above answers I was able to solve it.

as SimbalCoder suggested I saved the workspace. I suppose this is needed to set your workspace folder path.

I then modified my launch.json as such:

{
            "name": "Python: Remote Attach",
            "type": "python",
            "request": "attach",
            "connect": {
                "host": "localhost",
                "port": 5678
            },
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}/Scripts/MyScripts/"
                }
            ],
        }

Now the pathMappings are pointing to the correct file and upon debugger entry it is opening the correct file.


问:
How to run a github workflow job conditionally and pass env vars between jobs
I have this in my github workflow .yml file

name: Release workflow (pipeline)

# Enable Buildkit and let compose use it to speed up image building
env:
  DOCKER_BUILDKIT: 1
  COMPOSE_DOCKER_CLI_BUILD: 1
  RELEASE_ID: ''  # this env var will be modified in Create release job > Set release number step, so to be used in the deploy job

on:
  workflow_dispatch:
    inputs:
      environment:
        description: Environment to create the release for
        required: true
        type: choice
        options:
          # - dev
          - prod
        default: prod

      should_auto_deploy:
        description: Auto-deploy the release
        required: false
        type: boolean
        default: 'false'

# some other lines

jobs:
  create_release:
    name: Create release
    needs: run_tests
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      # i have this line in the bash script for this step, to modify the global env var above
      # echo "RELEASE_ID=$releaseId" >> $GITHUB_ENV
      - name: Set release number
        run: |
          chmod +x ./scripts/github-workflow/set-release-number.sh
          ./scripts/github-workflow/set-release-number.sh \
            -e ${{ github.event.inputs.environment }} \
            -n $(date +%Y-%m-%d)-${{ github.ref_name }}-${{ github.run_id }}

# some other lines

  deploy:
    name: Deploy release
    needs: create_release
    # this is the problematic condition.
    # this job ALWAYS runs even when i dont tick the checkbox to set `github.event.inputs.should_auto_deploy` to true
    if: ${{ github.event.inputs.should_auto_deploy && needs.create_release.result == 'success' }}
    uses: Aplanke/ApiBackend/.github/workflows/deployment.yml@main
    with:
      environment: ${{ github.event.inputs.environment }}
      # the updated env var should be passed to this job
      release_number: ${{ github.env.RELEASE_ID }}
```

What I expect:

Asked in How to pass data between github workflow jobs

The deploy job should only run when github.event.inputs.should_auto_deploy is true and the create_release job was successful

What happens:
The deploy jub always runs, even when github.event.inputs.should_auto_deploy is false (not selected in UI)

How do I fix these?

答:
Booleans in GitHub actions are not real booleans, you can read about the problem here.

You have to use:
{{ github.event.inputs.should_auto_deploy == 'true' }}

And for ENV variable - it's really bad approach to use ENV variables like that - there is explicit way of exchanging data between jobs described in here

At the end this workflow should be like this:

```<code>jobs:
  create_release:
    name: Create release
    needs: run_tests
    runs-on: ubuntu-latest
    outputs: ${{ steps.set_release_number.release_id }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Set release number
        id: set_release_number
        run: echo "::set-output name=release_id::RELEASE_ID"
  deploy:
    name: Deploy release
    needs: create_release
    if: ${{ github.event.inputs.should_auto_deploy == 'true' && needs.create_release.result == 'success' }}
    uses: Aplanke/ApiBackend/.github/workflows/deployment.yml@main
    with:
      environment: ${{ github.event.inputs.environment }}
      release_number: ${{ needs.create_release.outputs.release_id }}
</code>```

Body:
I have this in my github workflow .yml file

name: Release workflow (pipeline)

# Enable Buildkit and let compose use it to speed up image building
env:
  DOCKER_BUILDKIT: 1
  COMPOSE_DOCKER_CLI_BUILD: 1
  RELEASE_ID: ''  # this env var will be modified in Create release job > Set release number step, so to be used in the deploy job

on:
  workflow_dispatch:
    inputs:
      environment:
        description: Environment to create the release for
        required: true
        type: choice
        options:
          # - dev
          - prod
        default: prod

      should_auto_deploy:
        description: Auto-deploy the release
        required: false
        type: boolean
        default: 'false'

# some other lines

jobs:
  create_release:
    name: Create release
    needs: run_tests
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      # i have this line in the bash script for this step, to modify the global env var above
      # echo "RELEASE_ID=$releaseId" >> $GITHUB_ENV
      - name: Set release number
        run: |
          chmod +x ./scripts/github-workflow/set-release-number.sh
          ./scripts/github-workflow/set-release-number.sh \
            -e ${{ github.event.inputs.environment }} \
            -n $(date +%Y-%m-%d)-${{ github.ref_name }}-${{ github.run_id }}

# some other lines

  deploy:
    name: Deploy release
    needs: create_release
    # this is the problematic condition.
    # this job ALWAYS runs even when i dont tick the checkbox to set `github.event.inputs.should_auto_deploy` to true
    if: ${{ github.event.inputs.should_auto_deploy && needs.create_release.result == 'success' }}
    uses: Aplanke/ApiBackend/.github/workflows/deployment.yml@main
    with:
      environment: ${{ github.event.inputs.environment }}
      # the updated env var should be passed to this job
      release_number: ${{ github.env.RELEASE_ID }}

What I expect:

Asked in How to pass data between github workflow jobs

The deploy job should only run when github.event.inputs.should_auto_deploy is true and the create_release job was successful

What happens:
The deploy jub always runs, even when github.event.inputs.should_auto_deploy is false (not selected in UI)

How do I fix these?

Body:
Booleans in GitHub actions are not real booleans, you can read about the problem here.

You have to use:
{{ github.event.inputs.should_auto_deploy == 'true' }}

And for ENV variable - it's really bad approach to use ENV variables like that - there is explicit way of exchanging data between jobs described in here

At the end this workflow should be like this:

jobs:
  create_release:
    name: Create release
    needs: run_tests
    runs-on: ubuntu-latest
    outputs: ${{ steps.set_release_number.release_id }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Set release number
        id: set_release_number
        run: echo "::set-output name=release_id::RELEASE_ID"
  deploy:
    name: Deploy release
    needs: create_release
    if: ${{ github.event.inputs.should_auto_deploy == 'true' && needs.create_release.result == 'success' }}
    uses: Aplanke/ApiBackend/.github/workflows/deployment.yml@main
    with:
      environment: ${{ github.event.inputs.environment }}
      release_number: ${{ needs.create_release.outputs.release_id }}


问:
Does memcpy copy bytes in reverse order?
I am little bit confused on usage of memcpy. I though memcpy can be used to copy chunks of binary data to address we desire. I was trying to implement a small logic to directyl convert 2 bytes of hex to 16 bit signed integer without using union.

```<code> #include <stdio.h>
    #include <stdint.h>
    #include <string.h>
    int main()
    {   uint8_t message[2] = {0xfd,0x58};
        // int16_t roll = message[0]<<8;
        // roll|=message[1];
        int16_t roll = 0;
        memcpy((void *)&roll,(void *)&message,2);
        printf("%x",roll);

        return 0;
    }
</code>```

This return 58fd instead of fd58

答:
No, memcpy did not reverse the bytes as it copied them.  That would be a strange and wrong thing for memcpy to do.

The reason the bytes seem to be in the "wrong" order in the program you wrote is that that's the order they're actually in!  There's probably a canonical answer on this somewhere, but here's what you need to understand about byte order, or "endianness".

When you declare a string, it's laid out in memory just about exactly as you expect.  Suppose I write this little code fragment:

```<code>#include <stdio.h>

char string[] = "Hello";
printf("address of string:   %p\n", (void *)&string);
printf("address of 1st char: %p\n", (void *)&string[0]);
printf("address of 5th char: %p\n", (void *)&string[4]);
</code>```

If I compile and run it, I get something like this:

```<code>address of string:   0xe90a49c2
address of 1st char: 0xe90a49c2
address of 5th char: 0xe90a49c6
</code>```

This tells me that the bytes of the string are laid out in memory like this:

```<code>0xe90a49c2    H
0xe90a49c3    e
0xe90a49c4    l
0xe90a49c5    l
0xe90a49c6    o
0xe90a49c7    \0
</code>```

Here I've shown the string vertically, but if we laid it out horizontally, with addresses increasing from left to right, we would see the characters of the string "Hello" laid out from left to right also, just as we would expect.

But that's for strings, which are arrays of char.  But integers of various sizes are not really built out of characters, and it turns out that the individual bytes of an integer are not necessarily laid out in memory in "left-to-right" order as we might expect.  In fact, on the vast majority of machines today, the bytes within an integer are laid out in the opposite order.  Let's take a closer look at how that works.

Suppose I write this code:

```<code>int16_t i2 = 0x1234;
printf("address of short:    %p\n", (void *)&i2);
unsigned char *p = &i2;
printf("%p: %02x\n", p, *p);
p++;
printf("%p: %02x\n", p, *p);
</code>```

This initializes a 16-bit (or "short") integer to the hex value 0x1234, and then uses a pointer to print the two bytes of the integer in "left-to-right" order, that is, with the lower-addressed byte first, followed by the higher-addressed byte.
On my machine, the result is something like:

```<code>address of short:    0xe68c99c8
0xe68c99c8: 34
0xe68c99c9: 12
</code>```

You can clearly see that the byte that's stored at the "front" of the two-byte region in memory is 34, followed by 12.  The least-significant byte is stored first.  This is referred to as "little endian" byte order, because the "little end" of the integer — its least-significant byte, or LSB — comes first.

Larger integers work the same way:

```<code>int32_t i4 = 0x5678abcd;
printf("address of long:     %p\n", (void *)&i4);
p = &i4;
printf("%p: %02x\n", p, *p);
p++;
printf("%p: %02x\n", p, *p);
p++;
printf("%p: %02x\n", p, *p);
p++;
printf("%p: %02x\n", p, *p);
</code>```

This prints:

```<code>address of long:     0xe68c99bc
0xe68c99bc: cd
0xe68c99bd: ab
0xe68c99be: 78
0xe68c99bf: 56
</code>```

There are machines that lay the byes out in the other order, with the most-significant byte (MSB) first.  Those are called "big endian" machines, but for reasons I won't go into they're not as popular.

How do you construct an integer value out of individual bytes if you don't know your machine's byte order?  The best way is to do it "mathematically", based on the properties of the numbers.  For example, let's go back to your original array of bytes:

```<code>uint8_t message[2] = {0xfd, 0x58};
</code>```

Now, you know, because you wrote it, that 0xfd is supposed to be the MSB and 0xf8 is supposed to be the LSB.  So one good way of combining them together into an integer is like this:

```<code>int16_t roll = message[0] << 8;    /* MSB */
roll |= message[1];                /* LSB */
</code>```

The nice thing about this code is that it works correctly on machines of either endianness.  I called this technique "mathematical" because it's equivalent to doing it this other way:

```<code>int16_t roll = message[0] * 256;   /* MSB */
roll += message[1];                /* LSB */
</code>```

And, in fact, this suggestion of mine involving roll = message[0] << 8 is very close to something you already tried, but had commented out in the code you posted.  The difference is that you don't want to think about it in terms of two bytes next to each other in memory; you want to think about it in terms of the most- and least-significant byte.  When you say << 8, you're obviously thinking about the most-significant byte, so that should be message[0].

Body:
I am little bit confused on usage of memcpy. I though memcpy can be used to copy chunks of binary data to address we desire. I was trying to implement a small logic to directyl convert 2 bytes of hex to 16 bit signed integer without using union.

 #include <stdio.h>
    #include <stdint.h>
    #include <string.h>
    int main()
    {   uint8_t message[2] = {0xfd,0x58};
        // int16_t roll = message[0]<<8;
        // roll|=message[1];
        int16_t roll = 0;
        memcpy((void *)&roll,(void *)&message,2);
        printf("%x",roll);

        return 0;
    }

This return 58fd instead of fd58

Body:
No, memcpy did not reverse the bytes as it copied them.  That would be a strange and wrong thing for memcpy to do.

The reason the bytes seem to be in the "wrong" order in the program you wrote is that that's the order they're actually in!  There's probably a canonical answer on this somewhere, but here's what you need to understand about byte order, or "endianness".

When you declare a string, it's laid out in memory just about exactly as you expect.  Suppose I write this little code fragment:

#include <stdio.h>

char string[] = "Hello";
printf("address of string:   %p\n", (void *)&string);
printf("address of 1st char: %p\n", (void *)&string[0]);
printf("address of 5th char: %p\n", (void *)&string[4]);

If I compile and run it, I get something like this:

address of string:   0xe90a49c2
address of 1st char: 0xe90a49c2
address of 5th char: 0xe90a49c6

This tells me that the bytes of the string are laid out in memory like this:

0xe90a49c2    H
0xe90a49c3    e
0xe90a49c4    l
0xe90a49c5    l
0xe90a49c6    o
0xe90a49c7    \0

Here I've shown the string vertically, but if we laid it out horizontally, with addresses increasing from left to right, we would see the characters of the string "Hello" laid out from left to right also, just as we would expect.

But that's for strings, which are arrays of char.  But integers of various sizes are not really built out of characters, and it turns out that the individual bytes of an integer are not necessarily laid out in memory in "left-to-right" order as we might expect.  In fact, on the vast majority of machines today, the bytes within an integer are laid out in the opposite order.  Let's take a closer look at how that works.

Suppose I write this code:

int16_t i2 = 0x1234;
printf("address of short:    %p\n", (void *)&i2);
unsigned char *p = &i2;
printf("%p: %02x\n", p, *p);
p++;
printf("%p: %02x\n", p, *p);

This initializes a 16-bit (or "short") integer to the hex value 0x1234, and then uses a pointer to print the two bytes of the integer in "left-to-right" order, that is, with the lower-addressed byte first, followed by the higher-addressed byte.
On my machine, the result is something like:

address of short:    0xe68c99c8
0xe68c99c8: 34
0xe68c99c9: 12

You can clearly see that the byte that's stored at the "front" of the two-byte region in memory is 34, followed by 12.  The least-significant byte is stored first.  This is referred to as "little endian" byte order, because the "little end" of the integer — its least-significant byte, or LSB — comes first.

Larger integers work the same way:

int32_t i4 = 0x5678abcd;
printf("address of long:     %p\n", (void *)&i4);
p = &i4;
printf("%p: %02x\n", p, *p);
p++;
printf("%p: %02x\n", p, *p);
p++;
printf("%p: %02x\n", p, *p);
p++;
printf("%p: %02x\n", p, *p);

This prints:

address of long:     0xe68c99bc
0xe68c99bc: cd
0xe68c99bd: ab
0xe68c99be: 78
0xe68c99bf: 56

There are machines that lay the byes out in the other order, with the most-significant byte (MSB) first.  Those are called "big endian" machines, but for reasons I won't go into they're not as popular.

How do you construct an integer value out of individual bytes if you don't know your machine's byte order?  The best way is to do it "mathematically", based on the properties of the numbers.  For example, let's go back to your original array of bytes:

uint8_t message[2] = {0xfd, 0x58};

Now, you know, because you wrote it, that 0xfd is supposed to be the MSB and 0xf8 is supposed to be the LSB.  So one good way of combining them together into an integer is like this:

int16_t roll = message[0] << 8;    /* MSB */
roll |= message[1];                /* LSB */

The nice thing about this code is that it works correctly on machines of either endianness.  I called this technique "mathematical" because it's equivalent to doing it this other way:

int16_t roll = message[0] * 256;   /* MSB */
roll += message[1];                /* LSB */

And, in fact, this suggestion of mine involving roll = message[0] << 8 is very close to something you already tried, but had commented out in the code you posted.  The difference is that you don't want to think about it in terms of two bytes next to each other in memory; you want to think about it in terms of the most- and least-significant byte.  When you say << 8, you're obviously thinking about the most-significant byte, so that should be message[0].


问:
What do I do with new installed subversion
So I have installed subversion and am extremely new to it, about 2 hours new in fact.

I am using because I want to track changes made to my website.

I have a site folder where I keep my website files and it has a few pages used for the actual site and then all the images and css stylesheets etc.

At first do I commit add and commit all the files (php, html, css and images) to the svn repository or just the (php and html) or (php, html and css). Im really confused with this as to whats the best practice and what everyone else does.

If I have to upload everything, so images and all, then for every update I do to my site, do I then upload all my files again, or just the file I updated?

答:
You can add all the files for your project and commit them. General rule is that anything that can be "built", "generated" etc by your build process is not checked in to the repo.

Then as you make modifications and commit, it is only the modifications that are added to the repo. The files are not a added again and again. New files, are of course, added when you add them to the repo.

One thing is that you have to consider how you move / rename the files. Use svn cp or svn move or appropriate commands for the operations so that SVN recognizes that it is the same file moved / renamed / copied and will not add the file again.


问:
Decrypt encrypted RSA Private Key on the Browser side
I have an encrypted private RSA key:

```<code>-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,B92E0E3A7B... // <--- IV here.
...
-----END RSA PRIVATE KEY-----
</code>```

I need to decrypt it via a passphrase, basically I need the equivalent of

```<code>openssl rsa -in <encrypted_private.key>  -out <decrypted_private.key>
</code>```

on the browser side with an Angular based client, using webcrypto and pkijs.

答:
So for anyone who will in the future maybe face the same issue like I did:

PKI.js is providing an examples folder in their repo:
OpenSSLPrivateKeyEncryption

In there you will find a method called decrypt.
With the code I were able to decrypt my AES-CBC Private key.

Body:
I have an encrypted private RSA key:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,B92E0E3A7B... // <--- IV here.
...
-----END RSA PRIVATE KEY-----

I need to decrypt it via a passphrase, basically I need the equivalent of

openssl rsa -in <encrypted_private.key>  -out <decrypted_private.key>

on the browser side with an Angular based client, using webcrypto and pkijs.


问:
CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling cublasCreate(handle)
I got the following error when I ran my PyTorch deep learning model in Google Colab

```<code>/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias)
   1370         ret = torch.addmm(bias, input, weight.t())
   1371     else:
-> 1372         output = input.matmul(weight.t())
   1373         if bias is not None:
   1374             output += bias

RuntimeError: CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling `cublasCreate(handle)`
</code>```

I even reduced batch size from 128 to 64 i.e., reduced to half,  but still, I got this error. Earlier, I ran the same code with a batch size of 128 but didn't get any error like this.

答: My model is to classify two classes with only one neuron in the last layer. I had this problem when the last layer is nn.Linear(512,1) in pytorch environment. But my label is just [0] or [1]. I solved this problem by adding the layer: nn.sigmoid()</p>

Body:
I got the following error when I ran my PyTorch deep learning model in Google Colab

/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias)
   1370         ret = torch.addmm(bias, input, weight.t())
   1371     else:
-> 1372         output = input.matmul(weight.t())
   1373         if bias is not None:
   1374             output += bias

RuntimeError: CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling `cublasCreate(handle)`

I even reduced batch size from 128 to 64 i.e., reduced to half,  but still, I got this error. Earlier, I ran the same code with a batch size of 128 but didn't get any error like this.


问:
ReactJS problem with
 element visibility
I have 3 input fields with Name, Address and Year. I pass the length of all the 3 variables as props to this Error component. The errorText should be hidden by default and turn visible if the name is less than 4 letters.

Problem is when I input a name that is less than 4 letters, it changes the errorText variable to the correct "Error in field: name", which I can see by the alert, but the P element still does not change and stays empty.

Also reason why the errorText is not already the one I need by default is, I have more If statements for every alternative instance. For example, if Address and Name are less than 4, then it needs to say "Error in field: address, name".

What could be the issue here? Thanks in advance.

```<code>const Error = (props) => {
    let errorText = '';
    let isVisible = false;

    if (props.nameLength < 4 && props.addressLength >= 4 && props.yearLength >= 4) {
        errorText = "Error in field: name"
        isVisible = true;
        alert("errorText: " + errorText); //This alert is only for testing
    }

    return (
    <div>
        <p style={{visibility: isVisible ? "visible" : "hidden"}}>{errorText}</p>
    </div>
    )
}
</code>```

Error is rendered by the following button inside a return:

```<code><button type="submit" onClick={() => Error({nameLength, addressLength, yearLength})}>Add</button>
</code>```

答:
In react, to affect your DOM we need to use state management. So, every time you're using a variable to change the components/elements it should be provided in state.

try to replace:

let isVisible = false
```
<p>with</p>
<pre class="lang-js prettyprint-override"><code>const [isVisible, setIsVisible] = React.useState(false);
</code>```

and try to change

isVisible = true
```
<p>inside if with</p>
<pre class="lang-js prettyprint-override"><code>setIsVisible(true)
</code>```

Title: ReactJS problem with <p> element visibility

Body:
I have 3 input fields with Name, Address and Year. I pass the length of all the 3 variables as props to this Error component. The errorText should be hidden by default and turn visible if the name is less than 4 letters.

Problem is when I input a name that is less than 4 letters, it changes the errorText variable to the correct "Error in field: name", which I can see by the alert, but the P element still does not change and stays empty.

Also reason why the errorText is not already the one I need by default is, I have more If statements for every alternative instance. For example, if Address and Name are less than 4, then it needs to say "Error in field: address, name".

What could be the issue here? Thanks in advance.

const Error = (props) => {
    let errorText = '';
    let isVisible = false;

    if (props.nameLength < 4 && props.addressLength >= 4 && props.yearLength >= 4) {
        errorText = "Error in field: name"
        isVisible = true;
        alert("errorText: " + errorText); //This alert is only for testing
    }

    return (

{errorText}

    )
}

Error is rendered by the following button inside a return:

<button type="submit" onClick={() => Error({nameLength, addressLength, yearLength})}>Add</button>

Body:
In react, to affect your DOM we need to use state management. So, every time you're using a variable to change the components/elements it should be provided in state.

try to replace:

let isVisible = false

with

const [isVisible, setIsVisible] = React.useState(false);

and try to change

isVisible = true

inside if with

setIsVisible(true)


问:
Combine multiple sed commands into one
I have a file example.txt, I want to delete and replace fields in it.

The following commands are good, but in a very messy way, unfortunately I'm a rookie to sed command.

The commands I used:

sed 's/\-I\.\.\/\.\.\/\.\.//\n/g' example.txt > example.txt1

sed 's/\-I/\n/g' example.txt1 > example.txt2

sed '/^[[:space:]]*$/d' > example.txt2 example.txt3

sed 's/\.\.\/\.\.\/\.\.//g' > example.txt3 example.txt

and then I'm deleting all the unnecessary files.

I'm trying to get the following result:

```<code>Common/Components/Component
Common/Components/Component1
Common/Components/Component2
Common/Components/Component3
Common/Components/Component4
Common/Components/Component5
Common/Components/Component6
Comp
App
</code>```

The file looks like this:

```<code>-I../../../Common/Component -I../../../Common/Component1 -I../../../Common/Component2 -I../../../Common/Component3 -I../../../Common/Component4 -I../../../Common/Component5 -I../../../Common/Component6 -IComp  -IApp  ../../../
</code>```

I want to know how the best way to transform input format to output format standard text-processing tool with 1 call with sed tool or awk.

Title: Combine multiple sed commands into one

Body:
I have a file example.txt, I want to delete and replace fields in it.

The following commands are good, but in a very messy way, unfortunately I'm a rookie to sed command.

The commands I used:

sed 's/\-I\.\.\/\.\.\/\.\.//\n/g' example.txt > example.txt1

sed 's/\-I/\n/g' example.txt1 > example.txt2

sed '/^[[:space:]]*$/d' > example.txt2 example.txt3

sed 's/\.\.\/\.\.\/\.\.//g' > example.txt3 example.txt

and then I'm deleting all the unnecessary files.

I'm trying to get the following result:

Common/Components/Component
Common/Components/Component1
Common/Components/Component2
Common/Components/Component3
Common/Components/Component4
Common/Components/Component5
Common/Components/Component6
Comp
App

The file looks like this:

-I../../../Common/Component -I../../../Common/Component1 -I../../../Common/Component2 -I../../../Common/Component3 -I../../../Common/Component4 -I../../../Common/Component5 -I../../../Common/Component6 -IComp  -IApp  ../../../

I want to know how the best way to transform input format to output format standard text-processing tool with 1 call with sed tool or awk.

Body:
What about

sed -i 's/\-I\.\.\/\.\.\/\.\.//\n/g
s/\-I/\n/g
/^[[:space:]]*$/d
s/\.\.\/\.\.\/\.\.//g' example.txt


问:
Problems with session (hibernate)
I'm getting exception: No Session found for current thread, when I want to connect with database via hibernate, my cfg files:
web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

    <display-name>Here we blog web application</display-name>

    <servlet>
        <servlet-name>web-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>web-dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/web-dispatcher-servlet.xml</param-value>
    </context-param>

</web-app>
</code>```

dispatcher servlet:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="com.lime"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.postgresql.jdbc.Driver"/>
        <property name="url" value="jdbc:postgresql://localhost:8080/come_to_blog_db"/>
        <property name="username" value="postgres"/>
        <property name="password" value="admin"/>
    </bean>

    <bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="packagesToScan">
            <array>
                <value>com.lime</value>
            </array>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect
            </value>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>
</code>```

I tried one solution (adding @Transactional annotation in service layer on method connecting to hibernate,but now i'm getting 2 exceptions:
Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection, any solutions?
-maybe the problem is related with this: Cannot load JDBC driver class 'com.postgresql.jdbc.Driver'
-no one was able to help me, I have all neccesary dependencies, but don't know what's wrong, thanks

答:
Let's start the following segment:

<property name="driverClassName" value="com.postgresql.jdbc.Driver"/>
```
<p>I used "com.postgresql.jdbc.Driver" as well for driverClassName and got the same error as you are getting. The only difference is I gave the database connection details in a resource.xml file and used resource injection to initiate the database connectivity from Java files.</p>
<pre class="lang-xml prettyprint-override"><code><Context>

  <Resource name="jdbc/test"
            auth="Container" type="javax.sql.DataSource"
               maxActive="20" maxIdle="5" maxWait="10000"
               username="postgres" password="password"
               driverClassName="org.postgresql.Driver"
               url="jdbc:postgresql://localhost:5432/test?allowPublicKeyRetrieval=true"/>

</Context>
</code>```

My issue got resolved and there are no issues with database connectivity after I have used driverClassName="org.postgresql.Driver" instead of driverClassName="com.postgresql.jdbc.Driver".

Try the below code instead:

<property name="driverClassName" value="org.postgresql.Driver"/>
```

Clean the project once or multiple times before running with the new code. Once the changes get implemented, it starts working properly.

Title: Problems with session (hibernate)

Body:
I'm getting exception: No Session found for current thread, when I want to connect with database via hibernate, my cfg files:
web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

    <display-name>Here we blog web application</display-name>

    <servlet>
        <servlet-name>web-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>web-dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/web-dispatcher-servlet.xml</param-value>
    </context-param>

</web-app>

dispatcher servlet:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="com.lime"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.postgresql.jdbc.Driver"/>
        <property name="url" value="jdbc:postgresql://localhost:8080/come_to_blog_db"/>
        <property name="username" value="postgres"/>
        <property name="password" value="admin"/>
    </bean>

    <bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="packagesToScan">
            <array>
                <value>com.lime</value>
            </array>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect
            </value>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

I tried one solution (adding @Transactional annotation in service layer on method connecting to hibernate,but now i'm getting 2 exceptions:
Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection, any solutions?
-maybe the problem is related with this: Cannot load JDBC driver class 'com.postgresql.jdbc.Driver'
-no one was able to help me, I have all neccesary dependencies, but don't know what's wrong, thanks

Body:
Let's start the following segment:

<property name="driverClassName" value="com.postgresql.jdbc.Driver"/>

I used "com.postgresql.jdbc.Driver" as well for driverClassName and got the same error as you are getting. The only difference is I gave the database connection details in a resource.xml file and used resource injection to initiate the database connectivity from Java files.

<Context>

  <Resource name="jdbc/test"
            auth="Container" type="javax.sql.DataSource"
               maxActive="20" maxIdle="5" maxWait="10000"
               username="postgres" password="password"
               driverClassName="org.postgresql.Driver"
               url="jdbc:postgresql://localhost:5432/test?allowPublicKeyRetrieval=true"/>

</Context>

My issue got resolved and there are no issues with database connectivity after I have used driverClassName="org.postgresql.Driver" instead of driverClassName="com.postgresql.jdbc.Driver".

Try the below code instead:

<property name="driverClassName" value="org.postgresql.Driver"/>

Clean the project once or multiple times before running with the new code. Once the changes get implemented, it starts working properly.


问:
The seed entity for entity type 'X' cannot be added because the was no value provided for the required property "..ID"
I'm playing wit EF Core 2.1 Preview 2.
I have troubles with HasData (Seed) method in OnModelCreating(ModelBuilder modelBuilder)

My model is simple POCO class that has no annotation.

```<code>public class Tenant {
    public int TenantID {get; set;}
    public string Name {get; set;}
}
</code>```

in my DbContext inside OnModelCreating method is DB model defined as

```<code>modelBuilder.Entity<Tenant>(e => {
    e.HasKey(m => m.TenantID)
     .HasName("PK_Tenants");

    e.Property(m => m.TenantID)
     .UseSqlServerIdentityColumn();

    e.Property(m => m.Name)
     .IsRequired()
     .HasMaxLength(256);
}
</code>```

and the seed mehod is defined as:

```<code>modelBuilder.Entity<Tenant>().HasData(new []{
   new Tenant {
      TenantID = 0,
      Name = "SystemTenant",
   }
});
</code>```

During startap, when ctx.Database.Migrate() is run, I got exception:
The seed entity for entity type 'Tenant' cannot be added because there was no value provided for the required property 'TenantID

答:
Limitations of model seed data:

Temporary data for testing

Data that depends on database state

Data that is large (seeding data gets captured in migration snapshots, and large data can quickly lead to huge files and degraded performance).

Data that needs key values to be generated by the database, including entities that use alternate keys as the identity

Data that requires custom transformation (that is not handled by value conversions), such as some password hashing

Data that requires calls to external API, such as ASP.NET Core Identity roles and users creation

I get "The seed entity for entity type 'Role' cannot be added because a non-zero value is required for property 'Id'. Consider providing a negative value to avoid collisions with non-seed data" error when seeding asp.net Identity Role , so we should set Id value:

```<code>namespace Attendance.Server.Data.Configs;

public class RoleConfig : IEntityTypeConfiguration<Role>
    {
        public void Configure(EntityTypeBuilder<Role> builder)
        {
            builder.ToTable("Role");
            builder.Property(p => p.Name).IsUnicode(false).HasMaxLength(50).IsRequired();
            builder.Property(p => p.NormalizedName).IsUnicode(false).HasMaxLength(50).IsRequired();
            builder.Property(p => p.ConcurrencyStamp).IsUnicode(false);

            // seed
            builder.HasData(
                new Role { Id = 1, Name = "admin", NormalizedName = "ADMIN" },
                new Role { Id = 2, Name = "user", NormalizedName = "USER" }
            );
        }
    }
</code>```

my Role Entity :

```<code>using Microsoft.AspNetCore.Identity;

namespace Attendance.Server.Data.Entities;

public partial class Role : IdentityRole<int>
{

}
</code>```

Add all config classes by only one line code with ApplyConfigurationsFromAssembly method in DbContext :

```<code>namespace Attendance.Server.Data;

public class AppDbContext : IdentityDbContext<User, Role, int, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>, IUnitOfWork
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public Task<int> SaveChangesAsync()
    {
        return base.SaveChangesAsync();
    }

    public void MarkAsDeleted<TEntity>(TEntity entity) => base.Entry(entity).State = EntityState.Deleted;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserConfig).Assembly);
    }
}
</code>```

Body:
I'm playing wit EF Core 2.1 Preview 2.
I have troubles with HasData (Seed) method in OnModelCreating(ModelBuilder modelBuilder)

My model is simple POCO class that has no annotation.

public class Tenant {
    public int TenantID {get; set;}
    public string Name {get; set;}
}

in my DbContext inside OnModelCreating method is DB model defined as

modelBuilder.Entity<Tenant>(e => {
    e.HasKey(m => m.TenantID)
     .HasName("PK_Tenants");

    e.Property(m => m.TenantID)
     .UseSqlServerIdentityColumn();

    e.Property(m => m.Name)
     .IsRequired()
     .HasMaxLength(256);
}

and the seed mehod is defined as:

modelBuilder.Entity<Tenant>().HasData(new []{
   new Tenant {
      TenantID = 0,
      Name = "SystemTenant",
   }
});

During startap, when ctx.Database.Migrate() is run, I got exception:
The seed entity for entity type 'Tenant' cannot be added because there was no value provided for the required property 'TenantID

Body:
Limitations of model seed data:

Temporary data for testing

Data that depends on database state

Data that is large (seeding data gets captured in migration snapshots, and large data can quickly lead to huge files and degraded performance).

Data that needs key values to be generated by the database, including entities that use alternate keys as the identity

Data that requires custom transformation (that is not handled by value conversions), such as some password hashing

Data that requires calls to external API, such as ASP.NET Core Identity roles and users creation

I get "The seed entity for entity type 'Role' cannot be added because a non-zero value is required for property 'Id'. Consider providing a negative value to avoid collisions with non-seed data" error when seeding asp.net Identity Role , so we should set Id value:

namespace Attendance.Server.Data.Configs;

public class RoleConfig : IEntityTypeConfiguration<Role>
    {
        public void Configure(EntityTypeBuilder<Role> builder)
        {
            builder.ToTable("Role");
            builder.Property(p => p.Name).IsUnicode(false).HasMaxLength(50).IsRequired();
            builder.Property(p => p.NormalizedName).IsUnicode(false).HasMaxLength(50).IsRequired();
            builder.Property(p => p.ConcurrencyStamp).IsUnicode(false);

            // seed
            builder.HasData(
                new Role { Id = 1, Name = "admin", NormalizedName = "ADMIN" },
                new Role { Id = 2, Name = "user", NormalizedName = "USER" }
            );
        }
    }

my Role Entity :

using Microsoft.AspNetCore.Identity;

namespace Attendance.Server.Data.Entities;

public partial class Role : IdentityRole<int>
{

}

Add all config classes by only one line code with ApplyConfigurationsFromAssembly method in DbContext :

namespace Attendance.Server.Data;

public class AppDbContext : IdentityDbContext<User, Role, int, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>, IUnitOfWork
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public Task<int> SaveChangesAsync()
    {
        return base.SaveChangesAsync();
    }

    public void MarkAsDeleted<TEntity>(TEntity entity) => base.Entry(entity).State = EntityState.Deleted;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserConfig).Assembly);
    }
}


问:
How do I send a JPEG file along with other data such as Strings and Integers from Android to a Server?
I have a JPEG file and some other data (of type String and Integer) that I'm trying to send from an Android activity to a a REST Controller on my Server (Spring).

How can I do so? There are so many libraries out there I'm not sure which is deprecated or not or what are some best practices...

Thanks in advance!

答:
One of the safest and fastest ways is using an MQTT server. It is not a simple solution, but the best for my programs:

There is a good library on Android to send messages with pictures and other data.

There are enough program languages that can connect to MQTT.

Multiple Android devices can send data.

Connection loss is solved by MQTT.

Guarantee of delivering data: either in the same order or small chance on different order as sent by Android.

It's secure.

To improve security, I use base64 encoding, (also add sha256 checksums and dummy blocks with random data)

For publishing on a website you need to program some backend part on the server.

Most important: It's FREE

For details look:
https://mqtt.org/


问:
Scan for processes and do something when a specific is found
I want my C++ program to scan for processes and when a certain file.exe is running, I want my program to do something (irrelevant here). Could you help me with this task?

I found something on the internet. Is this ok ?

```<code>CreateMutex(NULL, FALSE, NAMEofTHEprocess_exe);
if (GetLastError() == ERROR_ALREADY_EXISTS)return 0;
</code>```

Can I use it in my program? I dont know what the Mutex is.

答:
Here's a basic enumeration of running processes in Windows:

```<code>#define  WINVER      0x0500
#define _WIN32_WINNT 0x0500
#define  PSAPI_VERSION    1
#include <windows.h>
#include <tchar.h>
#include <psapi.h>
#include <sddl.h>

void ListProcesses()
{
  DWORD aProcesses[1024], cbNeeded, cProcesses;
  MEMORYSTATUSEX statex;

  statex.dwLength = sizeof(statex);

  ::GlobalMemoryStatusEx(&statex);

  ::EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded);
  cProcesses = cbNeeded / sizeof(DWORD);

  for (size_t i = 0; i < cProcesses; ++i)
    if(aProcesses[i] != 0)
      std::cout << "PID: " << aProcesses[i] << ", Name: " << getProcessNameByID(aProcesses[i]) << std::endl;
}
</code>```

You can use the final name look-up with getProcessNameByID to make a decision. Here's the code for getProcessPathNameByID:

```<code>#include <tchar.h>

std::string getProcessNameByHandle(HANDLE hProcess)
{
  if (NULL == hProcess)
    return "<unknown>";

  TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
  HMODULE hMod;
  DWORD cbNeeded;

  if (::EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
    ::GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR));

  return std::string(szProcessName);
}

std::string getProcessNameByID(DWORD processID)
{
  HANDLE      hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
  std::string result   = getProcessNameByHandle(hProcess);
  ::CloseHandle(hProcess);

  return result;
}
</code>```

Body:
I want my C++ program to scan for processes and when a certain file.exe is running, I want my program to do something (irrelevant here). Could you help me with this task?

I found something on the internet. Is this ok ?

CreateMutex(NULL, FALSE, NAMEofTHEprocess_exe);
if (GetLastError() == ERROR_ALREADY_EXISTS)return 0;

Can I use it in my program? I dont know what the Mutex is.

Body:
Here's a basic enumeration of running processes in Windows:

#define  WINVER      0x0500
#define _WIN32_WINNT 0x0500
#define  PSAPI_VERSION    1
#include <windows.h>
#include <tchar.h>
#include <psapi.h>
#include <sddl.h>

void ListProcesses()
{
  DWORD aProcesses[1024], cbNeeded, cProcesses;
  MEMORYSTATUSEX statex;

  statex.dwLength = sizeof(statex);

  ::GlobalMemoryStatusEx(&statex);

  ::EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded);
  cProcesses = cbNeeded / sizeof(DWORD);

  for (size_t i = 0; i < cProcesses; ++i)
    if(aProcesses[i] != 0)
      std::cout << "PID: " << aProcesses[i] << ", Name: " << getProcessNameByID(aProcesses[i]) << std::endl;
}

You can use the final name look-up with getProcessNameByID to make a decision. Here's the code for getProcessPathNameByID:

#include <tchar.h>

std::string getProcessNameByHandle(HANDLE hProcess)
{
  if (NULL == hProcess)
    return "<unknown>";

  TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
  HMODULE hMod;
  DWORD cbNeeded;

  if (::EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
    ::GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR));

  return std::string(szProcessName);
}

std::string getProcessNameByID(DWORD processID)
{
  HANDLE      hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
  std::string result   = getProcessNameByHandle(hProcess);
  ::CloseHandle(hProcess);

  return result;
}