问:
creating a value based on an excel cell, and pushing it into a textbox or label in a userform
I am trying to create financial process and system in excel regarding Purchase Order in one of my company entity's.
I have a created a user form BUT I am trying to have a value of a cell in a worksheet representing on that userform.

I am wanting the PO number to be represented in the user form. that PO number will come from a worksheet with all PO number and just take the last number and +1 to it.
this will then be submitted with all the other information for approval.
I am having an issue with the below code. can anyone help? with ideas and also a explanation into your thinking to workout where I am going wrong.

all advice welcome. I'm very new to VBA.

```<code>' POnumber variable
Dim PONumber As Long

' variable for worksheet
Dim PONumberData As Worksheet

' variable for last POnumber
Dim lastPONumber As Integer

' variable for last POnumber
Dim PONumtxtBox As TextBox

' variable for textbox on userform
Dim PONumtxtBox As TextBox

' variable for PO integer converted to string
Dim PONumberstring As String

' set textbox variable to userform Textbox

Set PONumtxtBox = Me.PONumberTxtBox

' work outs the last PO number on the PONumberData worksheet

lastPONumber = PONumberData.Range("A2").End(xlDown).Value

' Take's last PO Number and add 1 to it to create next PO number

PONumber = lastPONumber + 1

' converts integer PO number in cell on PONumberData worksheet to string

PONumberstring = CStr(PONumber)

' should add that number to userform * but isn't *

PONumtxtBox.Text = PONumberstring
</code>```

I'm hoping to have a PO number in the userform

答:
You could create a label box inside your UserForm to hold the "PO Number". In the example below, the code is added to the UserForm directly and ran on initialization. It finds the last number in a column and adds one. This assumes that you have your PO Numbers in order in your sheet, otherwise it would not be very helpful.

The "PONumb" references the named label in the UserForm.

```<code>Private Sub UserForm_Initialize()

    With ThisWorkbook.Worksheets("Sheet1")

        Dim R As Integer

        R = .Cells(.Rows.Count, 1).End(xlUp).Row

        Me.PONumb = .Range("A" & R).Value + 1

    End With

End Sub
</code>```

Body:
I am trying to create financial process and system in excel regarding Purchase Order in one of my company entity's.
I have a created a user form BUT I am trying to have a value of a cell in a worksheet representing on that userform.

I am wanting the PO number to be represented in the user form. that PO number will come from a worksheet with all PO number and just take the last number and +1 to it.
this will then be submitted with all the other information for approval.
I am having an issue with the below code. can anyone help? with ideas and also a explanation into your thinking to workout where I am going wrong.

all advice welcome. I'm very new to VBA.

' POnumber variable
Dim PONumber As Long

' variable for worksheet
Dim PONumberData As Worksheet

' variable for last POnumber
Dim lastPONumber As Integer

' variable for last POnumber
Dim PONumtxtBox As TextBox

' variable for textbox on userform
Dim PONumtxtBox As TextBox

' variable for PO integer converted to string
Dim PONumberstring As String

' set textbox variable to userform Textbox

Set PONumtxtBox = Me.PONumberTxtBox

' work outs the last PO number on the PONumberData worksheet

lastPONumber = PONumberData.Range("A2").End(xlDown).Value

' Take's last PO Number and add 1 to it to create next PO number

PONumber = lastPONumber + 1

' converts integer PO number in cell on PONumberData worksheet to string

PONumberstring = CStr(PONumber)

' should add that number to userform * but isn't *

PONumtxtBox.Text = PONumberstring

I'm hoping to have a PO number in the userform

Body:
You could create a label box inside your UserForm to hold the "PO Number". In the example below, the code is added to the UserForm directly and ran on initialization. It finds the last number in a column and adds one. This assumes that you have your PO Numbers in order in your sheet, otherwise it would not be very helpful.

The "PONumb" references the named label in the UserForm.

Private Sub UserForm_Initialize()

    With ThisWorkbook.Worksheets("Sheet1")

        Dim R As Integer

        R = .Cells(.Rows.Count, 1).End(xlUp).Row

        Me.PONumb = .Range("A" & R).Value + 1

    End With

End Sub


来源: stackexchange

问:
VarHandle get/setOpaque
I keep fighting to understand what VarHandle::setOpaque and VarHandle::getOpaque are really doing. It has not been easy so far - there are some things I think I get (but will not present them in the question itself, not to muddy the waters), but overall this is miss-leading at best for me.

The documentation:

Returns the value of a variable, accessed in program order...

Well in my understanding if I have:

```<code>int xx = x; // read x
int yy = y; // read y
</code>```

These reads can be re-ordered. On the other had if I have:

```<code>// simplified code, does not compile, but reads happen on the same "this" for example
int xx = VarHandle_X.getOpaque(x);
int yy = VarHandle_Y.getOpaque(y);
</code>```

This time re-orderings are not possible? And this is what it means "program order"? Are we talking about insertions of barriers here for this re-ordering to be prohibited? If so, since these are two loads, would the same be achieved? via:

```<code> int xx = x;
 VarHandle.loadLoadFence()
 int yy = y;
</code>```

But it gets a lot trickier:

... but with no assurance of memory ordering effects with respect to other threads.

I could not come up with an example to even pretend I understand this part.

It seems to me that this documentation is targeted at people who know exactly what they are doing (and I am definitely not one)... So can someone shed some light here?

答:
Well in my understanding if I have:

```<code>int xx = x; // read x
int yy = y; // read y
</code>```

These reads can be re-ordered.

These reads may not only happen to be reordered, they may not happen at all. The thread may use an old, previously read value for x and/or y or values it did previously write to these variables whereas, in fact, the write may not have been performed yet, so the “reading thread” may use values, no other thread may know of and are not in the heap memory at that time (and probably never will).

On the other had if I have:

```<code>// simplified code, does not compile, but reads happen on the same "this" for example
int xx = VarHandle_X.getOpaque(x);
int yy = VarHandle_Y.getOpaque(y);
</code>```

This time re-orderings are not possible? And this is what it means "program order"?

Simply said, the main feature of opaque reads and writes, is, that they will actually happen. This implies that they can not be reordered in respect to other memory access of at least the same strength, but that has no impact for ordinary reads and writes.

The term program order is defined by the JLS:

… the program order of t is a total order that reflects the order in which these actions would be performed according to the intra-thread semantics of t.

That’s the evaluation order specified for expressions and statements. The order in which we perceive the effects, as long as only a single thread is involved.

Are we talking about insertions of barriers here for this re-ordering to be prohibited?

No, there is no barrier involved, which might be the intention behind the phrase “…but with no assurance of memory ordering effects with respect to other threads”.

Perhaps, we could say that opaque access works a bit like volatile was before Java 5, enforcing read access to see the most recent heap memory value (which makes only sense if the writing end also uses opaque or an even stronger mode), but with no effect on other reads or writes.

So what can you do with it?

A typical use case would be a cancellation or interruption flag that is not supposed to establish a happens-before relationship. Often, the stopped background task has no interest in perceiving actions made by the stopping task prior to signalling, but will just end its own activity. So writing and reading the flag with opaque mode would be sufficient to ensure that the signal is eventually noticed (unlike the normal access mode), but without any additional negative impact on the performance.

Likewise, a background task could write progress updates, like a percentage number, which the reporting (UI) thread is supposed to notice timely, while no happens-before relationship is required before the publication of the final result.

It’s also useful if you just want atomic access for long and double, without any other impact.

Since truly immutable objects using final fields are immune to data races, you can use opaque modes for timely publishing immutable objects, without the broader effect of release/acquire mode publishing.

A special case would be periodically checking a status for an expected value update and once available, querying the value with a stronger mode (or executing the matching fence instruction explicitly). In principle, a happens-before relationship can only be established between the write and its subsequent read anyway, but since optimizers usually don’t have the horizon to identify such a inter-thread use case, performance critical code can use opaque access to optimize such scenario.

ContentLicense: CC BY-SA 4.0

Title: VarHandle get/setOpaque

Body:
I keep fighting to understand what VarHandle::setOpaque and VarHandle::getOpaque are really doing. It has not been easy so far - there are some things I think I get (but will not present them in the question itself, not to muddy the waters), but overall this is miss-leading at best for me.

The documentation:

Returns the value of a variable, accessed in program order...

Well in my understanding if I have:

int xx = x; // read x
int yy = y; // read y

These reads can be re-ordered. On the other had if I have:

// simplified code, does not compile, but reads happen on the same "this" for example
int xx = VarHandle_X.getOpaque(x);
int yy = VarHandle_Y.getOpaque(y);

This time re-orderings are not possible? And this is what it means "program order"? Are we talking about insertions of barriers here for this re-ordering to be prohibited? If so, since these are two loads, would the same be achieved? via:

 int xx = x;
 VarHandle.loadLoadFence()
 int yy = y;

But it gets a lot trickier:

... but with no assurance of memory ordering effects with respect to other threads.

I could not come up with an example to even pretend I understand this part.

It seems to me that this documentation is targeted at people who know exactly what they are doing (and I am definitely not one)... So can someone shed some light here?

Body:
Well in my understanding if I have:

int xx = x; // read x
int yy = y; // read y

These reads can be re-ordered.

These reads may not only happen to be reordered, they may not happen at all. The thread may use an old, previously read value for x and/or y or values it did previously write to these variables whereas, in fact, the write may not have been performed yet, so the “reading thread” may use values, no other thread may know of and are not in the heap memory at that time (and probably never will).

On the other had if I have:

// simplified code, does not compile, but reads happen on the same "this" for example
int xx = VarHandle_X.getOpaque(x);
int yy = VarHandle_Y.getOpaque(y);

This time re-orderings are not possible? And this is what it means "program order"?

Simply said, the main feature of opaque reads and writes, is, that they will actually happen. This implies that they can not be reordered in respect to other memory access of at least the same strength, but that has no impact for ordinary reads and writes.

The term program order is defined by the JLS:

… the program order of t is a total order that reflects the order in which these actions would be performed according to the intra-thread semantics of t.

That’s the evaluation order specified for expressions and statements. The order in which we perceive the effects, as long as only a single thread is involved.

Are we talking about insertions of barriers here for this re-ordering to be prohibited?

No, there is no barrier involved, which might be the intention behind the phrase “…but with no assurance of memory ordering effects with respect to other threads”.

Perhaps, we could say that opaque access works a bit like volatile was before Java 5, enforcing read access to see the most recent heap memory value (which makes only sense if the writing end also uses opaque or an even stronger mode), but with no effect on other reads or writes.

So what can you do with it?

A typical use case would be a cancellation or interruption flag that is not supposed to establish a happens-before relationship. Often, the stopped background task has no interest in perceiving actions made by the stopping task prior to signalling, but will just end its own activity. So writing and reading the flag with opaque mode would be sufficient to ensure that the signal is eventually noticed (unlike the normal access mode), but without any additional negative impact on the performance.

Likewise, a background task could write progress updates, like a percentage number, which the reporting (UI) thread is supposed to notice timely, while no happens-before relationship is required before the publication of the final result.

It’s also useful if you just want atomic access for long and double, without any other impact.

Since truly immutable objects using final fields are immune to data races, you can use opaque modes for timely publishing immutable objects, without the broader effect of release/acquire mode publishing.

A special case would be periodically checking a status for an expected value update and once available, querying the value with a stronger mode (or executing the matching fence instruction explicitly). In principle, a happens-before relationship can only be established between the write and its subsequent read anyway, but since optimizers usually don’t have the horizon to identify such a inter-thread use case, performance critical code can use opaque access to optimize such scenario.


问:
Why aren't my if statements inside the for loops working properly?
I'm trying to do a w3resource.com exercise and my if statements inside the for loops aren't being respected(the code inside the if statement is running even if the condition isn't true). Please help me

I've already tried to replace the for loops with while loops and the problem persisted. I've tried to see what's wrong with my if statements but I couldn't find anything.

```<code>#include <iostream>
#include <algorithm>
#include <iterator>

void findAndPrintThe3LargestElements(int array[], int arraySize)
{
    int largestNumbers[] = { array[0], array[0], array[0] };
    for (int nextIndexNumber = 1; nextIndexNumber < arraySize; ++nextIndexNumber)
    {
        if (array[nextIndexNumber] > largestNumbers[0])
            largestNumbers[0] = array[nextIndexNumber];
    }

    for (int nextIndexNumber = 1; nextIndexNumber < arraySize; ++nextIndexNumber)
    {
        if (array[nextIndexNumber] > largestNumbers[1] && array[nextIndexNumber] != largestNumbers[0]);
        {
            largestNumbers[1] = array[nextIndexNumber];
        }
    }

    for (int nextIndexNumber = 1; nextIndexNumber < arraySize; ++nextIndexNumber)
    {
        if (array[nextIndexNumber] > largestNumbers[2] && array[nextIndexNumber] != largestNumbers[0] &&
            array[nextIndexNumber] != largestNumbers[1]);
        {
            largestNumbers[2] = array[nextIndexNumber];
        }
    }

    std::cout << "The three largest numbers in the array are: " << largestNumbers[0] << ", " << largestNumbers[1]
        << ", " << largestNumbers[2] << ".";
}

int main()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int arraySize = std::size(array);
    findAndPrintThe3LargestElements(array, arraySize);
    return 0;
}
</code>```

The program is not working properly, outputting the wrong numbers.

答:
In the second and third loop you put semicolon after the if:

```<code>if (<condidion>);
{
    <your code>
}
</code>```

so effectively the condition has empty block and the block with your code is always executed. It is more visible like this:

```<code>if (<condition>)
    ;    // no operation here

{        // always executed
    <your code>
}
</code>```

Body:
I'm trying to do a w3resource.com exercise and my if statements inside the for loops aren't being respected(the code inside the if statement is running even if the condition isn't true). Please help me

I've already tried to replace the for loops with while loops and the problem persisted. I've tried to see what's wrong with my if statements but I couldn't find anything.

#include <iostream>
#include <algorithm>
#include <iterator>

void findAndPrintThe3LargestElements(int array[], int arraySize)
{
    int largestNumbers[] = { array[0], array[0], array[0] };
    for (int nextIndexNumber = 1; nextIndexNumber < arraySize; ++nextIndexNumber)
    {
        if (array[nextIndexNumber] > largestNumbers[0])
            largestNumbers[0] = array[nextIndexNumber];
    }

    for (int nextIndexNumber = 1; nextIndexNumber < arraySize; ++nextIndexNumber)
    {
        if (array[nextIndexNumber] > largestNumbers[1] && array[nextIndexNumber] != largestNumbers[0]);
        {
            largestNumbers[1] = array[nextIndexNumber];
        }
    }

    for (int nextIndexNumber = 1; nextIndexNumber < arraySize; ++nextIndexNumber)
    {
        if (array[nextIndexNumber] > largestNumbers[2] && array[nextIndexNumber] != largestNumbers[0] &&
            array[nextIndexNumber] != largestNumbers[1]);
        {
            largestNumbers[2] = array[nextIndexNumber];
        }
    }

    std::cout << "The three largest numbers in the array are: " << largestNumbers[0] << ", " << largestNumbers[1]
        << ", " << largestNumbers[2] << ".";
}

int main()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int arraySize = std::size(array);
    findAndPrintThe3LargestElements(array, arraySize);
    return 0;
}

The program is not working properly, outputting the wrong numbers.

Body:
In the second and third loop you put semicolon after the if:

if (<condidion>);
{
    <your code>
}

so effectively the condition has empty block and the block with your code is always executed. It is more visible like this:

if (<condition>)
    ;    // no operation here

{        // always executed
    <your code>
}


问:
Setting hostname of a Surge CNAME record to @ on GoDaddy
I'm trying to deploy my portfolio to my domain www.dillonbartkus.com with Surge.

The instructions are as follows:

I'm using a GoDaddy domain that I bought through Google Suite.

In the picture it shows a CNAME record with a hostname of www and @ and a value of na-west1.surge.sh. When I try to do this in my DNS records, I can do the CNAME with www for the name, but when I try to do the @ I get an error that says 'Enter your host name as "@", "sub-domain" '.

I have tried all different syntax for this, but it won't go through.

How do I add / edit the other to include @ ?

答:
You must delete all A & CNAME records on GoDaddy first, then follow the Surge documentation. GoDaddy only allows a CNAME www record to be added, not @.

The documentation states you should replace the CNAME @ (apex domain) record with an A @ record using Surge's IP.

Thus, on GoDaddy you must delete all existing A & CNAME records and add the following two records following a Type : Name : Value format:

CNAME: www : na-west1.surge.sh

A : @ : 45.55.110.124

This had my domain resolving within 5 minutes.

https://www.godaddy.com/community/Managing-Domains/domain-DNS-with-surge-sh/td-p/24075


问:
Vector option in Java
I am using vector of object. My issue is the removal from vector is expensive operation( O(n^2)). What would be the replacement of vector in Java. In my uses addition and removal is extensively happens.

i am C++ person don't know much Java

答:
i think, Vector using System.arrayCopy which complexity is O(n^2)

It is correct that Vector will use System.arrayCopy to move the elements.  However the System.arrayCopy() call copies at most Vector.size() elements, and hence is O(N) where N is the vector's size.

Hence O(N^2) is incorrect for a single insertion / removal.

In fact, if you want better than O(N) insertion and deletion, you will need to use some kind of linked list type with a cursor abstraction that allows insertion and deletion at "the current position".  Even then you only get better than O(N) if you can do the insertions / deletions in the right order; i.e. not random order.

FWIW, the Java List APIs don't provide such a cursor mechanism ... not least because it would be awkward to use, and only efficient in certain circumstances / implementations.

ContentLicense: CC BY-SA 3.0

Title: Vector option in Java


问:
Having multiple var data
The script below is calling the instagram site of "data1" and prints the UserCount into a Spreadsheet. but I want to use different instagramAccountName

I'd like to set up 3 more datas.

The var instagramAccountName = "data1"&&"data2"; isnt working, so what's your suggestions?

```<code>var sheetName = "Tabellenblatt1";
var instagramAccountName = "data1";

function insertFollowerCount() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(this.sheetName);
  accountdata = getInstagramData(this.instagramAccountName);
  sheet.appendRow([instagramAccountName, Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"), accountdata.followerCount]);
 };

function getInstagramData(username) {
  var r = new RegExp('<script type="text\/javascript">' +
                   '([^{]+?({.*profile_pic_url.*})[^}]+?)' +
                   '<\/script>');
  var url = "https://www.instagram.com/" + username
  var source = UrlFetchApp.fetch(url).getContentText();
  var jsonStr = source.match(r)[2];
  var data = JSON.parse(jsonStr);
  console.log('data', data);
  var oldVariantOfData = data['entry_data']['ProfilePage'][0];
  console.log('oldVariantOfData', oldVariantOfData);

  return {
    followerCount : oldVariantOfData.graphql.user.edge_followed_by.count,
    followCount : oldVariantOfData.graphql.user.edge_follow.count,
    mediaCount : oldVariantOfData.graphql.user.edge_owner_to_timeline_media.count
  };
}
</code>```

答:
First, just reference your global variables by their names, there is no need for this.

Second, "data1" && "data2" equals to "data1 AND data2" (Google Apps Script is a subset of JavaScript), which always stores true in your instagramAccountName variable.

Third, there are a lot of ways to reference multiple account names, but you can write to your instagramAccountName variable an Array of names = ['n1','n2'] and then invoke getInstagramData(username) using a for, for...of loop or forEach method.

In the end, your function should look like this (btw, accountdata should be defined in an outer scope, otherwise you will get a ReferenceError):

```<code>var instagramAccountName = ['data1','data2'];

function insertFollowerCount() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(sheetName);

  instagramAccountName.forEach(function(username){
    accountdata = getInstagramData(username);
    sheet.appendRow([username, Utilities.formatDate(new Date(),
    "GMT", "yyyy-MM-dd"), accountdata.followerCount]);
  });
};
</code>```

References

forEach method reference on MDN

Title: Having multiple var data

Body:
The script below is calling the instagram site of "data1" and prints the UserCount into a Spreadsheet. but I want to use different instagramAccountName

I'd like to set up 3 more datas.

The var instagramAccountName = "data1"&&"data2"; isnt working, so what's your suggestions?

var sheetName = "Tabellenblatt1";
var instagramAccountName = "data1";

function insertFollowerCount() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(this.sheetName);
  accountdata = getInstagramData(this.instagramAccountName);
  sheet.appendRow([instagramAccountName, Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"), accountdata.followerCount]);
 };

function getInstagramData(username) {
  var r = new RegExp('

Body:
First, just reference your global variables by their names, there is no need for this.

Second, "data1" && "data2" equals to "data1 AND data2" (Google Apps Script is a subset of JavaScript), which always stores true in your instagramAccountName variable.

Third, there are a lot of ways to reference multiple account names, but you can write to your instagramAccountName variable an Array of names = ['n1','n2'] and then invoke getInstagramData(username) using a for, for...of loop or forEach method.

In the end, your function should look like this (btw, accountdata should be defined in an outer scope, otherwise you will get a ReferenceError):

var instagramAccountName = ['data1','data2'];

function insertFollowerCount() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(sheetName);

  instagramAccountName.forEach(function(username){
    accountdata = getInstagramData(username);
    sheet.appendRow([username, Utilities.formatDate(new Date(),
    "GMT", "yyyy-MM-dd"), accountdata.followerCount]);
  });
};

References

forEach method reference on MDN


问:
pentaho spoon: how to get filename as value?
I need filename because it has information I don't have in file context.
I already have the related column in my DB.
How to get filename as a column's values?</p>

答:
in your input configuration there is a section called "Additional output fields", there you must go to "Short Filename Field" and select ${Internal.Tranformation.Filename.Name}
then you cant test it on Preview Rows.</p>


问:
Drag and drop images on div
I cant seem to be able to append the images to the ul inside the dropzone div.I want to have all the images appear horizontally, but so far when I drag images from desktop to the red square nothing happens.

This is something I extracted from the internet. Any help is appreciated.

```<code>    var dropZone = document.getElementById('dropZone');

    dropZone.addEventListener('dragover', function(e) {
        e.stopPropagation();
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
    });

    dropZone.addEventListener('drop', function(e) {
        e.stopPropagation();
        e.preventDefault();
        var files = e.dataTransfer.files;

        for (var i=0, file; file=files[i]; i++) {
            if (file.type.match(/image.*/)) {
            var reader = new FileReader();

            reader.onload = function(e2) {
            // finished reading file data.
            var img = document.createElement('img');
            img.src= e2.target.result;
            node.append(img);
            document.getElementById('image_bar').appendChild(node);
        }

        reader.readAsDataURL(file); .
    }
}
});
</code>```

```<code><div id="dropZone" style="width: 100px; height: 100px; background-color: red">
    <div><ul id="image_bar"></ul></div>
</div>
</code>```

答:
First u need to remove the . on the line reader.readAsDataURL(file); . then when you run the code, you will see in the Console (F12 in chrome) that "node is not defined"

this code works:

create a file named myfile.html with this content:

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Hi</title>
</head>

<body>
<div id="dropZone" style="width: 100px; height: 100px; background-color: red">
    <div><ul id="image_bar"></ul></div>
</div>
  <script>
var dropZone = document.getElementById('dropZone');
    dropZone.addEventListener('dragover', function(e) {
            e.stopPropagation();
            e.preventDefault();
            e.dataTransfer.dropEffect = 'copy';
        });

        dropZone.addEventListener('drop', function(e) {
            e.stopPropagation();
            e.preventDefault();
            var files = e.dataTransfer.files;

            for (var i=0, file; file=files[i]; i++) {
                if (file.type.match(/image.*/)) {
                var reader = new FileReader();

                reader.onload = function(e2) {
                // finished reading file data.
                var img = document.createElement('img');
                img.src= e2.target.result;
                document.getElementById('image_bar').appendChild(img);
            }

            reader.readAsDataURL(file);
        }
    }
    });

</script>
</body>
</html>
</code>```

Title: Drag and drop images on div

Body:
I cant seem to be able to append the images to the ul inside the dropzone div.I want to have all the images appear horizontally, but so far when I drag images from desktop to the red square nothing happens.

This is something I extracted from the internet. Any help is appreciated.

    var dropZone = document.getElementById('dropZone');

    dropZone.addEventListener('dragover', function(e) {
        e.stopPropagation();
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
    });

    dropZone.addEventListener('drop', function(e) {
        e.stopPropagation();
        e.preventDefault();
        var files = e.dataTransfer.files;

        for (var i=0, file; file=files[i]; i++) {
            if (file.type.match(/image.*/)) {
            var reader = new FileReader();

            reader.onload = function(e2) {
            // finished reading file data.
            var img = document.createElement('img');
            img.src= e2.target.result;
            node.append(img);
            document.getElementById('image_bar').appendChild(node);
        }

        reader.readAsDataURL(file); .
    }
}
});

Body:
First u need to remove the . on the line reader.readAsDataURL(file); . then when you run the code, you will see in the Console (F12 in chrome) that "node is not defined"

this code works:

create a file named myfile.html with this content:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Hi</title>
</head>

<body>
<div id="dropZone" style="width: 100px; height: 100px; background-color: red">
    <div><ul id="image_bar"></ul></div>
</div>
  <script>
var dropZone = document.getElementById('dropZone');
    dropZone.addEventListener('dragover', function(e) {
            e.stopPropagation();
            e.preventDefault();
            e.dataTransfer.dropEffect = 'copy';
        });

        dropZone.addEventListener('drop', function(e) {
            e.stopPropagation();
            e.preventDefault();
            var files = e.dataTransfer.files;

            for (var i=0, file; file=files[i]; i++) {
                if (file.type.match(/image.*/)) {
                var reader = new FileReader();

                reader.onload = function(e2) {
                // finished reading file data.
                var img = document.createElement('img');
                img.src= e2.target.result;
                document.getElementById('image_bar').appendChild(img);
            }

            reader.readAsDataURL(file);
        }
    }
    });

</script>
</body>
</html>


问:
Use a ranged object for a loop
I'm searching for a certain header and saving it as a ranged object (FindEQ4). Now I want to use this header as a starting point for a dynamic ranged object. My question is, how can I get the information that Header 1 is in C5 and use it like Set TestR = .Range("C" & 5 + x)?

```<code> Sub FindCopyPasteV3()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ4 As Range
        Dim TestR As Range
        Dim x As Long

        Set FindEQ4 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        'I'm looking for something like TestR = .Range("FindEQ4" + x)
        'which works like Set TestR = .Range("C" & 5 + x)

    End With

End Sub
</code>```

答:
Use the Offset property of the Range object.

https://learn.microsoft.com/en-us/office/vba/api/excel.range.offset

This returns a range that is offset from the original by the specified amount. The first parameter is the number of rows to offset by (positive downwards, negative upwards) and the second parameter is the number of columns to offset by (positive right, negative left).

so for example

.Range("D7").offset(-3,2) would represent "F4", 3 rows up and 2 columns to the right.

```<code>Sub FindCopyPasteV3()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ4 As Range
        Dim TestR As Range
        Dim X As Long

        Set FindEQ4 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        Set TestR = FindEQ4.Offset(X, 0) 'X rows down, same column

    End With

End Sub
</code>```

Title: Use a ranged object for a loop

Body:
I'm searching for a certain header and saving it as a ranged object (FindEQ4). Now I want to use this header as a starting point for a dynamic ranged object. My question is, how can I get the information that Header 1 is in C5 and use it like Set TestR = .Range("C" & 5 + x)?

 Sub FindCopyPasteV3()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ4 As Range
        Dim TestR As Range
        Dim x As Long

        Set FindEQ4 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        'I'm looking for something like TestR = .Range("FindEQ4" + x)
        'which works like Set TestR = .Range("C" & 5 + x)

    End With

End Sub

Body:
Use the Offset property of the Range object.

https://learn.microsoft.com/en-us/office/vba/api/excel.range.offset

This returns a range that is offset from the original by the specified amount. The first parameter is the number of rows to offset by (positive downwards, negative upwards) and the second parameter is the number of columns to offset by (positive right, negative left).

so for example

.Range("D7").offset(-3,2) would represent "F4", 3 rows up and 2 columns to the right.

Sub FindCopyPasteV3()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ4 As Range
        Dim TestR As Range
        Dim X As Long

        Set FindEQ4 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        Set TestR = FindEQ4.Offset(X, 0) 'X rows down, same column

    End With

End Sub


问:
How can I make a UITextField move up when the keyboard is present - on starting to edit?
With the iOS SDK:

I have a UIView with UITextFields that bring up a keyboard. I need it to be able to:

Allow scrolling of the contents of the UIScrollView to see the other text fields once the keyboard is brought up

Automatically "jump" (by scrolling up) or shortening

I know that I need a UIScrollView.  I've tried changing the class of my UIView to a UIScrollView, but I'm still unable to scroll the textboxes up or down.

Do I need both a UIView and a UIScrollView? Does one go inside the other?

What needs to be implemented in order to automatically scroll to the active text field?

Ideally as much of the setup of the components as possible will be done in Interface Builder. I'd like to only write code for what needs it.

Note: the UIView (or UIScrollView) that I'm working with is brought up by a tabbar (UITabBar), which needs to function as normal.

I am adding the scroll bar just for when the keyboard comes up.  Even though it's not needed, I feel like it provides a better interface because then the user can scroll and change textboxes, for example.

I've got it working where I change the frame size of the UIScrollView when the keyboard goes up and down. I'm simply using:

```<code>-(void)textFieldDidBeginEditing:(UITextField *)textField {
    //Keyboard becomes visible
    scrollView.frame = CGRectMake(scrollView.frame.origin.x,
                                  scrollView.frame.origin.y,
    scrollView.frame.size.width,
    scrollView.frame.size.height - 215 + 50);   // Resize
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    // Keyboard will hide
    scrollView.frame = CGRectMake(scrollView.frame.origin.x,
                                  scrollView.frame.origin.y,
                                  scrollView.frame.size.width,
                                  scrollView.frame.size.height + 215 - 50); // Resize
}
</code>```

However, this doesn't automatically "move up" or center the lower text fields in the visible area, which is what I would really like.

答:
I've put together a universal, drop-in UIScrollView, UITableView and even UICollectionView subclass that takes care of moving all text fields within it out of the way of the keyboard.

When the keyboard is about to appear, the subclass will find the subview that's about to be edited, and adjust its frame and content offset to make sure that view is visible, with an animation to match the keyboard pop-up. When the keyboard disappears, it restores its prior size.

It should work with basically any setup, either a UITableView-based interface, or one consisting of views placed manually.

Here' tis: solution for moving text fields out of the way of the keyboard

Body:
With the iOS SDK:

I have a UIView with UITextFields that bring up a keyboard. I need it to be able to:

Allow scrolling of the contents of the UIScrollView to see the other text fields once the keyboard is brought up

Automatically "jump" (by scrolling up) or shortening

I know that I need a UIScrollView.  I've tried changing the class of my UIView to a UIScrollView, but I'm still unable to scroll the textboxes up or down.

Do I need both a UIView and a UIScrollView? Does one go inside the other?

What needs to be implemented in order to automatically scroll to the active text field?

Ideally as much of the setup of the components as possible will be done in Interface Builder. I'd like to only write code for what needs it.

Note: the UIView (or UIScrollView) that I'm working with is brought up by a tabbar (UITabBar), which needs to function as normal.

I am adding the scroll bar just for when the keyboard comes up.  Even though it's not needed, I feel like it provides a better interface because then the user can scroll and change textboxes, for example.

I've got it working where I change the frame size of the UIScrollView when the keyboard goes up and down. I'm simply using:

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    //Keyboard becomes visible
    scrollView.frame = CGRectMake(scrollView.frame.origin.x,
                                  scrollView.frame.origin.y,
    scrollView.frame.size.width,
    scrollView.frame.size.height - 215 + 50);   // Resize
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    // Keyboard will hide
    scrollView.frame = CGRectMake(scrollView.frame.origin.x,
                                  scrollView.frame.origin.y,
                                  scrollView.frame.size.width,
                                  scrollView.frame.size.height + 215 - 50); // Resize
}

However, this doesn't automatically "move up" or center the lower text fields in the visible area, which is what I would really like.


问:
Microsoft-Graph token using request is to small
I'm trying to get the access token for my Microsoft-Graph application using request to send a POST request.
The problem is that the token i get as a response is only 1188 characters long. While the token i get when i use Postman is 1461 characters long. Every time i send a request it generates a brand new token, but the one i get through request in nodejs is always 1188 and the one in postman is always 1461.

I have tried different things such as generating a new app api id in Microsoft Azure, but it keeps giving the same results.

This is my code, i took out sensitive information though by replacing it with the word CENSORED.
I'm using the EXACT same request parameters in Postman

```<code>const endpoint = "https://login.microsoftonline.com/CENSORED/oauth2/token";
    const requestParams = {
      client_id: "CENSORED",
      client_secret: "CENSORED",
      resource: "https://graph.windows.net",
      grant_type: "client_credentials"
    };

    let accessToken = await

    request.post({
      url: endpoint,
      form: requestParams
    }, function (err, response, body) {
      if (err) {
        console.log("error");
      } else {
        console.log("Body=" + body);
        let parsedBody = JSON.parse(body);
        if (parsedBody.error_description) {
          console.log("Error=" + parsedBody.error_description);
        } else {
          getCalendarEvents(parsedBody.access_token);
        }
      }
    });
</code>```

Postman returns an 1461 characters long access token and nodejs request only returns a 1188 characters long access token.

This is what i'm using in Nodejs: https://www.npmjs.com/package/request

答:
The resource https://graph.windows.net is for the legacy Azure AD Graph API. This is a completely separate API from the Microsoft Graph. For the Microsoft Graph, the resource should be https://graph.microsoft.com:

```<code>const endpoint = "https://login.microsoftonline.com/{tenant}/oauth2/token";
    const requestParams = {
      client_id: "{clientid}",
      client_secret: "{clientsecret}",
      resource: "https://graph.microsoft.com",
      grant_type: "client_credentials"
    };
</code>```

Body:
I'm trying to get the access token for my Microsoft-Graph application using request to send a POST request.
The problem is that the token i get as a response is only 1188 characters long. While the token i get when i use Postman is 1461 characters long. Every time i send a request it generates a brand new token, but the one i get through request in nodejs is always 1188 and the one in postman is always 1461.

I have tried different things such as generating a new app api id in Microsoft Azure, but it keeps giving the same results.

This is my code, i took out sensitive information though by replacing it with the word CENSORED.
I'm using the EXACT same request parameters in Postman

const endpoint = "https://login.microsoftonline.com/CENSORED/oauth2/token";
    const requestParams = {
      client_id: "CENSORED",
      client_secret: "CENSORED",
      resource: "https://graph.windows.net",
      grant_type: "client_credentials"
    };

    let accessToken = await

    request.post({
      url: endpoint,
      form: requestParams
    }, function (err, response, body) {
      if (err) {
        console.log("error");
      } else {
        console.log("Body=" + body);
        let parsedBody = JSON.parse(body);
        if (parsedBody.error_description) {
          console.log("Error=" + parsedBody.error_description);
        } else {
          getCalendarEvents(parsedBody.access_token);
        }
      }
    });

Postman returns an 1461 characters long access token and nodejs request only returns a 1188 characters long access token.

This is what i'm using in Nodejs: https://www.npmjs.com/package/request

Body:
The resource https://graph.windows.net is for the legacy Azure AD Graph API. This is a completely separate API from the Microsoft Graph. For the Microsoft Graph, the resource should be https://graph.microsoft.com:

const endpoint = "https://login.microsoftonline.com/{tenant}/oauth2/token";
    const requestParams = {
      client_id: "{clientid}",
      client_secret: "{clientsecret}",
      resource: "https://graph.microsoft.com",
      grant_type: "client_credentials"
    };


问:
Shell command to get remote system's ip address from its mac address?
I have the HWAddress of remote machine but its IP address is not static and keeps changing. How do I get its IP address through shell?

Relevant questions mostly have the remote system in the same network, but in my case its not.

EDIT: I know its IP range.

答:
Follow these steps:

Show the network interface names actives:

```<code>LIST_NET_IFACE=$(ip addr show | awk '/inet.*brd/{print $NF}')
echo "${LIST_NET_IFACE}"
</code>```

Get the network interface used to the connection out. If it is the first in the above list, get with this command:

```<code>NET_IFACE=$(ip addr show | awk '/inet.*brd/{print $NF; exit}')
echo "${NET_IFACE}"
</code>```

If necessary, get the network IP with its network mask:

```<code>NET_MASK=$(ip -o -4 addr list "${NET_IFACE}" | awk '{print $4}')
echo "${NET_MASK}"
</code>```

If necessary, separate the IP:

```<code>NET_IP=$(echo ${NET_MASK} | cut -d/ -f1)
echo "${NET_IP}"
</code>```

Finally, discovery and list the hardwares mac addresses at this network:

```<code>arp -n -i "${NET_IFACE}" | grep -v "incomplete"
</code>```

To get a IP from a specifc hardware mac address stored in var REMOTE_MACADDRESS (with content in lower case):

```<code>REMOTE_IP=$( arp -n -i "${NET_IFACE}" | grep -v "incomplete" | grep "${REMOTE_MACADDRESS}" | awk '{print $1}' )
</code>```

Body:
Follow these steps:

Show the network interface names actives:

LIST_NET_IFACE=$(ip addr show | awk '/inet.*brd/{print $NF}')
echo "${LIST_NET_IFACE}"

Get the network interface used to the connection out. If it is the first in the above list, get with this command:

NET_IFACE=$(ip addr show | awk '/inet.*brd/{print $NF; exit}')
echo "${NET_IFACE}"

If necessary, get the network IP with its network mask:

NET_MASK=$(ip -o -4 addr list "${NET_IFACE}" | awk '{print $4}')
echo "${NET_MASK}"

If necessary, separate the IP:

NET_IP=$(echo ${NET_MASK} | cut -d/ -f1)
echo "${NET_IP}"

Finally, discovery and list the hardwares mac addresses at this network:

arp -n -i "${NET_IFACE}" | grep -v "incomplete"

To get a IP from a specifc hardware mac address stored in var REMOTE_MACADDRESS (with content in lower case):

REMOTE_IP=$( arp -n -i "${NET_IFACE}" | grep -v "incomplete" | grep "${REMOTE_MACADDRESS}" | awk '{print $1}' )


问:
javax.inject.Provider vs String
I am trying to retrieve a set of JNDI keys in a webapp during the runtime.
The code looks like:

```<code>class Test{
    private final String someUrl;

    public Test(@Named("URL") String someUrl){
    // do something
    }

     public void dotEST( string someUrl){
      String x = someUrl;
      //some other logic
     }

}
</code>```

I want to understand the difference between using the above code and this:

```<code>class Test{
    private final Provider<String> someUrl;

    public Test(@Named("URL") Provider<String> someUrl){
    // do something
    }

     public void dotEST( Provider<String> someUrl){
      String x = someUrl.get();
      //some other logic
     }
}
</code>```

When and why should I use provider?

答:
I would use a provider if the value is complex or expensive to calculate. Maybe you would Provide a connection to the database, or fetching of some remote configuration values.

KISS - Keep it simple, stupid, is key when working with injection frameworks. The more you can rely on simple things (like types), the better. It can quickly grow into a mess that is hard to get out of.

Even @Named(...) is complex, so I would avoid that too if possible. It will probably be easier (not simpler??) long term to have a placeholder class for that string value.

```<code>class UrlToTheServer {
    private final String url;
}

...

class Test{
    private final String someUrl;

    @Inject
    public Test(UrlToTheServer urlToTheServer){
        someUrl = urlToTheServer.url;
    }

    public void foo() {
       // access someUrl here.
    }
 }
</code>```

}

Title: javax.inject.Provider vs String

Body:
I am trying to retrieve a set of JNDI keys in a webapp during the runtime.
The code looks like:

class Test{
    private final String someUrl;

    public Test(@Named("URL") String someUrl){
    // do something
    }

     public void dotEST( string someUrl){
      String x = someUrl;
      //some other logic
     }

}

I want to understand the difference between using the above code and this:

class Test{
    private final Provider<String> someUrl;

    public Test(@Named("URL") Provider<String> someUrl){
    // do something
    }

     public void dotEST( Provider<String> someUrl){
      String x = someUrl.get();
      //some other logic
     }
}

When and why should I use provider?

Body:
I would use a provider if the value is complex or expensive to calculate. Maybe you would Provide a connection to the database, or fetching of some remote configuration values.

KISS - Keep it simple, stupid, is key when working with injection frameworks. The more you can rely on simple things (like types), the better. It can quickly grow into a mess that is hard to get out of.

Even @Named(...) is complex, so I would avoid that too if possible. It will probably be easier (not simpler??) long term to have a placeholder class for that string value.

class UrlToTheServer {
    private final String url;
}

...

class Test{
    private final String someUrl;

    @Inject
    public Test(UrlToTheServer urlToTheServer){
        someUrl = urlToTheServer.url;
    }

    public void foo() {
       // access someUrl here.
    }
 }

}


问:
Filter specifik patern in a complex file
I have this logfile and im trying to avoid printing the text containing patern" APLHA".

```<code>   +++ skdfhahjsahsdjk >
** ALPHA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
* KJENRFKES DFJKLSDFJEDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
CL mesukww juwaehdiearfa
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
*C KJENRFKESDFJ ksludhieokdaewmdp
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

 +++ skdfhahjsahsdjk >
** BETA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-
</code>```

I tried via this way but not successful.It prints the rest of the text, except "ALPHA"

cat logfile |grep -v "ALPHA"

result:

```<code>+++ skdfhahjsahsdjk >
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-
</code>```

What i expect is the whole log containing "ALPHA" is not printed, like hereunder:

```<code> +++ skdfhahjsahsdjk >
* KJENRFKES DFJKLSDFJEDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
CL mesukww juwaehdiearfa
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
*C KJENRFKESDFJ ksludhieokdaewmdp
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

 +++ skdfhahjsahsdjk >
** BETA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-
</code>```

Can you please advise on any other solution to this case?

Regards Dom

答:
Alternate solution using perl's slurp mode(-00 to enable). This will tell perl to consider paragraphs are one record not the lines. Later is clear, print only if ALPHA is not present.

```<code>perl -00 -ne  'print if  !/ALPHA/' inputfile
   +++ skdfhahjsahsdjk >
* KJENRFKES DFJKLSDFJEDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
CL mesukww juwaehdiearfa
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
*C KJENRFKESDFJ ksludhieokdaewmdp
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

 +++ skdfhahjsahsdjk >
** BETA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-
</code>```

Body:
I have this logfile and im trying to avoid printing the text containing patern" APLHA".

   +++ skdfhahjsahsdjk >
** ALPHA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
* KJENRFKES DFJKLSDFJEDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
CL mesukww juwaehdiearfa
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
*C KJENRFKESDFJ ksludhieokdaewmdp
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

 +++ skdfhahjsahsdjk >
** BETA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

I tried via this way but not successful.It prints the rest of the text, except "ALPHA"

cat logfile |grep -v "ALPHA"

result:

+++ skdfhahjsahsdjk >
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

What i expect is the whole log containing "ALPHA" is not printed, like hereunder:

 +++ skdfhahjsahsdjk >
* KJENRFKES DFJKLSDFJEDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
CL mesukww juwaehdiearfa
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
*C KJENRFKESDFJ ksludhieokdaewmdp
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

 +++ skdfhahjsahsdjk >
** BETA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

Can you please advise on any other solution to this case?

Regards Dom

Body:
Alternate solution using perl's slurp mode(-00 to enable). This will tell perl to consider paragraphs are one record not the lines. Later is clear, print only if ALPHA is not present.

perl -00 -ne  'print if  !/ALPHA/' inputfile
   +++ skdfhahjsahsdjk >
* KJENRFKES DFJKLSDFJEDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
CL mesukww juwaehdiearfa
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
*C KJENRFKESDFJ ksludhieokdaewmdp
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

 +++ skdfhahjsahsdjk >
** BETA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-


问:
return same product with multiple id
Right now I'm returning a product by passing a code over url

```<code>class Product(APIView):
    def get_product(self, code):
        try:
            prod = ProductModel.objects.get(code=code)
            return prod
        except Product.DoesNotExist:
            raise Http404

    def get(self, request, code, format=None):
        product = self.get_product(code)
        serializer = ProductSerializer(product)
        return Response(serializer.data)
</code>```

url

```<code>path('product/<code>/', views.Product.as_view()),
</code>```

model:

```<code>class Product(models.Model):
    code = JSONField(default=dict, null=True, blank=True)
    description = models.TextField(blank=True, null=True, default='')
    category = models.TextField(blank=True, null=True, default='')
    marketing_text = models.TextField(blank=True, null=True, default='')
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
</code>```

this will return product if it's in the database, simple stuff but now I've added a JSON field in the ProductModel with multiple codes ["05017303032619", "05017303032626"], so I want to check do I have this codes and still return the item, basically return the same item by passing one of this codes over url.

答:
You can use an ArrayField instead of a JSONField for that.

models.py

from django.contrib.postgres.fields import ArrayField

class Product(models.Model):
    code = ArrayField(models.CharField(max_length=200), blank=True)
    ...
```

<p><strong>views.py</strong></p>

<pre class="lang-py prettyprint-override"><code>class Product(APIView):
    def get_product(self, code):
        try:
            return ProductModel.objects.filter(code__contains=code).first()
        except Product.DoesNotExist:
            raise Http404

    def get(self, request, code, format=None):
        product = self.get_product(code)
        serializer = ProductSerializer(product)
        return Response(serializer.data)
</code>```

Title: return same product with multiple id

Body:
Right now I'm returning a product by passing a code over url

class Product(APIView):
    def get_product(self, code):
        try:
            prod = ProductModel.objects.get(code=code)
            return prod
        except Product.DoesNotExist:
            raise Http404

    def get(self, request, code, format=None):
        product = self.get_product(code)
        serializer = ProductSerializer(product)
        return Response(serializer.data)

url

path('product//', views.Product.as_view()),

model:

class Product(models.Model):
    code = JSONField(default=dict, null=True, blank=True)
    description = models.TextField(blank=True, null=True, default='')
    category = models.TextField(blank=True, null=True, default='')
    marketing_text = models.TextField(blank=True, null=True, default='')
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

this will return product if it's in the database, simple stuff but now I've added a JSON field in the ProductModel with multiple codes ["05017303032619", "05017303032626"], so I want to check do I have this codes and still return the item, basically return the same item by passing one of this codes over url.

Body:
You can use an ArrayField instead of a JSONField for that.

models.py

from django.contrib.postgres.fields import ArrayField

class Product(models.Model):
    code = ArrayField(models.CharField(max_length=200), blank=True)
    ...

views.py

class Product(APIView):
    def get_product(self, code):
        try:
            return ProductModel.objects.filter(code__contains=code).first()
        except Product.DoesNotExist:
            raise Http404

    def get(self, request, code, format=None):
        product = self.get_product(code)
        serializer = ProductSerializer(product)
        return Response(serializer.data)


问:
Socket emitting event multiple times
I am working on socket for chatting. Here is my socket code in nodejs file which is working well.

The outer socket io.emit working good and emits the message to all the users which are connected to that conversationId.

But the socket.broadcast.emit(when user uses the app) which I am using to notify user, emits(socket.broadcast.emit) events multiple times. Why this is happening? Am I completely missing the socket approach.

```<code>socket.on('sendMessage', async(action2) => {
  try {
    action2.author = socket.decoded.id
    action2.readBy = [socket.decoded.id]
    action2.deliveredTo = [socket.decoded.id]
    const createMessage = await Message.create(action2)

    const sender = await User.findOne({ _id: socket.decoded.id }, { firstName: 1 })

    const memebers = //some api call to get members
    const promises = members.map(async(member) => {
      // socket for message
      const socketNotification = {
        // my object
      }
      console.log(socketNotification, 'socketNotifcication')
      socket.broadcast.emit(`messageSocket${member.memberId}`, socketNotification)
    })
    await Promise.all(promises)
    io.emit(action2.conversationId, messages) // "newMessage"
  } catch (err) {
    throw err
  }
})
</code>```

答:
From the Broadcast docs:

Sets a modifier for a subsequent event emission that the event data
  will only be broadcast to every sockets but the sender.

https://socket.io/docs/server-api/#Flag-%E2%80%98broadcast%E2%80%99

So in your loop you are saying send this everyone but the original socket, and you call that multiple times. What you want to use it it.to

```<code>io.to(membersSocketID).emit('eventName', socketNotification)
</code>```

It's unclear from your example if the messageSocket${member.memberId} is supposed to be the event name of if that is your specified socket.id.

This is a great cheatsheet for this https://socket.io/docs/emit-cheatsheet/

Side note, if your api call to get the member id's is significant you might be better off using rooms/namespaces and doing that query on connect to determine rooms.

Title: Socket emitting event multiple times

Body:
I am working on socket for chatting. Here is my socket code in nodejs file which is working well.

The outer socket io.emit working good and emits the message to all the users which are connected to that conversationId.

But the socket.broadcast.emit(when user uses the app) which I am using to notify user, emits(socket.broadcast.emit) events multiple times. Why this is happening? Am I completely missing the socket approach.

socket.on('sendMessage', async(action2) => {
  try {
    action2.author = socket.decoded.id
    action2.readBy = [socket.decoded.id]
    action2.deliveredTo = [socket.decoded.id]
    const createMessage = await Message.create(action2)

    const sender = await User.findOne({ _id: socket.decoded.id }, { firstName: 1 })

    const memebers = //some api call to get members
    const promises = members.map(async(member) => {
      // socket for message
      const socketNotification = {
        // my object
      }
      console.log(socketNotification, 'socketNotifcication')
      socket.broadcast.emit(`messageSocket${member.memberId}`, socketNotification)
    })
    await Promise.all(promises)
    io.emit(action2.conversationId, messages) // "newMessage"
  } catch (err) {
    throw err
  }
})

Body:
From the Broadcast docs:

Sets a modifier for a subsequent event emission that the event data
  will only be broadcast to every sockets but the sender.

https://socket.io/docs/server-api/#Flag-%E2%80%98broadcast%E2%80%99

So in your loop you are saying send this everyone but the original socket, and you call that multiple times. What you want to use it it.to

io.to(membersSocketID).emit('eventName', socketNotification)

It's unclear from your example if the messageSocket${member.memberId} is supposed to be the event name of if that is your specified socket.id.

This is a great cheatsheet for this https://socket.io/docs/emit-cheatsheet/

Side note, if your api call to get the member id's is significant you might be better off using rooms/namespaces and doing that query on connect to determine rooms.


问:
App Icons from MakeAppIcon didn't successfully appear
I went to MakeAppIcon and made them. Posted over there and deleted an icon called "App-Icon-76x76@2x.png". But when I launched on my iPad, the icon didn't appear. By the way, the other app is successfully appearing icon so I think this is not the iPad problem.

答:
The icon 76x76@2x is used for Retina display on iPads, so if you delete it, you'll not see the icon.
So you need to create one from your original that makes 152px x 152px, it will normally avoid the yellow error.</p>


问:
Print variable names when looping over a list
Consider the list of variables and a Python list:

```<code>apple='green'
banana='yellow'
orange='orange'

fruits = [apple, banana, orange]
</code>```

How to print the names of variables, instead of its values when lopping over the elements of the list?

```<code>for fruit in fruits:
    #print the names of variables, that is "apple", "banana", etc.
</code>```

I know that a dictionary would be a better fit in this problem but for the sake of argument, is it possible to do it with a list?

答:
It is a bit of a cheat, but if you store the names of the variables in the fruits array instead of the variable itself, it is trivial:

```<code>>>> apple = 'green'
>>> banana = 'yellow'
>>> orange = 'orange'
>>> fruits = ['apple','banana','orange']
>>> for fruit in fruits:
...     print fruit, vars()[fruit]
...
apple green
banana yellow
orange orange
</code>```

If you are really wanting to get the variable name, you have a problem as the array is not storing the variable, but the string it is pointing at - for example, you can change the content of apple after the assignment to demonstrate the array holds the original string:

```<code>>>> fruity = [ apple, orange, banana ]
>>> apple = 'yikes'
>>> print fruity
['green', 'orange', 'yellow']
</code>```

The best you can do is build a reverse lookup of the vars() dictionary and attempt to look up the variable...

```<code>>>> yy = dict([v,k] for k,v in vars().items() if isinstance(v,str))
>>> for fruit in fruity:
...     print yy.get(fruit,'Unknown'), fruit
...
Unknown green
orange orange
banana yellow
</code>```

Body:
Consider the list of variables and a Python list:

apple='green'
banana='yellow'
orange='orange'

fruits = [apple, banana, orange]

How to print the names of variables, instead of its values when lopping over the elements of the list?

for fruit in fruits:
    #print the names of variables, that is "apple", "banana", etc.

I know that a dictionary would be a better fit in this problem but for the sake of argument, is it possible to do it with a list?

Body:
It is a bit of a cheat, but if you store the names of the variables in the fruits array instead of the variable itself, it is trivial:

>>> apple = 'green'
>>> banana = 'yellow'
>>> orange = 'orange'
>>> fruits = ['apple','banana','orange']
>>> for fruit in fruits:
...     print fruit, vars()[fruit]
...
apple green
banana yellow
orange orange

If you are really wanting to get the variable name, you have a problem as the array is not storing the variable, but the string it is pointing at - for example, you can change the content of apple after the assignment to demonstrate the array holds the original string:

>>> fruity = [ apple, orange, banana ]
>>> apple = 'yikes'
>>> print fruity
['green', 'orange', 'yellow']

The best you can do is build a reverse lookup of the vars() dictionary and attempt to look up the variable...

>>> yy = dict([v,k] for k,v in vars().items() if isinstance(v,str))
>>> for fruit in fruity:
...     print yy.get(fruit,'Unknown'), fruit
...
Unknown green
orange orange
banana yellow


问:
Ruby EBCDIC conversion with String#encode instead of iconv
I used to do it fine with:

```<code>Iconv.iconv('ASCII', 'EBCDIC-US', someEBCDICstring)
</code>```

since ruby 1.9 I get that warning:

```<code>iconv will be deprecated in the future, use String#encode instead.
</code>```

but I can't find any reference of EBCDIC or cp37, cp500, cp875... in the Encoding class:

```<code>p Encoding.name_list
</code>```

Am I supposed to import it from somewhere? Can I add it myself?

答:
In Ruby 2.3 the EBCDIC-encoding is added:

Encoding

new Encoding::IBM037 (alias ebcdic-cp-us; dummy)

So this should work:

```<code>str = 'xx'
str.encode('IBM037')
</code>```

Body:
I used to do it fine with:

Iconv.iconv('ASCII', 'EBCDIC-US', someEBCDICstring)

since ruby 1.9 I get that warning:

iconv will be deprecated in the future, use String#encode instead.

but I can't find any reference of EBCDIC or cp37, cp500, cp875... in the Encoding class:

p Encoding.name_list

Am I supposed to import it from somewhere? Can I add it myself?

Body:
In Ruby 2.3 the EBCDIC-encoding is added:

Encoding

new Encoding::IBM037 (alias ebcdic-cp-us; dummy)

So this should work:

str = 'xx'
str.encode('IBM037')


问:
Exclude file from "git diff"
I am trying to exclude a file (db/irrelevant.php) from a Git diff. I have tried putting a file in the db subdirectory called .gitattributes with the line irrelevant.php -diff
and I have also tried creating a file called .git/info/attributes containing db/irrelevant.php.

In all cases, the db/irrelevant.php file is included in the diff as a Git binary patch. What I want is for the changes to that file to be ignore by the diff command. What am I doing wrong?

答:
I do the following:

```<code>git add *pattern_to_exclude*
git diff
git reset HEAD .
</code>```

I know it's not an elegant solution and it sometimes canot be used (eg. if you already have stuff staged) , but it does the trick without having to type a complicated command

Title: Exclude file from "git diff"

Body:
I do the following:

git add *pattern_to_exclude*
git diff
git reset HEAD .

I know it's not an elegant solution and it sometimes canot be used (eg. if you already have stuff staged) , but it does the trick without having to type a complicated command


问:
Show each row colums information php and sql
I want to print the values of custom columns for all rows, I've got a sql developer file, i mean that i want to print some columns of every rows, if for example my table is named client and has name, subname and email i want to print every client name, subname and email I've found how to make it with mysql but I want to make it with php and sql developer.

The code I've shown only shows the first user name and not the rest names and other columns of other users.

```<code><?php
function clientes($conexion) {
    $consulta = "SELECT NOMBRE FROM CLIENTE";
    $stmt = $conexion -> prepare($consulta);
    $stmt -> execute();
    return $stmt -> fetchColumn();
}

echo clientes($conexion);
?>
</code>```

答:
I want to print every client name, subname and email i've found

Then you should use fetchall() this will fetch all the results as an array then iterate through the array and print each element of the array

```<code>function clientes($conexion) {
    $stmt = $conexion ->query("SELECT name,subname,email FROM CLIENTE")->fetchall();

  foreach($stmt as $row){

    echo "Client Name : ".$row['name']."<br>";
    echo "Client subname : ".$row['subname']."<br>";
    echo "Client email : ".$row['email']."<br>";
  }
}

clientes($conexion);
?>
</code>```

Body:
I want to print the values of custom columns for all rows, I've got a sql developer file, i mean that i want to print some columns of every rows, if for example my table is named client and has name, subname and email i want to print every client name, subname and email I've found how to make it with mysql but I want to make it with php and sql developer.

The code I've shown only shows the first user name and not the rest names and other columns of other users.

<?php
function clientes($conexion) {
    $consulta = "SELECT NOMBRE FROM CLIENTE";
    $stmt = $conexion -> prepare($consulta);
    $stmt -> execute();
    return $stmt -> fetchColumn();
}

echo clientes($conexion);
?>

Body:
I want to print every client name, subname and email i've found

Then you should use fetchall() this will fetch all the results as an array then iterate through the array and print each element of the array

function clientes($conexion) {
    $stmt = $conexion ->query("SELECT name,subname,email FROM CLIENTE")->fetchall();

  foreach($stmt as $row){

    echo "Client Name : ".$row['name']."<br>";
    echo "Client subname : ".$row['subname']."<br>";
    echo "Client email : ".$row['email']."<br>";
  }
}

clientes($conexion);
?>


问:
Converting row to columns in mysql
My table is coming from the output of a stored procedure. It looks like :

```<code>col1
A
B
C
D
</code>```

It can have less than or equal to 5 rows.

I want it to look like this

```<code>Column1  Column2 Column3  Column4  column5
A          B      C         D       NULL
</code>```

Is there a way to achieve this in MYSQL?

答:
In MySQL 8+, there is a fairly easy way to do this using ROW_NUMBER along with a pivot query:

```<code>WITH cte AS (
    SELECT col1, ROW_NUMBER() OVER (ORDER BY col1) rn
    FROM yourTable
)

SELECT
    MAX(CASE WHEN rn = 1 THEN col1 END) AS Column1,
    MAX(CASE WHEN rn = 2 THEN col1 END) AS Column2,
    MAX(CASE WHEN rn = 3 THEN col1 END) AS Column3,
    MAX(CASE WHEN rn = 4 THEN col1 END) AS Column4,
    MAX(CASE WHEN rn = 5 THEN col1 END) AS Column5
FROM cte;
</code>```

Title: Converting row to columns in mysql

Body:
My table is coming from the output of a stored procedure. It looks like :

col1
A
B
C
D

It can have less than or equal to 5 rows.

I want it to look like this

Column1  Column2 Column3  Column4  column5
A          B      C         D       NULL

Is there a way to achieve this in MYSQL?

Body:
In MySQL 8+, there is a fairly easy way to do this using ROW_NUMBER along with a pivot query:

WITH cte AS (
    SELECT col1, ROW_NUMBER() OVER (ORDER BY col1) rn
    FROM yourTable
)

SELECT
    MAX(CASE WHEN rn = 1 THEN col1 END) AS Column1,
    MAX(CASE WHEN rn = 2 THEN col1 END) AS Column2,
    MAX(CASE WHEN rn = 3 THEN col1 END) AS Column3,
    MAX(CASE WHEN rn = 4 THEN col1 END) AS Column4,
    MAX(CASE WHEN rn = 5 THEN col1 END) AS Column5
FROM cte;


问:
Disable tag background color
When I double click a word in a html tag (editing an aspx file), I get a double background highlighting.

I have selected the word decSearchStartTime, but I also get the tag keyword button selected as well as attributes.

How do I only have the selected word highlit?

答: If you go to the Tools menu and select "Options" Then under "Environment" -> "Fonts and Colors" it's under "Brace Matching (Rectangle)" in the Display Items list for the Text Editor. Technically you can't turn it "off" but you can have the Item Background color set to the same as your editor's background color which does effectively the same thing.

Title: Disable tag background color


问:
How to place C compilation output files (Linux kernel modules) in a different directory from the source files's (using Makefile)
I have looked at these and at these other solutions but cannot write the correct Makefile to produce my wanted result.

So, I have this simple.c file. It simulates linux kernel module loading and removing. Location: /path/to/dir/simple.c

```<code>#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

/* This function is called when the module is loaded. */
int simple_init(void)
{
       printk(KERN_INFO "Loading Module\n");

       return 0;
}

/* This function is called when the module is removed. */
void simple_exit(void) {
    printk(KERN_INFO "Removing Module\n");
}

/* Macros for registering module entry and exit points. */
module_init( simple_init );
module_exit( simple_exit );

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple Module");
MODULE_AUTHOR("SGG");
</code>```

I also have this Makefile in the same directory as simple.c, location:/path/to/dir/Makefile.

```<code>obj-m += simple.o
all:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
</code>```

When on a terminal I run:

```<code>cd path/to/dir/
make
</code>```

everything is compiled correctly (in the same directory path/to/dir/.

What I want is this:

Location of simple.c in /path/to/dir/src/.

Location of Makefile in /path/to/dir/.

Location of the outputs in/path/to/dir/bin/ or/and /path/to/dir/obj/.

When make is run, the outputs should end in the bin, obj directories.

There are some complications in the Makefile (/lib/modules/$(shell uname -r)/build) which I don't quite understand. All the various changes to the Makefile in order to reach the desired result, ended without success in errors.

How do I do it?

Edit:

The Makefile in /lib/modules/$(shell uname -r)/build has the following code:

```<code>VERSION = 4
PATCHLEVEL = 4
SUBLEVEL = 162
EXTRAVERSION =
NAME = Blurry Fish Butt

# *DOCUMENTATION*
# To see a list of typical targets execute "make help"
# More info can be located in ./README
# Comments in this file are targeted only to the developer, do not
# expect to learn how to build the kernel reading this file.

# o Do not use make's built-in rules and variables
#   (this increases performance and avoids hard-to-debug behaviour);
# o Look for make include files relative to root of kernel src
MAKEFLAGS += -rR --include-dir=$(CURDIR)

# Avoid funny character set dependencies
unexport LC_ALL
LC_COLLATE=C
LC_NUMERIC=C
export LC_COLLATE LC_NUMERIC

# Avoid interference with shell env settings
unexport GREP_OPTIONS

# We are using a recursive build, so we need to do a little thinking
# to get the ordering right.
#
# Most importantly: sub-Makefiles should only ever modify files in
# their own directory. If in some directory we have a dependency on
# a file in another dir (which doesn't happen often, but it's often
# unavoidable when linking the built-in.o targets which finally
# turn into vmlinux), we will call a sub make in that other dir, and
# after that we are sure that everything which is in that other dir
# is now up to date.
#
# The only cases where we need to modify files which have global
# effects are thus separated out and done before the recursive
# descending is started. They are now explicitly listed as the
# prepare rule.

# Beautify output
# ---------------------------------------------------------------------------
#
# Normally, we echo the whole command before executing it. By making
"/lib/modules/4.4.0-141-generic/build/Makefile" [readonly] 1650L, 57062C
</code>```

答:
I don't know if i have understood the question. First of all I recommend you to locate the source code in the SRC folder. After that, choose the dir where you want to create the Makefile.

The next step is to define the set of codes that you are going to need to link your program. Do not forget the path to the SRC folder.

Now it's time to create the object files. In this step, choose the option -o [path_obj]/[file_name].o.

The last step consist in to link the program, do not forget that the objects are in the [path_obj] folder.

A simple example could be:

```<code>#path definitions

SRC_path = /path_to_src/
OBJ_path = /path_to_obj/
BIN_path = /path_to_bin/

#lists definitions
SRC = [file1].c [file2].c
OBJ = $(addsuffix .o, $(basename ${SRC}))

#Suffixes definitions
.suffixes:
.suffixes: .c .o

#Create objects
.c.o:   gcc -I[include_files] -c $(SRC_path)$< -o $(OBJ_path)$@

#Link program
TAG:    gcc  $(addprefix $(OBJ_path), $(OBJ)) -o $(BIN_path)[program_name]
</code>```

I hope you find it useful

Body:
I have looked at these and at these other solutions but cannot write the correct Makefile to produce my wanted result.

So, I have this simple.c file. It simulates linux kernel module loading and removing. Location: /path/to/dir/simple.c

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

/* This function is called when the module is loaded. */
int simple_init(void)
{
       printk(KERN_INFO "Loading Module\n");

       return 0;
}

/* This function is called when the module is removed. */
void simple_exit(void) {
    printk(KERN_INFO "Removing Module\n");
}

/* Macros for registering module entry and exit points. */
module_init( simple_init );
module_exit( simple_exit );

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple Module");
MODULE_AUTHOR("SGG");

I also have this Makefile in the same directory as simple.c, location:/path/to/dir/Makefile.

obj-m += simple.o
all:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

When on a terminal I run:

cd path/to/dir/
make

everything is compiled correctly (in the same directory path/to/dir/.

What I want is this:

Location of simple.c in /path/to/dir/src/.

Location of Makefile in /path/to/dir/.

Location of the outputs in/path/to/dir/bin/ or/and /path/to/dir/obj/.

When make is run, the outputs should end in the bin, obj directories.

There are some complications in the Makefile (/lib/modules/$(shell uname -r)/build) which I don't quite understand. All the various changes to the Makefile in order to reach the desired result, ended without success in errors.

How do I do it?

Edit:

The Makefile in /lib/modules/$(shell uname -r)/build has the following code:

VERSION = 4
PATCHLEVEL = 4
SUBLEVEL = 162
EXTRAVERSION =
NAME = Blurry Fish Butt

# *DOCUMENTATION*
# To see a list of typical targets execute "make help"
# More info can be located in ./README
# Comments in this file are targeted only to the developer, do not
# expect to learn how to build the kernel reading this file.

# o Do not use make's built-in rules and variables
#   (this increases performance and avoids hard-to-debug behaviour);
# o Look for make include files relative to root of kernel src
MAKEFLAGS += -rR --include-dir=$(CURDIR)

# Avoid funny character set dependencies
unexport LC_ALL
LC_COLLATE=C
LC_NUMERIC=C
export LC_COLLATE LC_NUMERIC

# Avoid interference with shell env settings
unexport GREP_OPTIONS

# We are using a recursive build, so we need to do a little thinking
# to get the ordering right.
#
# Most importantly: sub-Makefiles should only ever modify files in
# their own directory. If in some directory we have a dependency on
# a file in another dir (which doesn't happen often, but it's often
# unavoidable when linking the built-in.o targets which finally
# turn into vmlinux), we will call a sub make in that other dir, and
# after that we are sure that everything which is in that other dir
# is now up to date.
#
# The only cases where we need to modify files which have global
# effects are thus separated out and done before the recursive
# descending is started. They are now explicitly listed as the
# prepare rule.

# Beautify output
# ---------------------------------------------------------------------------
#
# Normally, we echo the whole command before executing it. By making
"/lib/modules/4.4.0-141-generic/build/Makefile" [readonly] 1650L, 57062C

Body:
I don't know if i have understood the question. First of all I recommend you to locate the source code in the SRC folder. After that, choose the dir where you want to create the Makefile.

The next step is to define the set of codes that you are going to need to link your program. Do not forget the path to the SRC folder.

Now it's time to create the object files. In this step, choose the option -o [path_obj]/[file_name].o.

The last step consist in to link the program, do not forget that the objects are in the [path_obj] folder.

A simple example could be:

#path definitions

SRC_path = /path_to_src/
OBJ_path = /path_to_obj/
BIN_path = /path_to_bin/

#lists definitions
SRC = [file1].c [file2].c
OBJ = $(addsuffix .o, $(basename ${SRC}))

#Suffixes definitions
.suffixes:
.suffixes: .c .o

#Create objects
.c.o:   gcc -I[include_files] -c $(SRC_path)$< -o $(OBJ_path)$@

#Link program
TAG:    gcc  $(addprefix $(OBJ_path), $(OBJ)) -o $(BIN_path)[program_name]

I hope you find it useful


问:
Can I use the Dropbox API to Download Files from a regular link?
I would like to download files from a link a received to Dropbox. I created an API token, but I'm not sure the type of link I received is sufficient.

Using these docs, I tried retrieving the file but am receiving the following error:

```<code>ApiError: ApiError('', GetSharedLinkFileError('shared_link_access_denied', None))
</code>```

Here's my code:

```<code>import dropbox
dbx = dropbox.Dropbox("{ACCESS TOKEN}")
dbx.users_get_current_account()

download_path = '{LOCAL PATH}'
url = 'https://www.dropbox.com/sh/{DROPBOX FOLDER}?dl=0'
dbx.sharing_get_shared_link_file_to_file(download_path, url, path=None, link_password=None)
</code>```

I tried replacing the sh with s based on this, no success.

Do I have the link I need? Is it something in the code?
Thanks in advance!

答:
Dropbox shared links with "/sh" refer to folders. These links are valid for use with sharing_get_shared_link_file_to_file, but since they refer to folders and not individual files, you do need to specify the path parameter to indicate which file in the linked folder you want.

Here's a working example:

```<code>import dropbox

dbx = dropbox.Dropbox("{ACCESS TOKEN}")

file_path = '/dahlia_l.jpg'
download_path = 'download.jpg'
url = 'https://www.dropbox.com/sh/ljrkl8kbddx8n1c/AAACNrUwqPSVv27oh97QhN0Za?dl=0'
res = dbx.sharing_get_shared_link_file_to_file(download_path, url, path=file_path)

print(res)
</code>```

Body:
I would like to download files from a link a received to Dropbox. I created an API token, but I'm not sure the type of link I received is sufficient.

Using these docs, I tried retrieving the file but am receiving the following error:

ApiError: ApiError('', GetSharedLinkFileError('shared_link_access_denied', None))

Here's my code:

import dropbox
dbx = dropbox.Dropbox("{ACCESS TOKEN}")
dbx.users_get_current_account()

download_path = '{LOCAL PATH}'
url = 'https://www.dropbox.com/sh/{DROPBOX FOLDER}?dl=0'
dbx.sharing_get_shared_link_file_to_file(download_path, url, path=None, link_password=None)

I tried replacing the sh with s based on this, no success.

Do I have the link I need? Is it something in the code?
Thanks in advance!

Body:
Dropbox shared links with "/sh" refer to folders. These links are valid for use with sharing_get_shared_link_file_to_file, but since they refer to folders and not individual files, you do need to specify the path parameter to indicate which file in the linked folder you want.

Here's a working example:

import dropbox

dbx = dropbox.Dropbox("{ACCESS TOKEN}")

file_path = '/dahlia_l.jpg'
download_path = 'download.jpg'
url = 'https://www.dropbox.com/sh/ljrkl8kbddx8n1c/AAACNrUwqPSVv27oh97QhN0Za?dl=0'
res = dbx.sharing_get_shared_link_file_to_file(download_path, url, path=file_path)

print(res)


问:
How to plot two lines in the same graph if the number of observations is uneqal?
I have two dataframes each containing a "Date" and a "Price" column.
I now want to produce a graph with two plots in it based on the observations of this two dataframes. The problem I have is that the dates are not equal. My data looks like this:

```<code>Date1 <- seq.Date(from = as.Date("2015-08-07"), to = as.Date("2015-08-16"), by = "days")
Price1 <- c(2.5,6.3,1.2,2.4,4.2,5.1,7.3,9.2,12.5,8.7)
df1 <- data.frame(Date1, Price1)

Date2 <- seq.Date(from=as.Date("2015-08-11"), to = as.Date ("2015-08-16"), by = "days")
Price2 <- c(24.3,21.2,18.4,16.2,17.1,15.6)
df2 <- data.frame(Date2, Price2)

df1
#         Date1 Price1
# 1  2015-08-07    2.5
# 2  2015-08-08    6.3
# 3  2015-08-09    1.2
# 4  2015-08-10    2.4
# 5  2015-08-11    4.2
# 6  2015-08-12    5.1
# 7  2015-08-13    7.3
# 8  2015-08-14    9.2
# 9  2015-08-15   12.5
# 10 2015-08-16    8.7

df2
#        Date2 Price2
# 1 2015-08-11   24.3
# 2 2015-08-12   21.2
# 3 2015-08-13   18.4
# 4 2015-08-14   16.2
# 5 2015-08-15   17.1
# 6 2015-08-16   15.6
</code>```

To create the two plots in one graph I use the following code:

```<code>par(mar = c(5, 5, 9, 5))
plot(df1[,1],df1[,2], log = "y", type ="l", col = "orange")
par(new = TRUE)
plot(df2[,2],log = "y", type = "l",col = "blue")
</code>```

What I would like to receive is a graph in which the plot from df1 starts from the beginning and the df2 starts at a later point in time.

Thanks!

答:
You can pass them in one data frame, so that the length of the dates is the same:

```<code>df3 <- merge(df1, df2, by.x = 'Date1', by.y = 'Date2', all.x = TRUE)
</code>```

And then plot, using lines in order to overlay the second line:

```<code>plot(df3$Date1, df3$Price1, type='l', col='blue', ylim = c(0, max(df3$Price2, na.rm = TRUE)))
lines(df3$Date1, df3$Price2, col='red')
</code>```

Make sure you add the limits accordingly because the plot call is the one setting the axes.

Body:
I have two dataframes each containing a "Date" and a "Price" column.
I now want to produce a graph with two plots in it based on the observations of this two dataframes. The problem I have is that the dates are not equal. My data looks like this:

Date1 <- seq.Date(from = as.Date("2015-08-07"), to = as.Date("2015-08-16"), by = "days")
Price1 <- c(2.5,6.3,1.2,2.4,4.2,5.1,7.3,9.2,12.5,8.7)
df1 <- data.frame(Date1, Price1)

Date2 <- seq.Date(from=as.Date("2015-08-11"), to = as.Date ("2015-08-16"), by = "days")
Price2 <- c(24.3,21.2,18.4,16.2,17.1,15.6)
df2 <- data.frame(Date2, Price2)

df1
#         Date1 Price1
# 1  2015-08-07    2.5
# 2  2015-08-08    6.3
# 3  2015-08-09    1.2
# 4  2015-08-10    2.4
# 5  2015-08-11    4.2
# 6  2015-08-12    5.1
# 7  2015-08-13    7.3
# 8  2015-08-14    9.2
# 9  2015-08-15   12.5
# 10 2015-08-16    8.7

df2
#        Date2 Price2
# 1 2015-08-11   24.3
# 2 2015-08-12   21.2
# 3 2015-08-13   18.4
# 4 2015-08-14   16.2
# 5 2015-08-15   17.1
# 6 2015-08-16   15.6

To create the two plots in one graph I use the following code:

par(mar = c(5, 5, 9, 5))
plot(df1[,1],df1[,2], log = "y", type ="l", col = "orange")
par(new = TRUE)
plot(df2[,2],log = "y", type = "l",col = "blue")

What I would like to receive is a graph in which the plot from df1 starts from the beginning and the df2 starts at a later point in time.

Thanks!

Body:
You can pass them in one data frame, so that the length of the dates is the same:

df3 <- merge(df1, df2, by.x = 'Date1', by.y = 'Date2', all.x = TRUE)

And then plot, using lines in order to overlay the second line:

plot(df3$Date1, df3$Price1, type='l', col='blue', ylim = c(0, max(df3$Price2, na.rm = TRUE)))
lines(df3$Date1, df3$Price2, col='red')

Make sure you add the limits accordingly because the plot call is the one setting the axes.


问:
Ant patterns configuration
I have this Spring configuration and OAuth2:

```<code>public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "resource-server-rest-api";
    private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
    private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";
    private static final String SECURED_PATTERN = "/api/**";
    private static final String PUBLIC_PATTERN = "/api/*/public/**";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                    .anonymous()
                .and()
                    .requestMatchers()
                        .antMatchers(SECURED_PATTERN)
                .and().authorizeRequests()
                        .antMatchers(PUBLIC_PATTERN).permitAll()
                        .antMatchers(HttpMethod.POST, SECURED_PATTERN).access(SECURED_WRITE_SCOPE)
                .anyRequest().access(SECURED_READ_SCOPE);
    }
}
</code>```

Now I want to add Swagger to my project. I configured a SwaggerController:

```<code>@Controller //note - this is a spring-boot controller, not @RestController
public class SwaggerController {

    public static final String SWAGGER_URL = "/api/v1/public/swagger/docs";
    public static final String SWAGGER_HTML = "/swagger-ui.html";

    @RequestMapping(SWAGGER_URL)
    public String home() {
        return "redirect:" + SWAGGER_HTML;
    }
}
</code>```

The problem is that I cannot make the "/swagger-ui.html" path not to trigger the Spring Login.
I tried this (note that I added antMatchers for the Swagger html):

```<code>@Override
    public void configure(HttpSecurity http) throws Exception {
        http
                ...
                .and().authorizeRequests()
                        .antMatchers(PUBLIC_PATTERN).permitAll()
                        .antMatchers("/swagger-ui.htm").permitAll()// No authentication
</code>```

...
        }

But it did not work.
How do I need to configure the HttpSecurity?

答:
Add this override:</p>

```<code>@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers(SWAGGER_URL)
            .antMatchers(SWAGGER_HTML);
}
</code>```

Title: Ant patterns configuration

Body:
I have this Spring configuration and OAuth2:

public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "resource-server-rest-api";
    private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
    private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";
    private static final String SECURED_PATTERN = "/api/**";
    private static final String PUBLIC_PATTERN = "/api/*/public/**";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                    .anonymous()
                .and()
                    .requestMatchers()
                        .antMatchers(SECURED_PATTERN)
                .and().authorizeRequests()
                        .antMatchers(PUBLIC_PATTERN).permitAll()
                        .antMatchers(HttpMethod.POST, SECURED_PATTERN).access(SECURED_WRITE_SCOPE)
                .anyRequest().access(SECURED_READ_SCOPE);
    }
}

Now I want to add Swagger to my project. I configured a SwaggerController:

@Controller //note - this is a spring-boot controller, not @RestController
public class SwaggerController {

    public static final String SWAGGER_URL = "/api/v1/public/swagger/docs";
    public static final String SWAGGER_HTML = "/swagger-ui.html";

    @RequestMapping(SWAGGER_URL)
    public String home() {
        return "redirect:" + SWAGGER_HTML;
    }
}

The problem is that I cannot make the "/swagger-ui.html" path not to trigger the Spring Login.
I tried this (note that I added antMatchers for the Swagger html):

@Override
    public void configure(HttpSecurity http) throws Exception {
        http
                ...
                .and().authorizeRequests()
                        .antMatchers(PUBLIC_PATTERN).permitAll()
                        .antMatchers("/swagger-ui.htm").permitAll()// No authentication

...
        }

But it did not work.
How do I need to configure the HttpSecurity?

Body:
Add this override:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers(SWAGGER_URL)
            .antMatchers(SWAGGER_HTML);
}


问:
Defining a maximum running time for a process
I need to stop a process from running longer than n seconds, so here's what I thought I'd do:

```<code>|aProcess|
aProcess := [ 10000 timesRepeat: [Transcript show: 'X'] ] fork.
[(Delay forSeconds: 1) wait. aProcess terminate] fork.
</code>```

I thought this was the proper way to proceed, but it seems to fail from time to time, the Transcript just goes on printing Xes. What bugs me is that it does work sometimes and I can't figure out what the work/fail pattern is.

答:
Both processes are running on the same priority, that's why the second process actually doesn't get chance to interrupt the first one at all. Try to run the first loop in lower priority or even better, second one in higher:</p>

```<code> [(Delay forSeconds: 1) wait. aProcess terminate]
       forkAt: Processor userInterruptPriority
</code>```

Body:
I need to stop a process from running longer than n seconds, so here's what I thought I'd do:

|aProcess|
aProcess := [ 10000 timesRepeat: [Transcript show: 'X'] ] fork.
[(Delay forSeconds: 1) wait. aProcess terminate] fork.

I thought this was the proper way to proceed, but it seems to fail from time to time, the Transcript just goes on printing Xes. What bugs me is that it does work sometimes and I can't figure out what the work/fail pattern is.

Body:
Both processes are running on the same priority, that's why the second process actually doesn't get chance to interrupt the first one at all. Try to run the first loop in lower priority or even better, second one in higher:

 [(Delay forSeconds: 1) wait. aProcess terminate]
       forkAt: Processor userInterruptPriority


答:
It's easier to add to a base graphics plot using lines() rather than par(add=TRUE). And when doing this, you want to make sure the first plot draws the entire range of values so we explicitly set the xlim= andylim= properties.

```<code>plot(df1[,1],df1[,2], log = "y", type ="l", col = "orange",
     xlim=range(df1[,1], df2[,1]),
     ylim=range(df1[,2], df2[,2]))
lines(df2[,1], df2[,2], col = "blue")
</code>```

Title: How to plot two lines in the same graph if the number of observations is uneqal?

Body:
It's easier to add to a base graphics plot using lines() rather than par(add=TRUE). And when doing this, you want to make sure the first plot draws the entire range of values so we explicitly set the xlim= andylim= properties.

plot(df1[,1],df1[,2], log = "y", type ="l", col = "orange",
     xlim=range(df1[,1], df2[,1]),
     ylim=range(df1[,2], df2[,2]))
lines(df2[,1], df2[,2], col = "blue")


问:
Load images in the same order as the files
I am working with Firebase Storage. In a bucket I have several image files and a listfile.txt with the list of all files.
What I need to do is to load the images and put them into an array in the same order as the files are listed in listfile.txt.

I am facing issues, as getDownloadURL() is asynchronous and the images are loaded in a random order into the overlay Array.

```<code>var files=[];
var mapRef=[];
var overlay=[];

var listMapsRef = storageRef.child(prefix+"/listfile.txt");
listMapsRef.getDownloadURL().then(function(url) {
    $.get(url, function(txt){
        files = txt.split("\n");
        for (var i = 0; i < files.length; i++) {
            mapRef.push(storageRef.child(files[i]));
            .....
            .....
        }
        count = mapRef.length;
        mapRef.forEach(function(oneMap) {
                oneMap.getDownloadURL().then(function(url){
                ovl=loadImage(url);
                overlay.push(ovl);
                if (!--count) {
                    startMyApp();
                    }
                });
            });

    }); //.get
});  //.then
</code>```

答:
Do something like this pseudo-code</p>

```<code>function loadImage(url) {
  return new Promsie((resolve, reject) => {
    fetch(url, (data, err) => {
       if (err) reject(err);
       else resolve(data);
    })
  });
}

const overlay = await Promise.all(
    mapRef.map(
        oneMap => oneMap
            .getDownloadURL()
            .then(url => loadImage(url)
    )
);
</code>```

Body:
I am working with Firebase Storage. In a bucket I have several image files and a listfile.txt with the list of all files.
What I need to do is to load the images and put them into an array in the same order as the files are listed in listfile.txt.

I am facing issues, as getDownloadURL() is asynchronous and the images are loaded in a random order into the overlay Array.

var files=[];
var mapRef=[];
var overlay=[];

var listMapsRef = storageRef.child(prefix+"/listfile.txt");
listMapsRef.getDownloadURL().then(function(url) {
    $.get(url, function(txt){
        files = txt.split("\n");
        for (var i = 0; i < files.length; i++) {
            mapRef.push(storageRef.child(files[i]));
            .....
            .....
        }
        count = mapRef.length;
        mapRef.forEach(function(oneMap) {
                oneMap.getDownloadURL().then(function(url){
                ovl=loadImage(url);
                overlay.push(ovl);
                if (!--count) {
                    startMyApp();
                    }
                });
            });

    }); //.get
});  //.then

Body:
Do something like this pseudo-code

function loadImage(url) {
  return new Promsie((resolve, reject) => {
    fetch(url, (data, err) => {
       if (err) reject(err);
       else resolve(data);
    })
  });
}

const overlay = await Promise.all(
    mapRef.map(
        oneMap => oneMap
            .getDownloadURL()
            .then(url => loadImage(url)
    )
);