问:
UIImagePickerController and iCloud photos
After switching to iCloud Photo, it seems that some of the images returned by UIImagePickerController are very blur. It looks like the image are taken from iCloud Photo.

Am I able to retrieve the original image, or filter off iCloud Photo images, or do I have to switch to other frameworks to do what UIImagePickerController do?

答:
From the symptoms, I'm going to assume you are using something like this to load your images:

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            loadImageInMemory(image)
        }
        picker.dismiss(animated: true, completion: nil)
        self.presentingViewController?.dismiss(animated: true, completion: nil)
    }
```
<p>where <code>loadImageInMemory</code> is a function where you process the image.</p>
<p>It turns out that if you use that method, images stored over iCloud may be retrieved in lower quality than the original. A way to verify that this is the case is to change your Photos settings. From the Settings app:</p>
```Settings -> Photos -> Download and Keep Originals
```
<p>This would fix the issue, but of course it's not desirable. If you want to keep using Photos, instead of implementing your own iCloud solution, while keeping the <code>Optimize iPhone Storage</code> setting, you can use PhotoKit to retrieve the original image.</p>
<p>Use this code instead:</p>
<pre class="lang-swift prettyprint-override"><code>import Photos

// ...

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        // it will be loaded asynchronously
        loadImageFromPicker(info: info)
        picker.dismiss(animated: true, completion: nil)
        self.presentingViewController?.dismiss(animated: true, completion: nil)
    }

    private func loadImageFromPicker(info: [UIImagePickerController.InfoKey : Any]) {
        var phAsset: PHAsset?
        if #available(iOS 11.0, *) {
            phAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset
        } else {
            // Fallback on earlier versions
            if let referenceURL = info[UIImagePickerController.InfoKey.referenceURL] as? URL {
                let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
                phAsset = fetchResult.firstObject
            }
        }
        guard let asset = phAsset else {
            return
        }
        // size doesn't matter, because resizeMode = .none
        let size = CGSize(width: 32, height: 32)
        let options = PHImageRequestOptions()
        options.version = .original
        options.deliveryMode = .highQualityFormat
        options.resizeMode = .none
        options.isNetworkAccessAllowed = true
        PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFit, options: options) { [weak self] (image, info) in
            if let s = self, let image = image {
                s.loadImageInMemory(image)
            }
        }
    }
</code>```

This code will work with both local images and iCloud images.

This has fixed a similar problem I experienced working with small PNG images with alpha. See this other post for reference.

Body:
From the symptoms, I'm going to assume you are using something like this to load your images:

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            loadImageInMemory(image)
        }
        picker.dismiss(animated: true, completion: nil)
        self.presentingViewController?.dismiss(animated: true, completion: nil)
    }

where loadImageInMemory is a function where you process the image.

It turns out that if you use that method, images stored over iCloud may be retrieved in lower quality than the original. A way to verify that this is the case is to change your Photos settings. From the Settings app:

Settings -> Photos -> Download and Keep Originals

This would fix the issue, but of course it's not desirable. If you want to keep using Photos, instead of implementing your own iCloud solution, while keeping the Optimize iPhone Storage setting, you can use PhotoKit to retrieve the original image.

Use this code instead:

import Photos

// ...

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        // it will be loaded asynchronously
        loadImageFromPicker(info: info)
        picker.dismiss(animated: true, completion: nil)
        self.presentingViewController?.dismiss(animated: true, completion: nil)
    }

    private func loadImageFromPicker(info: [UIImagePickerController.InfoKey : Any]) {
        var phAsset: PHAsset?
        if #available(iOS 11.0, *) {
            phAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset
        } else {
            // Fallback on earlier versions
            if let referenceURL = info[UIImagePickerController.InfoKey.referenceURL] as? URL {
                let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
                phAsset = fetchResult.firstObject
            }
        }
        guard let asset = phAsset else {
            return
        }
        // size doesn't matter, because resizeMode = .none
        let size = CGSize(width: 32, height: 32)
        let options = PHImageRequestOptions()
        options.version = .original
        options.deliveryMode = .highQualityFormat
        options.resizeMode = .none
        options.isNetworkAccessAllowed = true
        PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFit, options: options) { [weak self] (image, info) in
            if let s = self, let image = image {
                s.loadImageInMemory(image)
            }
        }
    }

This code will work with both local images and iCloud images.

This has fixed a similar problem I experienced working with small PNG images with alpha. See this other post for reference.


来源: stackexchange

问:
I cannot pull branch to my local repository
I want to pull branches to my local repository but I cannot. I tried revert my last commit now all remote branches like that . What is '29e74ac'? Is it can be about references/HEAD ? .  I am using eclipse and trying from team->switch to->other when try to switch branch.

答: When this happens to me and I don't need to keep any of my local changes, I get back to the branch's last commit by running git reset --hard HEAD. This command resets your local repository to the HEAD (latest commit on that branch) but removes all file changes. If you need to keep changes I'd probably suggest stashing your files before that.

ContentLicense: CC BY-SA 4.0


问:
Unable to bind LINQ to gridview
I just using a simple LINQ query having group by clause and trying to bind its result set to GridView.
My LINQ query looks like

```<code>var expData = from c in WebDB.TransTable
              group c by c.enterdate into g
              select g;
</code>```

Grid view on ASP.NET page

```<code><asp:GridView ID="GridView1" AutoGenerateColumns="true" runat="server" DataKeyField="Key" />
</code>```

But getting the error:

A field or property with the name 'Key' was not found on the selected data source.

Anyone can help me please?

None of the answers were helpful

答:
expData is a string as you've put the LINQ query inside quotation marks.

```<code>var expData = "from c in WebDB.TransTable
            group c by c.enterdate into g
              select g;"
</code>```

System.String does not have a property called Key, hence the error.

If you remove the quotation marks it should all work fine.

ContentLicense: CC BY-SA 3.0

Title: Unable to bind LINQ to gridview

Body:
I just using a simple LINQ query having group by clause and trying to bind its result set to GridView.
My LINQ query looks like

var expData = from c in WebDB.TransTable
              group c by c.enterdate into g
              select g;

Grid view on ASP.NET page

<asp:GridView ID="GridView1" AutoGenerateColumns="true" runat="server" DataKeyField="Key" />

But getting the error:

A field or property with the name 'Key' was not found on the selected data source.

Anyone can help me please?

None of the answers were helpful

Body:
expData is a string as you've put the LINQ query inside quotation marks.

var expData = "from c in WebDB.TransTable
            group c by c.enterdate into g
              select g;"

System.String does not have a property called Key, hence the error.

If you remove the quotation marks it should all work fine.


问:
Open CV trivial circle detection -- how to get least squares instead of a contour?
My goal is to accurately measure the diameter of a hole from a microscope. Workflow is: take an image, process for fitting, fit, convert radius in pixels to mm, write to a csv

This is an output of my image processing script used to measure the diameter of a hole. I'm having an issue where it seems like my circle fitting is prioritizing matching the contour rather than something like a least squares approach.

I've alternatively averaged many fits in something like this:

My issue here is I like to quickly scan to make sure the circle fit is appropriate. The trade off is the more fits I have, the more realistic the fit, the fewer I have the easier is to make sure the number is correct. My circles aren't always as pretty and circular as this one so it's important to me.

Here's the piece of my script fitting circles if you could take a look and tell me how to do more of a least squares approach on the order of 5 circles. I don't want to use minimum circle detection because a fluid is flowing through this hole so I'd like it to be more like a hydraulic diameter-- thanks!

```<code>(thresh, blackAndWhiteImage0) = cv2.threshold(img0, 100, 255, cv2.THRESH_BINARY) #make black + white
median0 = cv2.medianBlur(blackAndWhiteImage0, 151) #get rid of noise
circles0 = cv2.HoughCircles(median0,cv2.HOUGH_GRADIENT,1,minDist=5,param1= 25, param2=10, minRadius=min_radius_small,maxRadius=max_radius_small) #fit circles to image
</code>```

答:
I would suggest computing a mask as in nathancy's answer, but then simply counting the number of pixels in the mask opening that he computed (which is an unbiased estimate of the area of the hole), and then translating the area to a radius using radius = sqrt(area/pi). This will give you the radius of the circle with the same area as the hole, and corresponds to one method to obtain a best fit circle.

A different way of obtaining a best fit circle is to take the contour of the hole (as returned in cnts by cv.findContours in nethancy's answer), finding its centroid, and then computing the mean distance of each vertex to the centroid. This would correspond approximately* to a least squares fit of a circle to the hole perimeter.

* I say approximately because the vertices of the contour are an approximation to the contour, and the distances between these vertices is likely not uniform. The error should be really small though.

Here's code example using DIPlib (disclosure: I'm an author) (note: the import PyDIP statement below requires you install DIPlib, and you cannot install it with pip, there is a binary release for Windows on the GitHub page, or otherwise you need to build it from sources).

import PyDIP as dip
import imageio
import math

img = imageio.imread('https://i.stack.imgur.com/szvc2.jpg')
img = dip.Image(img[:,2600:-1])
img.SetPixelSize(0.01, 'mm')      # Use your actual values!
bin = ~dip.OtsuThreshold(dip.Gauss(img, [3]))
bin = dip.Opening(bin, 25)
#dip.Overlay(img, bin - dip.BinaryErosion(bin, 1, 3)).Show()

msr = dip.MeasurementTool.Measure(dip.Label(bin), features=['Size', 'Radius'])
#print(msr)

print('Method 1:', math.sqrt(msr[1]['Size'][0] / 3.14), 'mm')
print('Method 2:', msr[1]['Radius'][1], 'mm')
```

<p>The <code>MeasurementTool.Measure</code> function computes <code>'Size'</code>, which is the area; and <code>'Radius'</code>, which returns the max, mean, min and standard deviation of the distances between each boundary pixel and the centroid. From <code>'Radius'</code>, we take the 2nd value, the mean radius.</p>

<p>This outputs:</p>

```Method 1: 7.227900647539411 mm
Method 2: 7.225178113501325 mm
```

But do note that I assigned a random pixel size (0.01mm per pixel), you'll need to fill in the right pixels-to-mm conversion value.

Note how the two estimates are very close. Both methods are good, unbiased estimates. The first method is computationally cheaper.

Body:
My goal is to accurately measure the diameter of a hole from a microscope. Workflow is: take an image, process for fitting, fit, convert radius in pixels to mm, write to a csv

This is an output of my image processing script used to measure the diameter of a hole. I'm having an issue where it seems like my circle fitting is prioritizing matching the contour rather than something like a least squares approach.

I've alternatively averaged many fits in something like this:

My issue here is I like to quickly scan to make sure the circle fit is appropriate. The trade off is the more fits I have, the more realistic the fit, the fewer I have the easier is to make sure the number is correct. My circles aren't always as pretty and circular as this one so it's important to me.

Here's the piece of my script fitting circles if you could take a look and tell me how to do more of a least squares approach on the order of 5 circles. I don't want to use minimum circle detection because a fluid is flowing through this hole so I'd like it to be more like a hydraulic diameter-- thanks!

(thresh, blackAndWhiteImage0) = cv2.threshold(img0, 100, 255, cv2.THRESH_BINARY) #make black + white
median0 = cv2.medianBlur(blackAndWhiteImage0, 151) #get rid of noise
circles0 = cv2.HoughCircles(median0,cv2.HOUGH_GRADIENT,1,minDist=5,param1= 25, param2=10, minRadius=min_radius_small,maxRadius=max_radius_small) #fit circles to image

Body:
I would suggest computing a mask as in nathancy's answer, but then simply counting the number of pixels in the mask opening that he computed (which is an unbiased estimate of the area of the hole), and then translating the area to a radius using radius = sqrt(area/pi). This will give you the radius of the circle with the same area as the hole, and corresponds to one method to obtain a best fit circle.

A different way of obtaining a best fit circle is to take the contour of the hole (as returned in cnts by cv.findContours in nethancy's answer), finding its centroid, and then computing the mean distance of each vertex to the centroid. This would correspond approximately* to a least squares fit of a circle to the hole perimeter.

* I say approximately because the vertices of the contour are an approximation to the contour, and the distances between these vertices is likely not uniform. The error should be really small though.

Here's code example using DIPlib (disclosure: I'm an author) (note: the import PyDIP statement below requires you install DIPlib, and you cannot install it with pip, there is a binary release for Windows on the GitHub page, or otherwise you need to build it from sources).

import PyDIP as dip
import imageio
import math

img = imageio.imread('https://i.stack.imgur.com/szvc2.jpg')
img = dip.Image(img[:,2600:-1])
img.SetPixelSize(0.01, 'mm')      # Use your actual values!
bin = ~dip.OtsuThreshold(dip.Gauss(img, [3]))
bin = dip.Opening(bin, 25)
#dip.Overlay(img, bin - dip.BinaryErosion(bin, 1, 3)).Show()

msr = dip.MeasurementTool.Measure(dip.Label(bin), features=['Size', 'Radius'])
#print(msr)

print('Method 1:', math.sqrt(msr[1]['Size'][0] / 3.14), 'mm')
print('Method 2:', msr[1]['Radius'][1], 'mm')

The MeasurementTool.Measure function computes 'Size', which is the area; and 'Radius', which returns the max, mean, min and standard deviation of the distances between each boundary pixel and the centroid. From 'Radius', we take the 2nd value, the mean radius.

This outputs:

Method 1: 7.227900647539411 mm
Method 2: 7.225178113501325 mm

But do note that I assigned a random pixel size (0.01mm per pixel), you'll need to fill in the right pixels-to-mm conversion value.

Note how the two estimates are very close. Both methods are good, unbiased estimates. The first method is computationally cheaper.


问:
Eclipse - Find and Replace Dialog Always Opening Maximized
The Find and Replace dialog in my copy of Eclipse always opens maximized.  Is there a way within Eclipse to control the behavior of the dialog so it opens as a smaller popup window?  The same issue is occurring when I set Run Configuration environment variables.

I am using Eclipse Neon (yes, I know--many versions behind the current).  I have not had this problem until recently.  I cannot think of any changes I made myself that would have caused this behavior.

答: i was also in the discomfortable situation of having a big file/replace window that was hiding the code. right clicking on the title bar permitted me to resize it, and size was kept at next eclipse restart.</p>


问:
How can I implement a FPS view with WebGL inside a browser?
I'm using Copperlicht, and I want to create a usable FPS. The demo controls shows why the browser environment makes this a pain.

In order to implement FPS camera control, you need to track the relative mouse position - in other words, its motion, not its absolute screen coordinates. The mouse can leave the browser at any time (rightfully so) and can't be tracked, unless the user initiates a drag event inside the page. Click events change focus and prevent the application from using mouse data as input.

The mouse position can be tracked during drag, but this requires the user to hold down their left mouse button. This isn't good since left clicking is usually used for other things. Holding the button down is also tiring and cumbersome.

The only thing I can think of is automating the middle mouse button. A middle mouse button press keeps focus in the browser, and keeps left/right click events outside the browser window in the browser's focus. Is it possible to cause middle mouse button to stay pressed using JavaScript?

If not, is there a "pure" solution to this ? I'd rather not go to flash or Java or a plugin as an answer.

答:
I found this example code at
http://bitdaddys.com/javascript/example3run.html</p>

```<code> <html>
<head>
<title>JavaScript Example of Mouse Position Tracking</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form name=thisform>
<table border=0>
<tr><td colspan=2>Position Of Cursor</td></tr>
<tr><td>X <input type=text name=x value=""></td>
    <td>Y <input type=text name=y value=""></td>

</tr>
</table>
</form>

<script type=text/javascript>
    var isIE = document.all?true:false;
    if (!isIE) document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = getMousePosition;
    function getMousePosition(mp) {
      var _x;
      var _y;
      if (!isIE) {
        _x = mp.pageX;
        _y = mp.pageY;
      }
      if (isIE) {
        _x = event.clientX + document.body.scrollLeft;
        _y = event.clientY + document.body.scrollTop;
      }
      document.thisform.x.value=_x;
      document.thisform.y.value=_y;
      return true;
    }
</script>

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

Body:
I found this example code at
http://bitdaddys.com/javascript/example3run.html

 <html>
<head>
<title>JavaScript Example of Mouse Position Tracking</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form name=thisform>
<table border=0>
<tr><td colspan=2>Position Of Cursor</td></tr>
<tr><td>X <input type=text name=x value=""></td>
    <td>Y <input type=text name=y value=""></td>

</tr>
</table>
</form>

<script type=text/javascript>
    var isIE = document.all?true:false;
    if (!isIE) document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = getMousePosition;
    function getMousePosition(mp) {
      var _x;
      var _y;
      if (!isIE) {
        _x = mp.pageX;
        _y = mp.pageY;
      }
      if (isIE) {
        _x = event.clientX + document.body.scrollLeft;
        _y = event.clientY + document.body.scrollTop;
      }
      document.thisform.x.value=_x;
      document.thisform.y.value=_y;
      return true;
    }
</script>

</body>
</html>


问:
Jwt expiration control and redirect login page
The user has a valid jwt for a certain period of time. this jwt ends if no activity is performed within 30 minutes. How can I redirect user to login page in middleware after jwt time is over.</p>

```<code>return (next) => (action) => {
    if (typeof action === 'function') {
      if (getToken() && !getState().auth.pendingRefreshingToken) {
        const tokenExp = new Date(getTokenExp() * 1000);
        if (new Date() < tokenExp) { // JWT Expiration Control
          const refreshThreshold = new Date((new Date().getTime() + 300000));
          if (refreshThreshold > new Date(getTokenExp() * 1000)) {
            refreshToken(dispatch).then(() => next(action)); // JWT Refresh
          }
        } else {
          logoutMiddleware(dispatch); // JWT Expiration(I want to redirect user to login page)
        }
      }
    }
    return next(action);
  };
</code>```

答:
I'm not sure if I understand your question correctly but assuming you have a specific route for login and you just want to redirect the user to that route you can do this:</p>

```<code>window.location.href = '/login'
</code>```

Body:
The user has a valid jwt for a certain period of time. this jwt ends if no activity is performed within 30 minutes. How can I redirect user to login page in middleware after jwt time is over.

return (next) => (action) => {
    if (typeof action === 'function') {
      if (getToken() && !getState().auth.pendingRefreshingToken) {
        const tokenExp = new Date(getTokenExp() * 1000);
        if (new Date() < tokenExp) { // JWT Expiration Control
          const refreshThreshold = new Date((new Date().getTime() + 300000));
          if (refreshThreshold > new Date(getTokenExp() * 1000)) {
            refreshToken(dispatch).then(() => next(action)); // JWT Refresh
          }
        } else {
          logoutMiddleware(dispatch); // JWT Expiration(I want to redirect user to login page)
        }
      }
    }
    return next(action);
  };

Body:
I'm not sure if I understand your question correctly but assuming you have a specific route for login and you just want to redirect the user to that route you can do this:

window.location.href = '/login'


问:
Entity Framework - Updated relationship does not retrieve data created from the old relationship
I recently updated my Entity Framework (version 6.2.0) mapping to improve the performance of my application but without modifying the database schema. Basically, I had a One-to-Many relationship I turned into a One-to-One relationship.

When I create new objects with this new mapping, everything works as expected: the objects are saved in the database with the right values in the foreign key colums, etc. When I restart my application (and reset the DbContext) and access to those objects, the navigation properties of my entities are fulfilled.

The problem occurs when I try to access objects that were created before this EF mapping update. With those old objects, the navigation properties are null and I can't access to the other end of the relationship.

Concretely, I have two tables defined like this:

```<code> ______           _____________
|Sample|         |Sample_Result|
|------|         |-------------|
|Id    |<--------|Result_Of    |
|______|  Fk     |_____________|

</code>```

From a business perspective, a sample can only have one result. But we used to have it mapped in Entity Framework as a One-to-Many relation ship as follow:

```<code>[Table("Sample")]
public class SampleEntity
{
    public virtual IList<SampleResultEntity> Results { get; set; }
}

[Table("Sample_Result")]
public class SampleResultEntity
{
    [Required]
    [Column("Result_Of")]
    public Guid ResultOfFk { get; set; }

    [ForeignKey(nameof(ResultOfFk))]
    public virtual SampleEntity ResultOf { get; set; }
}
</code>```

We had terrible performance with this mapping so I recently update it to a One-to-One relationship:

```<code>[Table("Sample")]
public class SampleEntity
{
    public virtual SampleResultEntity Result { get; set; }
}

[Table("Sample_Result")]
public class SampleResultEntity
{
    [Required]
    [Column("Result_Of")]
    public Guid ResultOfFk { get; set; }

    public virtual SampleEntity ResultOf { get; set; }
}
</code>```

And in my dbContext, I added the following mapping:

```<code> modelBuilder.Entity<SampleResultEntity>()
            .HasRequired(sr => sr.ResultOf)
            .WithRequiredDependent(s => s.Result);
</code>```

When I access to samples created after the mapping update, sample.Result is defined.

When I access to samples created before the mapping update, sample.Result is null.

When I query the database with an inner join over the two tables, like this:

```<code>SELECT *
  FROM Sample s
  INNER JOIN Sample_Result sr ON s.Id = sr.Result_Of;
</code>```

I don't "lose" rows (if I have 40 samples, I get 40 rows). So the foreign keys are well set.

Can someone explain me this behavior?

答:
You will probably need to outline your complete table structure because from what you describe you cannot simply change a mapping from 1-to-many to 1-to-1 based on a schema.

A 1-to-many schema will look something like this:

```<code>Sample
SampleID (PK)

SampleResult
SampleResultID (PK)
SampleID (FK)
</code>```

A 1-to-1 schema will look like:
    Sample
    SampleID (PK)

```<code>SampleResult
SampleID (PK + FK)
</code>```

So, in a 1-to-many schema containing effectively 1 to 1 rows you would have Sample ID=1 with a SampleResult with SampleResultID = 16 and SampleID = 1.
If you were to simply change the mapping to 1-to-1, EF would expect the PKs on both tables to equate. Since SampleResult's PK is SampleResultId, getting the right record is impossible as it'd be comparing Sample.SampleId /w SampleResult.SampleResultId (not SampleResult.SampleId)

Your new test records will appear to work because what you would probably find would be:

```<code>Sample.SampleID = **220**

SampleResult.SampleResultID = **220**
SampleResult.SampleID = 220
</code>```

If you were using Identity (Int) columns for keys this problem would have manifested somewhat differently where you'd either be getting empty links, or getting links to incorrect results. Because you are using GUIDs and each ID will be relatively universally unique, the result will be empty links.

I would recommend using a Profiler on your test database to capture the SQL being used when loading a Sample/Result pair to verify the correct columns are being joined.

Without changing the schema, as long as SampleResult.SampleResultId is set up as an Identity / Default, and you can guarantee that there are no 1-to-many instances (multiple results on a single sample) you should be able to update the mapping in EF to treat the SampleId on the SampleResult as the Key.  This way, with your new mapping EF will link the 2 together. This will mean your previous "new" test records will no longer work because they would have been marrying the Sample.SampleID with the SampleResult.SampleResultID, but your original records should work, and newer records should work as well. EF's Key does not have to match the PK on the table, so long as you are using DB-First (no migrations) and the schema is satisfied. If the DB column for SampleResultId defaults to NewSequentialId() or NewId() then you shouldn't need to worry about it. If the PK is set in code then you may need to map the property as a regular column and make a note to use the SampleId. Where this can "break" is if you have any other entities linking to SampleResult based on SampleResultId. EF will be considering the SampleId as the Key when joining.

On a final note: I'm a bit wary about the conclusion that a 1-to-many relationship between Sample and SampleResult led to performance issues that would be resolved by re-mapping to a 1-to-1. While it's somewhat misleading to have a 1-to-many relationship that only is meant to contain 1 child, in the end EF will be using an Inner Join in both cases. I would strongly suspect something else is at play. GUID keys can be problematic as systems grow if you are using NewId() / Guid.New for new rows. This is because the relative randomness of the 128 bit key in a Clustered Index can lead to considerable fragmentation in the index tables. It is better to use NewSequentialId() or a code-based implementation of NewSequentialId() to generate unique, but sort-able GUIDs that minimize this effect, and combine that with regular index maintenance on the database tables.

Body:
I recently updated my Entity Framework (version 6.2.0) mapping to improve the performance of my application but without modifying the database schema. Basically, I had a One-to-Many relationship I turned into a One-to-One relationship.

When I create new objects with this new mapping, everything works as expected: the objects are saved in the database with the right values in the foreign key colums, etc. When I restart my application (and reset the DbContext) and access to those objects, the navigation properties of my entities are fulfilled.

The problem occurs when I try to access objects that were created before this EF mapping update. With those old objects, the navigation properties are null and I can't access to the other end of the relationship.

Concretely, I have two tables defined like this:

 ______           _____________
|Sample|         |Sample_Result|
|------|         |-------------|
|Id    |<--------|Result_Of    |
|______|  Fk     |_____________|

From a business perspective, a sample can only have one result. But we used to have it mapped in Entity Framework as a One-to-Many relation ship as follow:

[Table("Sample")]
public class SampleEntity
{
    public virtual IList<SampleResultEntity> Results { get; set; }
}

[Table("Sample_Result")]
public class SampleResultEntity
{
    [Required]
    [Column("Result_Of")]
    public Guid ResultOfFk { get; set; }

    [ForeignKey(nameof(ResultOfFk))]
    public virtual SampleEntity ResultOf { get; set; }
}

We had terrible performance with this mapping so I recently update it to a One-to-One relationship:

[Table("Sample")]
public class SampleEntity
{
    public virtual SampleResultEntity Result { get; set; }
}

[Table("Sample_Result")]
public class SampleResultEntity
{
    [Required]
    [Column("Result_Of")]
    public Guid ResultOfFk { get; set; }

    public virtual SampleEntity ResultOf { get; set; }
}

And in my dbContext, I added the following mapping:

 modelBuilder.Entity<SampleResultEntity>()
            .HasRequired(sr => sr.ResultOf)
            .WithRequiredDependent(s => s.Result);

When I access to samples created after the mapping update, sample.Result is defined.

When I access to samples created before the mapping update, sample.Result is null.

When I query the database with an inner join over the two tables, like this:

SELECT *
  FROM Sample s
  INNER JOIN Sample_Result sr ON s.Id = sr.Result_Of;

I don't "lose" rows (if I have 40 samples, I get 40 rows). So the foreign keys are well set.

Can someone explain me this behavior?

Body:
You will probably need to outline your complete table structure because from what you describe you cannot simply change a mapping from 1-to-many to 1-to-1 based on a schema.

A 1-to-many schema will look something like this:

Sample
SampleID (PK)

SampleResult
SampleResultID (PK)
SampleID (FK)

A 1-to-1 schema will look like:
    Sample
    SampleID (PK)

SampleResult
SampleID (PK + FK)

So, in a 1-to-many schema containing effectively 1 to 1 rows you would have Sample ID=1 with a SampleResult with SampleResultID = 16 and SampleID = 1.
If you were to simply change the mapping to 1-to-1, EF would expect the PKs on both tables to equate. Since SampleResult's PK is SampleResultId, getting the right record is impossible as it'd be comparing Sample.SampleId /w SampleResult.SampleResultId (not SampleResult.SampleId)

Your new test records will appear to work because what you would probably find would be:

Sample.SampleID = **220**

SampleResult.SampleResultID = **220**
SampleResult.SampleID = 220

If you were using Identity (Int) columns for keys this problem would have manifested somewhat differently where you'd either be getting empty links, or getting links to incorrect results. Because you are using GUIDs and each ID will be relatively universally unique, the result will be empty links.

I would recommend using a Profiler on your test database to capture the SQL being used when loading a Sample/Result pair to verify the correct columns are being joined.

Without changing the schema, as long as SampleResult.SampleResultId is set up as an Identity / Default, and you can guarantee that there are no 1-to-many instances (multiple results on a single sample) you should be able to update the mapping in EF to treat the SampleId on the SampleResult as the Key.  This way, with your new mapping EF will link the 2 together. This will mean your previous "new" test records will no longer work because they would have been marrying the Sample.SampleID with the SampleResult.SampleResultID, but your original records should work, and newer records should work as well. EF's Key does not have to match the PK on the table, so long as you are using DB-First (no migrations) and the schema is satisfied. If the DB column for SampleResultId defaults to NewSequentialId() or NewId() then you shouldn't need to worry about it. If the PK is set in code then you may need to map the property as a regular column and make a note to use the SampleId. Where this can "break" is if you have any other entities linking to SampleResult based on SampleResultId. EF will be considering the SampleId as the Key when joining.

On a final note: I'm a bit wary about the conclusion that a 1-to-many relationship between Sample and SampleResult led to performance issues that would be resolved by re-mapping to a 1-to-1. While it's somewhat misleading to have a 1-to-many relationship that only is meant to contain 1 child, in the end EF will be using an Inner Join in both cases. I would strongly suspect something else is at play. GUID keys can be problematic as systems grow if you are using NewId() / Guid.New for new rows. This is because the relative randomness of the 128 bit key in a Clustered Index can lead to considerable fragmentation in the index tables. It is better to use NewSequentialId() or a code-based implementation of NewSequentialId() to generate unique, but sort-able GUIDs that minimize this effect, and combine that with regular index maintenance on the database tables.


问:
Get one item of each array and check a condition with both
I have the following using Typescript:

```<code>private baskets$: BehaviorSubjectBasket[]> = new BehaviorSubject<Basket[]>([]);

private products$: BehaviorSubject<Product[]> = new BehaviorSubject<Product[]>([]);
</code>```

Given BasketId and ProductId I need to get a Basket and a Product and check a condition with both:

```<code>result: Observable<boolean> = this.baskets$.asObservable().pipe(
    map(baskets => baskets.find(x => x.basketId === basketId)),
    map(basket => Check condition with basket and product);
</code>```

My problem is how to get the product and use it in the condition along with the basket.

答:
You can do a combine operator like so:

```<code>result: Observable<boolean> = combineLatest(this.baskets$.asObservable(),
                                            this.products$.asObservable(),
                                            ).pipe(
                                 map(([baskets, products]) => /*... do what you need here */),
                               );

</code>```

I like combineLatest but there is also forkJoin, zip, etc. with slight variations.

Body:
I have the following using Typescript:

private baskets$: BehaviorSubjectBasket[]> = new BehaviorSubject<Basket[]>([]);

private products$: BehaviorSubject<Product[]> = new BehaviorSubject<Product[]>([]);

Given BasketId and ProductId I need to get a Basket and a Product and check a condition with both:

result: Observable<boolean> = this.baskets$.asObservable().pipe(
    map(baskets => baskets.find(x => x.basketId === basketId)),
    map(basket => Check condition with basket and product);

My problem is how to get the product and use it in the condition along with the basket.

Body:
You can do a combine operator like so:

result: Observable<boolean> = combineLatest(this.baskets$.asObservable(),
                                            this.products$.asObservable(),
                                            ).pipe(
                                 map(([baskets, products]) => /*... do what you need here */),
                               );

I like combineLatest but there is also forkJoin, zip, etc. with slight variations.


问:
Generic casting / instance check / exclude type parameter
Problem.

A Detect can supply a specific type of Detectables, which look like

```<code>interface Detectable
{/*...*/}

interface Some_detectable extends Detectable
{/*...*/}
</code>```

A supply method in Detect should be able to accept any Detectable and only supply it if it is of a specific type. I imagine the described situation like this

```<code>abstract
class Detect<D extends Detectable>
{
  private final Set<D>
  DETECT= new LinkedHashSet<>();

  void
  supplying(Detectable d)
  {
    /*[ DETECT.add(d); ]*/
    /*supply d if of type D*/
  }
}
</code>```

Attemps.

First I tried to make a method to accept D and another method handles the case when the argument is not D but just any Detectable.

Unfortunately I am not able to exclude D from the second method or the class type D.

Therefore, these methods may result in an ambiguous method (if D is the raw Detectable)

```<code>abstract
class Detect<D extends Detectable>
{
  /*...*/
  void
  supplying(D d)
  {
    DETECT.add(d);
  }
  void
  supplying(Detectable d){}
}
</code>```

My current working, but ugly attempt to solve the problem.

```<code>abstract
class Detect<D extends Detectable>
{
  final Set<D>
  DETECT= new LinkedHashSet<>();

  void
  supplying(Detectable d)
  {
    D
    casted= try_cast(d);

    if(casted==null) {return;}
    DETECT.add(casted);
  }

  abstract protected D
  try_cast(Detectable detectable);
}

class
Some_detect
extends Detect<Some_detectable>
{
  @Override protected Some_detectable
  try_cast(Detectable d)
  {
    return d instanceof Some_detectable
           ? (Some_detectable)d
           : null;
  }
}
</code>```

答:
I suggest you to store an object of class Class<D> and use it to check class of d. Java generics are erased at runtime, so you can't write something like d instanceof D without storing this class.

Here's example code (sorry, I edited your code to correspond to Java code style):

```<code>interface Detectable {}
interface SomeDetectable extends Detectable {}

abstract class Detect<D extends Detectable> {
    private final Class<D> dClass;
    private final Set<D> detect = new LinkedHashSet<>();

    protected Detect(Class<D> dClass) {
        this.dClass = dClass;
    }

    void supplying(Detectable d) {
        if (dClass.isInstance(d)) {
            detect.add(dClass.cast(d));
        }
    }
}

class SomeDetect extends Detect<SomeDetectable> {
    SomeDetect() {
        super(SomeDetectable.class);
    }
}
</code>```

You can make your base class Detect<D> easier to use by automatically finding out type parameter in this particular case, because it's actually stored in class metadata. But it is a fragile approach and I don't generally recommend it.

Body:
Problem.

A Detect can supply a specific type of Detectables, which look like

interface Detectable
{/*...*/}

interface Some_detectable extends Detectable
{/*...*/}

A supply method in Detect should be able to accept any Detectable and only supply it if it is of a specific type. I imagine the described situation like this

abstract
class Detect<D extends Detectable>
{
  private final Set<D>
  DETECT= new LinkedHashSet<>();

  void
  supplying(Detectable d)
  {
    /*[ DETECT.add(d); ]*/
    /*supply d if of type D*/
  }
}

Attemps.

First I tried to make a method to accept D and another method handles the case when the argument is not D but just any Detectable.

Unfortunately I am not able to exclude D from the second method or the class type D.

Therefore, these methods may result in an ambiguous method (if D is the raw Detectable)

abstract
class Detect<D extends Detectable>
{
  /*...*/
  void
  supplying(D d)
  {
    DETECT.add(d);
  }
  void
  supplying(Detectable d){}
}

My current working, but ugly attempt to solve the problem.

abstract
class Detect<D extends Detectable>
{
  final Set<D>
  DETECT= new LinkedHashSet<>();

  void
  supplying(Detectable d)
  {
    D
    casted= try_cast(d);

    if(casted==null) {return;}
    DETECT.add(casted);
  }

  abstract protected D
  try_cast(Detectable detectable);
}

class
Some_detect
extends Detect<Some_detectable>
{
  @Override protected Some_detectable
  try_cast(Detectable d)
  {
    return d instanceof Some_detectable
           ? (Some_detectable)d
           : null;
  }
}

Body:
I suggest you to store an object of class Class<D> and use it to check class of d. Java generics are erased at runtime, so you can't write something like d instanceof D without storing this class.

Here's example code (sorry, I edited your code to correspond to Java code style):

interface Detectable {}
interface SomeDetectable extends Detectable {}

abstract class Detect<D extends Detectable> {
    private final Class<D> dClass;
    private final Set<D> detect = new LinkedHashSet<>();

    protected Detect(Class<D> dClass) {
        this.dClass = dClass;
    }

    void supplying(Detectable d) {
        if (dClass.isInstance(d)) {
            detect.add(dClass.cast(d));
        }
    }
}

class SomeDetect extends Detect<SomeDetectable> {
    SomeDetect() {
        super(SomeDetectable.class);
    }
}

You can make your base class Detect<D> easier to use by automatically finding out type parameter in this particular case, because it's actually stored in class metadata. But it is a fragile approach and I don't generally recommend it.


问:
setValue() for multiple cells
I use the function below to concat the value of the cell in Google Sheets and a hyperlink to crate a HYPERLINK() function on my ss.

```<code>    function setCustomLink(){
      var ss = SpreadsheetApp.getActive().getActiveSheet();
      var cell = ss.getActiveCell();
      var cellValue = cell.getValue();
      cell.setValue('=HYPERLINK("https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=pesquisaSimples&-H&Host:&projudi.tjpr.jus.br&-H&User-Agent:&Mozilla/5.0&(Windows&NT&6.3;&WOW64;&rv:49.0)&Gecko/20100101&Firefox/49.0&-H&Accept:&text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&-H&Accept-Language:&pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3&--compressed&-H&Referer:&https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=iniciarSimples&-H&Cookie:&projudiContCookie=0;&JSESSIONID=053165f8dd5f8532c326f3eb06d7;&projudi-route=4;&dtLatC=54;&dtPC=-;&dtCookie=49542FA50EF89B032E8685F08394F120|UHJvanVkaSstK0V4dGVybm98MQ&-H&Connection:&keep-alive&-H&Upgrade-Insecure-Requests:&1&--data&page=1&flagNumeroUnico=true&flagNumeroFisicoAntigo=false&numeroProcesso='
      + cellValue + '";"' + cellValue+'")');
    }
</code>```

It works just fine. The only problem is that I have to execute the function one by one, and it takes a lot of time. I usualy have them on a row like this (A2:A):

Is there any way I can select the entire row and run the function once? I tried using .foreach(function(r){return r[0]})*, but for some reason never could get it right. Thanks!

(FYI: the content is in portuguese and the function allows me to see the lawsuit status by linking its number with the search tool hyperlink).

*Here is the function I tried to make, it comes back as "null". I also tried range.forEach(function(r), with no luck.

```<code>function myFunction() {
  var ss = SpreadsheetApp.getActive().getActiveSheet();
  var range = ss.getActiveRange().getValues();
  var value = range.forEach(function(r){
    '=HYPERLINK("https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=pesquisaSimples&-H&Host:&projudi.tjpr.jus.br&-H&User-Agent:&Mozilla/5.0&(Windows&NT&6.3;&WOW64;&rv:49.0)&Gecko/20100101&Firefox/49.0&-H&Accept:&text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&-H&Accept-Language:&pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3&--compressed&-H&Referer:&https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=iniciarSimples&-H&Cookie:&projudiContCookie=0;&JSESSIONID=053165f8dd5f8532c326f3eb06d7;&projudi-route=4;&dtLatC=54;&dtPC=-;&dtCookie=49542FA50EF89B032E8685F08394F120|UHJvanVkaSstK0V4dGVybm98MQ&-H&Connection:&keep-alive&-H&Upgrade-Insecure-Requests:&1&--data&page=1&flagNumeroUnico=true&flagNumeroFisicoAntigo=false&numeroProcesso=' + r[0] + '";"' + r[0]+'")'
  });
  range.setValue(value);
}
</code>```

答:
Given your use of getActiveCell(), it looks like your workflow is:

select a cell

execute the function to update that single cell

To use the same workflow when selecting multiple cells, you want to use the Spreadsheet.getActiveRangeList() method. This will allow you to interact with a list of all the currently selected ranges. This will work with all of the below cases:

selecting a single cell

selecting a range of contiguous cells

selecting multiple ranges of contiguous cells (i.e. using CTRL + left click)

```<code>// Use a global constant to ease editing the value should the URL need to be changed.
var URL_PREFIX = 'http://url/?param1=value1&param2=';

function setCustomLinks() {
  var activeSheet = SpreadsheetApp.getActiveSheet();
  var ranges = activeSheet.getActiveRangeList().getRanges();

  // Loop through the ranges.
  for (var i = 0; i < ranges.length; i++) {

    // Get all cell values of the range into a 2D array.
    var values = ranges[i].getValues();

    // Loop through the 2D array of values.
    for (var j = 0; j < values.length; j++) {
      for (var k = 0; k < values[j].length; k++) {

        // Replace each value with a hyperlink formula.
        values[j][k] = createCustomLink(values[j][k]);
      }
    }

    // Set the cell values using the new values.
    ranges[i].setValues(values);
  }
}

function createCustomLink(value) {
  var url = URL_PREFIX + value;
  return '=HYPERLINK("' + url + '", "' + value + '")';
}
</code>```

Another benefit with this approach is that it's using batch operations to get/set each range of values in single method call. This makes it much faster when handling a large range and is one of the documented best practices.

Title: setValue() for multiple cells

Body:
I use the function below to concat the value of the cell in Google Sheets and a hyperlink to crate a HYPERLINK() function on my ss.

    function setCustomLink(){
      var ss = SpreadsheetApp.getActive().getActiveSheet();
      var cell = ss.getActiveCell();
      var cellValue = cell.getValue();
      cell.setValue('=HYPERLINK("https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=pesquisaSimples&-H&Host:&projudi.tjpr.jus.br&-H&User-Agent:&Mozilla/5.0&(Windows&NT&6.3;&WOW64;&rv:49.0)&Gecko/20100101&Firefox/49.0&-H&Accept:&text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&-H&Accept-Language:&pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3&--compressed&-H&Referer:&https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=iniciarSimples&-H&Cookie:&projudiContCookie=0;&JSESSIONID=053165f8dd5f8532c326f3eb06d7;&projudi-route=4;&dtLatC=54;&dtPC=-;&dtCookie=49542FA50EF89B032E8685F08394F120|UHJvanVkaSstK0V4dGVybm98MQ&-H&Connection:&keep-alive&-H&Upgrade-Insecure-Requests:&1&--data&page=1&flagNumeroUnico=true&flagNumeroFisicoAntigo=false&numeroProcesso='
      + cellValue + '";"' + cellValue+'")');
    }

It works just fine. The only problem is that I have to execute the function one by one, and it takes a lot of time. I usualy have them on a row like this (A2:A):

Is there any way I can select the entire row and run the function once? I tried using .foreach(function(r){return r[0]})*, but for some reason never could get it right. Thanks!

(FYI: the content is in portuguese and the function allows me to see the lawsuit status by linking its number with the search tool hyperlink).

*Here is the function I tried to make, it comes back as "null". I also tried range.forEach(function(r), with no luck.

function myFunction() {
  var ss = SpreadsheetApp.getActive().getActiveSheet();
  var range = ss.getActiveRange().getValues();
  var value = range.forEach(function(r){
    '=HYPERLINK("https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=pesquisaSimples&-H&Host:&projudi.tjpr.jus.br&-H&User-Agent:&Mozilla/5.0&(Windows&NT&6.3;&WOW64;&rv:49.0)&Gecko/20100101&Firefox/49.0&-H&Accept:&text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&-H&Accept-Language:&pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3&--compressed&-H&Referer:&https://projudi.tjpr.jus.br/projudi/processo/buscaProcesso.do?actionType=iniciarSimples&-H&Cookie:&projudiContCookie=0;&JSESSIONID=053165f8dd5f8532c326f3eb06d7;&projudi-route=4;&dtLatC=54;&dtPC=-;&dtCookie=49542FA50EF89B032E8685F08394F120|UHJvanVkaSstK0V4dGVybm98MQ&-H&Connection:&keep-alive&-H&Upgrade-Insecure-Requests:&1&--data&page=1&flagNumeroUnico=true&flagNumeroFisicoAntigo=false&numeroProcesso=' + r[0] + '";"' + r[0]+'")'
  });
  range.setValue(value);
}

Body:
Given your use of getActiveCell(), it looks like your workflow is:

select a cell

execute the function to update that single cell

To use the same workflow when selecting multiple cells, you want to use the Spreadsheet.getActiveRangeList() method. This will allow you to interact with a list of all the currently selected ranges. This will work with all of the below cases:

selecting a single cell

selecting a range of contiguous cells

selecting multiple ranges of contiguous cells (i.e. using CTRL + left click)

// Use a global constant to ease editing the value should the URL need to be changed.
var URL_PREFIX = 'http://url/?param1=value1&param2=';

function setCustomLinks() {
  var activeSheet = SpreadsheetApp.getActiveSheet();
  var ranges = activeSheet.getActiveRangeList().getRanges();

  // Loop through the ranges.
  for (var i = 0; i < ranges.length; i++) {

    // Get all cell values of the range into a 2D array.
    var values = ranges[i].getValues();

    // Loop through the 2D array of values.
    for (var j = 0; j < values.length; j++) {
      for (var k = 0; k < values[j].length; k++) {

        // Replace each value with a hyperlink formula.
        values[j][k] = createCustomLink(values[j][k]);
      }
    }

    // Set the cell values using the new values.
    ranges[i].setValues(values);
  }
}

function createCustomLink(value) {
  var url = URL_PREFIX + value;
  return '=HYPERLINK("' + url + '", "' + value + '")';
}

Another benefit with this approach is that it's using batch operations to get/set each range of values in single method call. This makes it much faster when handling a large range and is one of the documented best practices.


问:
Numpy Changing Matrix dimensions
I have a 28x28 pixel image as a numpy array and its shape is (28,28) using the np.array.shape function. I want the shape to be 784x1. In other words with a NxN matrix how do you convert it to a N^2x1. Using the flatten function i get almost what I'm looking for, the shape from flatten is (784,).</p>

答:
Another possible way is to use np.atleast_2d</p>

```<code>np.atleast_2d(arr.flatten())
</code>```

Title: Numpy Changing Matrix dimensions

Body:
Another possible way is to use np.atleast_2d

np.atleast_2d(arr.flatten())


问:
Heroku Cannot GET /
I am new to Heroku and believe I am following all of the steps outlined on Heroku's website to deploy via node.js – https://devcenter.heroku.com/articles/getting-started-with-nodejs – but despite indications of success, I only see this in the browser when I go to my newly-generated herokuapp.com site.

Cannot GET /

No errors when executing

```<code>git push heroku master
</code>```

My Procfile is simply

```<code>web: node app.js
</code>```

I dont quite understand dynos yet, but there seems to be one running:

heroku ps
  === web (1X): node app.js
  web.1: up 2014/07/03 23:55:00 (~ 18m ago)

Then:

heroku open
  Opening APP-NAME... done

But https://APP-NAME.herokuapp.com/ just displays the Cannot GET / message.

答: I'm a little bit embarrased but my error was running git push heroku master without the changes being commited.</p>

Title: Heroku Cannot GET /

Body:
I am new to Heroku and believe I am following all of the steps outlined on Heroku's website to deploy via node.js – https://devcenter.heroku.com/articles/getting-started-with-nodejs – but despite indications of success, I only see this in the browser when I go to my newly-generated herokuapp.com site.

Cannot GET /

No errors when executing

git push heroku master

My Procfile is simply

web: node app.js

I dont quite understand dynos yet, but there seems to be one running:

heroku ps
  === web (1X): node app.js
  web.1: up 2014/07/03 23:55:00 (~ 18m ago)

Then:

heroku open
  Opening APP-NAME... done

But https://APP-NAME.herokuapp.com/ just displays the Cannot GET / message.


问:
Using Google Slides API is it possible to use the response from one request in all or any of the remaining requests during the same batch Update
I created this code which creates a Google Slides table from a Spreadsheet.  But since I had to have the tableObjectId I did it in two batchUpdates.  So I'm wondering if it's possible to get the resp1.replies[0].creatTable.objectId from the first request which creates the table, into the requests for loading the cells all in the same batch update.

The Code:

```<code>function putTablesIntoSlides() {
  var pr=SlidesApp.openById('Presentation Id');
  var slide1_ObjectId=pr.getSlides()[1].getObjectId();
  Logger.log(slide1_ObjectId);
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet10');
  var rg=sh.getDataRange();
  var v=rg.getValues();

  //Create Table
  var request1={"createTable": {"elementProperties":{"pageObjectId": slide1_ObjectId},"rows": v.length,"columns": v[0].length}};
  var resp1=Slides.Presentations.batchUpdate({requests:request1}, pr.getId());

  //Preparing the request for Adding Text into cells
  var request2=[];
  for(var i=0;i<v.length;i++) {
    for(var j=0;j<v[i].length;j++) {

      //Is there a way to get the replies[0].createTable.objectId from the create table request in the same batch update.
      request2.push({"insertText":{"objectId":resp1.replies[0].createTable.objectId,"cellLocation": {"rowIndex":i,"columnIndex":j},"text": v[i][j].toString()}});
    }
  }

  //Adding text
  var resp2=Slides.Presentations.batchUpdate({requests:request2}, pr.getId());
}
</code>```

In other words is it possible to use the response from one request in any or all of the remaining requests during a single batch update.

答:
You want to run the batchUpdate method of Slides API of the following requests by one API call.

Create new table.

Put values.

You want to achieve this using Google Apps Script.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modififcation points:

In this case, when new table is created, the object ID of created table can be set at the request body.

Using the object ID, the values can be put to the table.

The official documentsays as follows.

objectId:
  A user-supplied object ID for the placeholder identified above that to be created onto a slide.
  If you specify an ID, it must be unique among all pages and page elements in the presentation. The ID must start with an alphanumeric character or an underscore (matches regex [a-zA-Z0-9_] ); remaining characters may include those as well as a hyphen or colon (matches regex [a-zA-Z0-9_-:] ). The length of the ID must not be less than 5 or greater than 50.
  If you don't specify an ID, a unique one is generated.

When above points are reflected to your script, it becomes as follows.

Modified script:

From:

```<code>//Create Table
var request1={"createTable": {"elementProperties":{"pageObjectId": slide1_ObjectId},"rows": v.length,"columns": v[0].length}};
var resp1=Slides.Presentations.batchUpdate({requests:request1}, pr.getId());

//Preparing the request for Adding Text into cells
var request2=[];
for(var i=0;i<v.length;i++) {
  for(var j=0;j<v[i].length;j++) {

    //Is there a way to get the replies[0].createTable.objectId from the create table request in the same batch update.
    request2.push({"insertText":{"objectId":resp1.replies[0].createTable.objectId,"cellLocation": {"rowIndex":i,"columnIndex":j},"text": v[i][j].toString()}});
  }
}
//Adding text
var resp2=Slides.Presentations.batchUpdate({requests:request2}, pr.getId());
</code>```

To:

```<code>var tableObjectId = "sampleId1";  // Here, the object ID of table is set.

//Create Table
var requests = [{"createTable": {"objectId": tableObjectId, "elementProperties":{"pageObjectId": slide1_ObjectId},"rows": v.length,"columns": v[0].length}}];

//Preparing the request for Adding Text into cells
for(var i=0;i<v.length;i++) {
  for(var j=0;j<v[i].length;j++) {

    //Is there a way to get the replies[0].createTable.objectId from the create table request in the same batch update.
    requests.push({"insertText":{"objectId":tableObjectId,"cellLocation": {"rowIndex":i,"columnIndex":j},"text": v[i][j].toString()}});
  }
}
//Adding text
var resp = Slides.Presentations.batchUpdate({requests:requests}, pr.getId());
</code>```

In this case, as a sample object ID, var tableObjectId = "sampleId1" is used.

Reference:

CreateTableRequest

If I misunderstood your question and this was not the direction you want, I apologize.

Body:
I created this code which creates a Google Slides table from a Spreadsheet.  But since I had to have the tableObjectId I did it in two batchUpdates.  So I'm wondering if it's possible to get the resp1.replies[0].creatTable.objectId from the first request which creates the table, into the requests for loading the cells all in the same batch update.

The Code:

function putTablesIntoSlides() {
  var pr=SlidesApp.openById('Presentation Id');
  var slide1_ObjectId=pr.getSlides()[1].getObjectId();
  Logger.log(slide1_ObjectId);
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet10');
  var rg=sh.getDataRange();
  var v=rg.getValues();

  //Create Table
  var request1={"createTable": {"elementProperties":{"pageObjectId": slide1_ObjectId},"rows": v.length,"columns": v[0].length}};
  var resp1=Slides.Presentations.batchUpdate({requests:request1}, pr.getId());

  //Preparing the request for Adding Text into cells
  var request2=[];
  for(var i=0;i<v.length;i++) {
    for(var j=0;j<v[i].length;j++) {

      //Is there a way to get the replies[0].createTable.objectId from the create table request in the same batch update.
      request2.push({"insertText":{"objectId":resp1.replies[0].createTable.objectId,"cellLocation": {"rowIndex":i,"columnIndex":j},"text": v[i][j].toString()}});
    }
  }

  //Adding text
  var resp2=Slides.Presentations.batchUpdate({requests:request2}, pr.getId());
}

In other words is it possible to use the response from one request in any or all of the remaining requests during a single batch update.

Body:
You want to run the batchUpdate method of Slides API of the following requests by one API call.

Create new table.

Put values.

You want to achieve this using Google Apps Script.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modififcation points:

In this case, when new table is created, the object ID of created table can be set at the request body.

Using the object ID, the values can be put to the table.

The official documentsays as follows.

objectId:
  A user-supplied object ID for the placeholder identified above that to be created onto a slide.
  If you specify an ID, it must be unique among all pages and page elements in the presentation. The ID must start with an alphanumeric character or an underscore (matches regex [a-zA-Z0-9_] ); remaining characters may include those as well as a hyphen or colon (matches regex [a-zA-Z0-9_-:] ). The length of the ID must not be less than 5 or greater than 50.
  If you don't specify an ID, a unique one is generated.

When above points are reflected to your script, it becomes as follows.

Modified script:

From:

//Create Table
var request1={"createTable": {"elementProperties":{"pageObjectId": slide1_ObjectId},"rows": v.length,"columns": v[0].length}};
var resp1=Slides.Presentations.batchUpdate({requests:request1}, pr.getId());

//Preparing the request for Adding Text into cells
var request2=[];
for(var i=0;i<v.length;i++) {
  for(var j=0;j<v[i].length;j++) {

    //Is there a way to get the replies[0].createTable.objectId from the create table request in the same batch update.
    request2.push({"insertText":{"objectId":resp1.replies[0].createTable.objectId,"cellLocation": {"rowIndex":i,"columnIndex":j},"text": v[i][j].toString()}});
  }
}
//Adding text
var resp2=Slides.Presentations.batchUpdate({requests:request2}, pr.getId());

To:

var tableObjectId = "sampleId1";  // Here, the object ID of table is set.

//Create Table
var requests = [{"createTable": {"objectId": tableObjectId, "elementProperties":{"pageObjectId": slide1_ObjectId},"rows": v.length,"columns": v[0].length}}];

//Preparing the request for Adding Text into cells
for(var i=0;i<v.length;i++) {
  for(var j=0;j<v[i].length;j++) {

    //Is there a way to get the replies[0].createTable.objectId from the create table request in the same batch update.
    requests.push({"insertText":{"objectId":tableObjectId,"cellLocation": {"rowIndex":i,"columnIndex":j},"text": v[i][j].toString()}});
  }
}
//Adding text
var resp = Slides.Presentations.batchUpdate({requests:requests}, pr.getId());

In this case, as a sample object ID, var tableObjectId = "sampleId1" is used.

Reference:

CreateTableRequest

If I misunderstood your question and this was not the direction you want, I apologize.


问:
How to stop Spring Boot from adding session cookies?
I have a Spring Boot web application that I'm trying to make stateless.  In my WebSecurityConfigurerAdapter I have set

```<code>    http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
</code>```

But the application (which uses Thymeleaf templates) keeps rewriting URLs for images and scripts by appending ";jsessionid=<some_session_id>" to the file name.  In addition to giving me a cookie I don't want, it also has the annoying side effect that Spring Security blocks the request because it has a semicolon in the URL!

Thymeleaf says this is the intended and desired behavior and says it's not their fault: Thymeleaf merely asks the "Servlet API" to rewrite the URL, and that we should "configure the application at the Tomcat context level" to solve the problem.

So, how do I do that?  I have a custom JWT cookie for authorization so I don't want or need the session cookie at all, certainly not in rewritten URLs.

答:
The jsessionid behavior, has nothing to do with STATELESS.

Initially, the servlet container does not known whether the client (browser) supports cookies, or not.

Therefore, on the first request to the page (typically a HTTP GET):

The servlet container will append the ;jsessionid=... to all URLs.

The servlet container will (try) to set a cookie with the jsessionid.

When clicking on link, or submitting a formular (HTTP GET/POST), the browser will send the cookie back to the server, IF AND ONLY IF, the browser did accept the cookie set in the first place.
Now, the servlet container can identify, whether the jsessionid came from the cookie (transmitted via the HTTP Request Header), or the URL.

If the jsessionid originated from the cookie, the servlet container will stop appending the ;jsessionid=... to the URLs.
If the jsessionid originated from the URL you clicked, it will continue appending the ;jsessionid= to all URLs.

This has nothing to do with STATELESS or any other configuration of the SessionCreationPolicy.

Take a look at the Spring Security documentation for the SessionCreationPolicy:

```<code>/** Always create an {@link HttpSession} */
ALWAYS,
/**
 * Spring Security will never create an {@link HttpSession}, but will use the
 * {@link HttpSession} if it already exists
 */
NEVER,
/** Spring Security will only create an {@link HttpSession} if required */
IF_REQUIRED,
/**
 * Spring Security will never create an {@link HttpSession} and it will never use it
 * to obtain the {@link SecurityContext}
 */
STATELESS
</code>```

Update:

To disable the tracking mode via URL, set following property:

```<code>server.servlet.session.tracking-modes: COOKIE
</code>```

See: https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html

Body:
I have a Spring Boot web application that I'm trying to make stateless.  In my WebSecurityConfigurerAdapter I have set

    http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

But the application (which uses Thymeleaf templates) keeps rewriting URLs for images and scripts by appending ";jsessionid=<some_session_id>" to the file name.  In addition to giving me a cookie I don't want, it also has the annoying side effect that Spring Security blocks the request because it has a semicolon in the URL!

Thymeleaf says this is the intended and desired behavior and says it's not their fault: Thymeleaf merely asks the "Servlet API" to rewrite the URL, and that we should "configure the application at the Tomcat context level" to solve the problem.

So, how do I do that?  I have a custom JWT cookie for authorization so I don't want or need the session cookie at all, certainly not in rewritten URLs.

Body:
The jsessionid behavior, has nothing to do with STATELESS.

Initially, the servlet container does not known whether the client (browser) supports cookies, or not.

Therefore, on the first request to the page (typically a HTTP GET):

The servlet container will append the ;jsessionid=... to all URLs.

The servlet container will (try) to set a cookie with the jsessionid.

When clicking on link, or submitting a formular (HTTP GET/POST), the browser will send the cookie back to the server, IF AND ONLY IF, the browser did accept the cookie set in the first place.
Now, the servlet container can identify, whether the jsessionid came from the cookie (transmitted via the HTTP Request Header), or the URL.

If the jsessionid originated from the cookie, the servlet container will stop appending the ;jsessionid=... to the URLs.
If the jsessionid originated from the URL you clicked, it will continue appending the ;jsessionid= to all URLs.

This has nothing to do with STATELESS or any other configuration of the SessionCreationPolicy.

Take a look at the Spring Security documentation for the SessionCreationPolicy:

/** Always create an {@link HttpSession} */
ALWAYS,
/**
 * Spring Security will never create an {@link HttpSession}, but will use the
 * {@link HttpSession} if it already exists
 */
NEVER,
/** Spring Security will only create an {@link HttpSession} if required */
IF_REQUIRED,
/**
 * Spring Security will never create an {@link HttpSession} and it will never use it
 * to obtain the {@link SecurityContext}
 */
STATELESS

Update:

To disable the tracking mode via URL, set following property:

server.servlet.session.tracking-modes: COOKIE

See: https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html


问:
batch variable exclamation points used in dir | findstr
I'm trying to find files that do not match (at the beginning of the filename) predefined formats contained in a .txt file.

I have the following:

```<code>@Echo off
chcp 1254>nul

setlocal DisableDelayedExpansion

    for /f "usebackq tokens=1,2,3* delims=~" %%f in ("%USERPROFILE%\Desktop\xref.txt") do (
    set "DIRNAME=%%f"
    set "DIRNAM2=^%%f"
    set "PATHNAM=%%h"
    set "ALBUMNM=%%g"
    SETLOCAL EnableDelayedExpansion
    IF EXIST !PATHNAM!!DIRNAME! (
    PushD !PATHNAM!!DIRNAME!
    dir /b /a-d "*" | findstr /v /r /c:"!DIRNAM2! -*"
    )
    ENDLOCAL
    )
    pause
    EXIT /b
</code>```

This works great except with filenames containing bangs (exclamation points).

Here's a sampling of my .txt file (subdirectory~album name~path) which gets generated by a script:

```<code>12 Byzantine Rulers. The History of The Byzantine Empire~12 Byzantine Rulers. The History of The Byzantine Empire~g:\test\
17th Century Poetry~17th Century Poetry~g:\test\
1984 (George Orwell)~1984 (George Orwell)~g:\test\
1_2_1~1_2_1~g:\test\
21st Century American Foreign Policy~21st Century American Foreign Policy~g:\test\
99% Invisible~99% Invisible~g:\test\
Communication Matters. That’s Not What I Meant!~Communication Matters. That’s Not What I Meant!~g:\test\
</code>```

There are hundreds of directories containing hundreds of files (podcasts). I'd like to fix this batch so it can also handle bangs (!).

Thx in advance.

Edit. My test data wasn't robust enough.  The findstr command also doesn't work with (at least) the following characters: é’»¿ ... that is to say PushD gets me to the right directory, but FindStr doesn't do it's culling as expected.

答:
I don't think that the issue is necessarily code page or encoding related, and less so exclamation marks, (bangs). The major issue I see is that your text file content uses smart quotes, (curly), instead of dumb quotes, (straight). Additionally you have % characters which in batch files usually require doubling. For those reasons I would first suggest that you try to replace those characters.

For example:

```<code>@Echo Off
SetLocal DisableDelayedExpansion
For /F "UseBackQ Tokens=1-3 Delims=~" %%G In ("%USERPROFILE%\Desktop\xref.txt")Do (
    Set "SUBDIRN=%%G"
    Set "ALBUMNM=%%H"
    Set "PATHNAM=%%I"
    SetLocal EnableDelayedExpansion
    Set SUBDIRN=!SUBDIRN:%%=%%%%!
    Set ALBUMNM=!ALBUMNM:%%=%%%%!
    Set PATHNAM=!PATHNAM:%%=%%%%!
    Set SUBDIRN=!SUBDIRN:’='!
    Set ALBUMNM=!ALBUMNM:’='!
    Set PATHNAM=!PATHNAM:’='!
    Set SUBDIRN=!SUBDIRN:“="!
    Set ALBUMNM=!ALBUMNM:“="!
    Set PATHNAM=!PATHNAM:“="!
    Set SUBDIRN=!SUBDIRN:”="!
    Set ALBUMNM=!ALBUMNM:”="!
    Set PATHNAM=!PATHNAM:”="!
    If Exist "!PATHNAM!!SUBDIRN!\" (
        PushD "!PATHNAM!!SUBDIRN!"
        Dir /B/A-D|FindStr /IVRC:"^!SUBDIRN! -"
    )
    EndLocal
)
Pause
Exit /B
</code>```

I'm not sure how a copy of this code, within the code box will handle the smart quotes, but I'm sure you'll get the idea.

Body:
I'm trying to find files that do not match (at the beginning of the filename) predefined formats contained in a .txt file.

I have the following:

@Echo off
chcp 1254>nul

setlocal DisableDelayedExpansion

    for /f "usebackq tokens=1,2,3* delims=~" %%f in ("%USERPROFILE%\Desktop\xref.txt") do (
    set "DIRNAME=%%f"
    set "DIRNAM2=^%%f"
    set "PATHNAM=%%h"
    set "ALBUMNM=%%g"
    SETLOCAL EnableDelayedExpansion
    IF EXIST !PATHNAM!!DIRNAME! (
    PushD !PATHNAM!!DIRNAME!
    dir /b /a-d "*" | findstr /v /r /c:"!DIRNAM2! -*"
    )
    ENDLOCAL
    )
    pause
    EXIT /b

This works great except with filenames containing bangs (exclamation points).

Here's a sampling of my .txt file (subdirectory~album name~path) which gets generated by a script:

12 Byzantine Rulers. The History of The Byzantine Empire~12 Byzantine Rulers. The History of The Byzantine Empire~g:\test\
17th Century Poetry~17th Century Poetry~g:\test\
1984 (George Orwell)~1984 (George Orwell)~g:\test\
1_2_1~1_2_1~g:\test\
21st Century American Foreign Policy~21st Century American Foreign Policy~g:\test\
99% Invisible~99% Invisible~g:\test\
Communication Matters. That’s Not What I Meant!~Communication Matters. That’s Not What I Meant!~g:\test\

There are hundreds of directories containing hundreds of files (podcasts). I'd like to fix this batch so it can also handle bangs (!).

Thx in advance.

Edit. My test data wasn't robust enough.  The findstr command also doesn't work with (at least) the following characters: é’»¿ ... that is to say PushD gets me to the right directory, but FindStr doesn't do it's culling as expected.

Body:
I don't think that the issue is necessarily code page or encoding related, and less so exclamation marks, (bangs). The major issue I see is that your text file content uses smart quotes, (curly), instead of dumb quotes, (straight). Additionally you have % characters which in batch files usually require doubling. For those reasons I would first suggest that you try to replace those characters.

For example:

@Echo Off
SetLocal DisableDelayedExpansion
For /F "UseBackQ Tokens=1-3 Delims=~" %%G In ("%USERPROFILE%\Desktop\xref.txt")Do (
    Set "SUBDIRN=%%G"
    Set "ALBUMNM=%%H"
    Set "PATHNAM=%%I"
    SetLocal EnableDelayedExpansion
    Set SUBDIRN=!SUBDIRN:%%=%%%%!
    Set ALBUMNM=!ALBUMNM:%%=%%%%!
    Set PATHNAM=!PATHNAM:%%=%%%%!
    Set SUBDIRN=!SUBDIRN:’='!
    Set ALBUMNM=!ALBUMNM:’='!
    Set PATHNAM=!PATHNAM:’='!
    Set SUBDIRN=!SUBDIRN:“="!
    Set ALBUMNM=!ALBUMNM:“="!
    Set PATHNAM=!PATHNAM:“="!
    Set SUBDIRN=!SUBDIRN:”="!
    Set ALBUMNM=!ALBUMNM:”="!
    Set PATHNAM=!PATHNAM:”="!
    If Exist "!PATHNAM!!SUBDIRN!\" (
        PushD "!PATHNAM!!SUBDIRN!"
        Dir /B/A-D|FindStr /IVRC:"^!SUBDIRN! -"
    )
    EndLocal
)
Pause
Exit /B

I'm not sure how a copy of this code, within the code box will handle the smart quotes, but I'm sure you'll get the idea.


问:
"IDX10511: Signature validation failed" for Azure AD SPA application
I have an SPA application derived from the Identity Platform sample that originally calls a Graph API.

I've changed the endpoint to call a local API.

The SPA uses Azure AD for authentication.

The API sample is derived from the VS 2019 project template for API.

,NET 4.7.2 - no .NET Core.

I can authenticate OK and both ID and access tokens are present when I do a network trace.

However, on the API side I get an error:

```<code>"IDX10511: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey, KeyId: '1E50B4475DAC931359D564309A3385FFAB7FB431', InternalId: 'f61f7746-3cff-4557-8b2c-b47fad9cf1e3'. , KeyId: 1E50B4475DAC931359D564309A3385FFAB7FB431"
</code>```

Decoding the access token shows:

```<code>"{
  "typ": "JWT",
  "nonce": "G0Q6_BuYJUfZaBnX-l1Ox1eoncxXRT4KMThFBcn1-VA",
  "alg": "RS256",
  "x5t": "HlC0R12skxNZ1WQwmjOF_6t_tDE",
  "kid": "HlC0R12skxNZ1WQwmjOF_6t_tDE"
}"
</code>```

Googling this, it appears that the signature fails because of the nonce in the header and this requires "special processing".

All the validation is being done by OWIN.

Any idea what this is or how to fix this?

答:
I didn't think it was a configuration issue because I've never seen any configuration that specifies signature.

So I started looking through msal.js - it's open source.

"User.Read" (the scope defined in the sample I used) is hardcoded in a number of places so I removed this scope from the sample and created a dummy one called "abc".

I also reconfigured Azure AD for the scope change.

Lo and behold, everything worked.

Even more interesting, the header is different:

```<code>{
  "typ": "JWT",
  "alg": "RS256",
  "x5t": "HlC0R12skxNZ1WQwmjOF_6t_tDE",
  "kid": "HlC0R12skxNZ1WQwmjOF_6t_tDE"
}
</code>```

Notice that there is no nonce.

So I suspect that because the original sample used Microsoft Graph, "User.Read" implies some special Graph processing that adds the nonce that screws up the signature.

For reference.

Body:
I have an SPA application derived from the Identity Platform sample that originally calls a Graph API.

I've changed the endpoint to call a local API.

The SPA uses Azure AD for authentication.

The API sample is derived from the VS 2019 project template for API.

,NET 4.7.2 - no .NET Core.

I can authenticate OK and both ID and access tokens are present when I do a network trace.

However, on the API side I get an error:

"IDX10511: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey, KeyId: '1E50B4475DAC931359D564309A3385FFAB7FB431', InternalId: 'f61f7746-3cff-4557-8b2c-b47fad9cf1e3'. , KeyId: 1E50B4475DAC931359D564309A3385FFAB7FB431"

Decoding the access token shows:

"{
  "typ": "JWT",
  "nonce": "G0Q6_BuYJUfZaBnX-l1Ox1eoncxXRT4KMThFBcn1-VA",
  "alg": "RS256",
  "x5t": "HlC0R12skxNZ1WQwmjOF_6t_tDE",
  "kid": "HlC0R12skxNZ1WQwmjOF_6t_tDE"
}"

Googling this, it appears that the signature fails because of the nonce in the header and this requires "special processing".

All the validation is being done by OWIN.

Any idea what this is or how to fix this?

Body:
I didn't think it was a configuration issue because I've never seen any configuration that specifies signature.

So I started looking through msal.js - it's open source.

"User.Read" (the scope defined in the sample I used) is hardcoded in a number of places so I removed this scope from the sample and created a dummy one called "abc".

I also reconfigured Azure AD for the scope change.

Lo and behold, everything worked.

Even more interesting, the header is different:

{
  "typ": "JWT",
  "alg": "RS256",
  "x5t": "HlC0R12skxNZ1WQwmjOF_6t_tDE",
  "kid": "HlC0R12skxNZ1WQwmjOF_6t_tDE"
}

Notice that there is no nonce.

So I suspect that because the original sample used Microsoft Graph, "User.Read" implies some special Graph processing that adds the nonce that screws up the signature.

For reference.


问:
Django: call method after clicking button
I was searching for this answer but none met my expectation. So, In my template I have some content and wanted to add button (which later will add to favorites). After clicking I want to call method from my views.py and redirect to other view.

my views.py

```<code>def home(request):
    //logic here
    request.session['url'] = url
    return render(request,'file.html')

def function_to_call(request):
    ///logic here
    url = request.session.get('url')
    return render(request,'second_file.html',url=url)
</code>```

file.html

```<code><form action="{% url 'function_to_call' %}">
    <button id="submit" type="button" value="Click" />
</form>
</code>```

and in my urls.py

```<code>url(r'^function_to_call/',views.function_to_call,name='function_to_call'),
</code>```

Unfortunately, after clicking on button, nothing happens

答:
If for some reason you need to use a POST request rather than a GET this will work:

```<code><form method="POST" action="{% url 'function_to_call' %}">
    <button id="submit" type="submit" value="Click" />
</form>
</code>```

Using a post can be helpful when you don't want to include data in the querystring because it's a little less secure than having the parameters in the request's body.

Body:
I was searching for this answer but none met my expectation. So, In my template I have some content and wanted to add button (which later will add to favorites). After clicking I want to call method from my views.py and redirect to other view.

my views.py

def home(request):
    //logic here
    request.session['url'] = url
    return render(request,'file.html')

def function_to_call(request):
    ///logic here
    url = request.session.get('url')
    return render(request,'second_file.html',url=url)

file.html

<form action="{% url 'function_to_call' %}">
    <button id="submit" type="button" value="Click" />
</form>

and in my urls.py

url(r'^function_to_call/',views.function_to_call,name='function_to_call'),

Unfortunately, after clicking on button, nothing happens

Body:
If for some reason you need to use a POST request rather than a GET this will work:

<form method="POST" action="{% url 'function_to_call' %}">
    <button id="submit" type="submit" value="Click" />
</form>

Using a post can be helpful when you don't want to include data in the querystring because it's a little less secure than having the parameters in the request's body.


问:
Django REST framework - Serializer relations User.username
Im working on a django project, and I have a model that looks like this:

```<code>class Comment(models.Model):
    user            = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,on_delete=models.CASCADE)
    slug            = models.SlugField(unique=True,null=True, blank=True)
    content_type    = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id       = models.PositiveIntegerField()
    content_object  = GenericForeignKey('content_type', 'object_id')
    parent          = models.ForeignKey("self", null=True, blank=True,on_delete=models.CASCADE)
    content         = models.TextField()
    timestamp       = models.DateTimeField(auto_now_add=True)

    objects = CommentManager()

    def __str__(self):
        return str(self.user.username)
</code>```

I use this serializer:

```<code>class CommentDetailSerializer(ModelSerializer):
    user = SerializerMethodField()
    replies = SerializerMethodField()
    class Meta:
        model = Comment
        fields = [
            'user',
            'content',
            'replies',
            'timestamp'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_replies(self,obj):
        if obj.is_parent:
            return CommentChildSerializer(obj.children(),many=True).data
</code>```

for this view:

```<code>class CommentDetailApiView(RetrieveAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentDetailSerializer
    lookup_field = 'slug'
</code>```

here is the PostSerializer I use,

```<code>class PostSerializer(ModelSerializer):
    user = SerializerMethodField()
    comments = SerializerMethodField()
    class Meta:
        model = Post
        fields = [
            'user',
            'title',
            'content',
            'comments'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_comments(self,obj):
        comments_qs = Comment.objects.filter_by_instance(obj)
        comments = CommentSerializer(comments_qs, many=True).data
        return comments
</code>```

this is what I get in the PostDetailAPIView:

```<code>{
    "user": "abc",
    "title": "blabla",
    "content": "bla",
    "comments": [
        {
            "user": 1,
            "content": "hey",
            "timestamp": "2020-02-18T00:07:29.932850Z"
        }
    ]
}
</code>```

How do I get the comment user username instead of its id?

I get the username of the comment user only in the CommentDetailApiView.

Thank you

答:
StringRelatedField may be used to represent the target of the relationship using its __str__ method.

For example, the following serializer.

```<code>class CommentDetailSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField()
    ...

    class Meta:
        model = Comment
        fields = [
            'user',
            'content',
            'replies',
            'timestamp'
        ]
        ...
</code>```

Body:
Im working on a django project, and I have a model that looks like this:

class Comment(models.Model):
    user            = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,on_delete=models.CASCADE)
    slug            = models.SlugField(unique=True,null=True, blank=True)
    content_type    = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id       = models.PositiveIntegerField()
    content_object  = GenericForeignKey('content_type', 'object_id')
    parent          = models.ForeignKey("self", null=True, blank=True,on_delete=models.CASCADE)
    content         = models.TextField()
    timestamp       = models.DateTimeField(auto_now_add=True)

    objects = CommentManager()

    def __str__(self):
        return str(self.user.username)

I use this serializer:

class CommentDetailSerializer(ModelSerializer):
    user = SerializerMethodField()
    replies = SerializerMethodField()
    class Meta:
        model = Comment
        fields = [
            'user',
            'content',
            'replies',
            'timestamp'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_replies(self,obj):
        if obj.is_parent:
            return CommentChildSerializer(obj.children(),many=True).data

for this view:

class CommentDetailApiView(RetrieveAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentDetailSerializer
    lookup_field = 'slug'

here is the PostSerializer I use,

class PostSerializer(ModelSerializer):
    user = SerializerMethodField()
    comments = SerializerMethodField()
    class Meta:
        model = Post
        fields = [
            'user',
            'title',
            'content',
            'comments'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_comments(self,obj):
        comments_qs = Comment.objects.filter_by_instance(obj)
        comments = CommentSerializer(comments_qs, many=True).data
        return comments

this is what I get in the PostDetailAPIView:

{
    "user": "abc",
    "title": "blabla",
    "content": "bla",
    "comments": [
        {
            "user": 1,
            "content": "hey",
            "timestamp": "2020-02-18T00:07:29.932850Z"
        }
    ]
}

How do I get the comment user username instead of its id?

I get the username of the comment user only in the CommentDetailApiView.

Thank you

Body:
StringRelatedField may be used to represent the target of the relationship using its __str__ method.

For example, the following serializer.

class CommentDetailSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField()
    ...

    class Meta:
        model = Comment
        fields = [
            'user',
            'content',
            'replies',
            'timestamp'
        ]
        ...


问:
nginx - two subdomain configuration
I'm new to Nginx and I'm trying to get subdomains working.

What I would like to do is take my domain (let's call it example.com) and add:

sub1.example.com,

sub2.example.com, and also have

www.example.com available.

I know how to do this with Apache, but Nginx is being a real head scratcher.

I'm running Debian 6.

My current /etc/nginx/sites-enabled/example.com:

```<code>server {
    server_name www.example.com example.com;
    access_log /srv/www/www.example.com/logs/access.log;
    error_log /srv/www/www.example.com/logs/error.log;
    root /srv/www/www.example.com/public_html;

    location / {
        index  index.html index.htm;
    }

    location ~ \.php$ {
        include /etc/nginx/fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
    }
}
</code>```

It is working to serve example.com and www.example.com.

I have tried to add a second server block in the same file like:

```<code>server {
        server_name www.example.com example.com;
        access_log /srv/www/www.example.com/logs/access.log;
        error_log /srv/www/www.example.com/logs/error.log;
        root /srv/www/www.example.com/public_html;

        server {
            server_name sub1.example.com;
            access_log /srv/www/example.com/logs/sub1-access.log;
            error_log /srv/www/example.com/logs/sub1-error.log;
            root /srv/www/example.com/sub1;
    }
        location / {
            index  index.html index.htm;
        }

        location ~ \.php$ {
            include /etc/nginx/fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
        }
}
</code>```

No luck. Any ideas? I'd super appreciate any feedback.

答:
There is a very customizable solution, depending on your server implementation:

Two (or more) SUBdomains in a single nginx "sites" file? Good if you own a wildcard TLS certificate, thus want to maintain ONE nginx config file. All using same services BUT different ports? (Think of different app versions running concurrently, each listening locally to differents ports)

```<code>server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ~^(?<sub>.+).example.com;

    # default app (the "default" ports, good for the "old" app)
    set $app 19069;
    set $app-chat 19072;

    # new app
    # new.example.com
    if ( $sub = "new" ) {
        set $app 18069;
        set $app-chat 18072;
    }
    # upstreaming
    location / {
        proxy_redirect off;
        proxy_pass http://127.0.0.1:$app;
    }

    location /longpolling {
        proxy_pass http://127.0.0.1:$app-chat;
    }
</code>```

I know the performance will "suck", but then again, since the decision was to go with one server for all it's like complaining that an econobox cannot haul as much people as a bus because the little car has a "heavy" roof rack on top of it.

A regex expert could potentially improve the performance for such a custom solution, specially since it could ommit the CPU expensive "if" conditional statements.

Title: nginx - two subdomain configuration

Body:
I'm new to Nginx and I'm trying to get subdomains working.

What I would like to do is take my domain (let's call it example.com) and add:

sub1.example.com,

sub2.example.com, and also have

www.example.com available.

I know how to do this with Apache, but Nginx is being a real head scratcher.

I'm running Debian 6.

My current /etc/nginx/sites-enabled/example.com:

server {
    server_name www.example.com example.com;
    access_log /srv/www/www.example.com/logs/access.log;
    error_log /srv/www/www.example.com/logs/error.log;
    root /srv/www/www.example.com/public_html;

    location / {
        index  index.html index.htm;
    }

    location ~ \.php$ {
        include /etc/nginx/fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
    }
}

It is working to serve example.com and www.example.com.

I have tried to add a second server block in the same file like:

server {
        server_name www.example.com example.com;
        access_log /srv/www/www.example.com/logs/access.log;
        error_log /srv/www/www.example.com/logs/error.log;
        root /srv/www/www.example.com/public_html;

        server {
            server_name sub1.example.com;
            access_log /srv/www/example.com/logs/sub1-access.log;
            error_log /srv/www/example.com/logs/sub1-error.log;
            root /srv/www/example.com/sub1;
    }
        location / {
            index  index.html index.htm;
        }

        location ~ \.php$ {
            include /etc/nginx/fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
        }
}

No luck. Any ideas? I'd super appreciate any feedback.

Body:
There is a very customizable solution, depending on your server implementation:

Two (or more) SUBdomains in a single nginx "sites" file? Good if you own a wildcard TLS certificate, thus want to maintain ONE nginx config file. All using same services BUT different ports? (Think of different app versions running concurrently, each listening locally to differents ports)

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ~^(?<sub>.+).example.com;

    # default app (the "default" ports, good for the "old" app)
    set $app 19069;
    set $app-chat 19072;

    # new app
    # new.example.com
    if ( $sub = "new" ) {
        set $app 18069;
        set $app-chat 18072;
    }
    # upstreaming
    location / {
        proxy_redirect off;
        proxy_pass http://127.0.0.1:$app;
    }

    location /longpolling {
        proxy_pass http://127.0.0.1:$app-chat;
    }

I know the performance will "suck", but then again, since the decision was to go with one server for all it's like complaining that an econobox cannot haul as much people as a bus because the little car has a "heavy" roof rack on top of it.

A regex expert could potentially improve the performance for such a custom solution, specially since it could ommit the CPU expensive "if" conditional statements.