问:
Links floating to the left?
Many of the links on my site are ignoring css rules and floating to the left. It's just the links, the other text seems fine. You can see here, https://adsler.co.uk/dating/ under terms and conditions on mobile view, or in the Privacy Policy page, between you and Adsler.co.uk. By registering, you are agreeing that we will process you data in accordance with our Privacy Policy,
Terms and Conditions
and
Cookie Policy https://adsler.co.uk/privacy-policy/

Aside from them being very naughty links :-) what's causing this and how to rectify?

I have this html from f12 which is the only thing i could identify as potential cause. Unable to supply css because not sure what's causing it?

```<code><div class= "entry-content" >
<p> Text <p>
<p dir="ltr">
Text...
</code>```

答:
This is because you have defined the display:block; property on the anchor tag.

You need to change the anchor property to display:inline-block; or you can
override the anchor property with class inherit.

```<code>.entry-content a
{
  display:inline-block;
}
</code>```

I hope it will work for you!

Title: Links floating to the left?

Body:
Many of the links on my site are ignoring css rules and floating to the left. It's just the links, the other text seems fine. You can see here, https://adsler.co.uk/dating/ under terms and conditions on mobile view, or in the Privacy Policy page, between you and Adsler.co.uk. By registering, you are agreeing that we will process you data in accordance with our Privacy Policy,
Terms and Conditions
and
Cookie Policy https://adsler.co.uk/privacy-policy/

Aside from them being very naughty links :-) what's causing this and how to rectify?

I have this html from f12 which is the only thing i could identify as potential cause. Unable to supply css because not sure what's causing it?

 Text

Text...

Body:
This is because you have defined the display:block; property on the anchor tag.

You need to change the anchor property to display:inline-block; or you can
override the anchor property with class inherit.

.entry-content a
{
  display:inline-block;
}

I hope it will work for you!


来源: stackexchange

问:
YAML header of markdown file generates odd table on top of document
I get a weird output from my YAML header which I do not intend.
Instead I expect the normal output with title, author and the table of contents of course.

The following code produces the following output:

```<code>---
title: General Stuff
author: Me
output:
    html_document:
    toc: true # table of content true
    toc_depth: 3  # upto three depths of headings (specified by #, ## and ###)
    number_sections: true  ## if you want number sections at each table header
    theme: united
---
</code>```

generates this output:

I got this output from GitHub where the file is displayed. Maybe the issue is that GitHub uses some interesting markdown version...?

答:
Maybe the issue is that GitHub uses some interesting markdown version...?

YAML frontmatter isn't part of Markdown itself. A regular Markdown processor wouldn't do anything special with it. It would probably render a
 and some text, maybe ending with a header.

But yes, GitHub treats YAML front matter specially:

Many blogging websites, like Jekyll with GitHub Pages, depend on
  some YAML-formatted metadata at the beginning of your post. You know, the stuff that goes between dashes like this:

```<code>---
title: Blogging Like a Boss
---
</code>```

Starting [September 27, 2013], we’ll render this metadata within GitHub as an
  horizontal table, for easier reading

ContentLicense: CC BY-SA 4.0

Body:
I get a weird output from my YAML header which I do not intend.
Instead I expect the normal output with title, author and the table of contents of course.

The following code produces the following output:

---
title: General Stuff
author: Me
output:
    html_document:
    toc: true # table of content true
    toc_depth: 3  # upto three depths of headings (specified by #, ## and ###)
    number_sections: true  ## if you want number sections at each table header
    theme: united
---

generates this output:

I got this output from GitHub where the file is displayed. Maybe the issue is that GitHub uses some interesting markdown version...?

Body:
Maybe the issue is that GitHub uses some interesting markdown version...?

YAML frontmatter isn't part of Markdown itself. A regular Markdown processor wouldn't do anything special with it. It would probably render a <hr> and some text, maybe ending with a header.

But yes, GitHub treats YAML front matter specially:

Many blogging websites, like Jekyll with GitHub Pages, depend on
  some YAML-formatted metadata at the beginning of your post. You know, the stuff that goes between dashes like this:

---
title: Blogging Like a Boss
---

Starting [September 27, 2013], we’ll render this metadata within GitHub as an
  horizontal table, for easier reading


问:
Update row in TABLE1 using value from another row in TABLE1 to lookup value in TABLE2
I have a table as follows

TABLE1

```<code>Id   UserId  Type       Value
1    AAA     companyid  123
2    AAA     branchid
3    BBB     companyid  124
4    BBB     branchid
5    CCC     companyid  125
6    CCC     branchid
</code>```

and TABLE2

```<code>BranchId   CompanyId   Name
1          123         RedBranch
2          123         YellowBranch
3          123         GreenBranch
4          124         SouthBranch
5          125         NorthBranch
</code>```

I need to update Type in TABLE1 WHERE Type = 'branchid' using the value in Type = 'companyid' for the same UserId.  Once I have the correct 'companyid' I want to use the following SELECT to get the TOP BranchId from TABLE2

```<code>SELECT TOP 1 Id
FROM TABLE2
WHERE CompanyId = (correct companyid from TABLE1)
ORDER BY Id DESC
</code>```

How can I achieve this in one Update statement?

答:
I'm not sure that I fully understand the quesion, but maybe...</p>

```<code>with maxBranch as
(
select
     max(BranchId) as BranchId
    ,CompanyId
from TABLE2
group by CompanyId
)
update t1
set t1.Value = m.BranchID
from TABLE1 as t1
join TABLE1 as t11
    on t1.UserId = t11.UserId
    and t1.Type = 'branchid'
    and t11.Type = 'companyid'
join maxBranch as m
    on m.CompanyId = t11.Value
</code>```

Body:
I have a table as follows

TABLE1

Id   UserId  Type       Value
1    AAA     companyid  123
2    AAA     branchid
3    BBB     companyid  124
4    BBB     branchid
5    CCC     companyid  125
6    CCC     branchid

and TABLE2

BranchId   CompanyId   Name
1          123         RedBranch
2          123         YellowBranch
3          123         GreenBranch
4          124         SouthBranch
5          125         NorthBranch

I need to update Type in TABLE1 WHERE Type = 'branchid' using the value in Type = 'companyid' for the same UserId.  Once I have the correct 'companyid' I want to use the following SELECT to get the TOP BranchId from TABLE2

SELECT TOP 1 Id
FROM TABLE2
WHERE CompanyId = (correct companyid from TABLE1)
ORDER BY Id DESC

How can I achieve this in one Update statement?

Body:
I'm not sure that I fully understand the quesion, but maybe...

with maxBranch as
(
select
     max(BranchId) as BranchId
    ,CompanyId
from TABLE2
group by CompanyId
)
update t1
set t1.Value = m.BranchID
from TABLE1 as t1
join TABLE1 as t11
    on t1.UserId = t11.UserId
    and t1.Type = 'branchid'
    and t11.Type = 'companyid'
join maxBranch as m
    on m.CompanyId = t11.Value


问:
Show div using onclick on an a tag
i try to show my div using  onclick but my funciton doesnt run when i click it
  here is my code </p>

```<code>     <script>
       function BxhNam() {
         document.getElementById("#Top5").style.display = "block";
     }
     </script>
<a href="javascript:void(0);" class="dropdown-item" onclick="return BxhNam();">Theo Năm</a>
<div id="Top5" style="display:none">
 <span>Content</span>
</div>
</code>```

答:
The 'getElementById()' method returns the element that has the ID attribute with the specified value. When you want to select an element with js selector by id you just must set an id with same id that was set as attribute(id) in html.
for select element by id "Top5" :

```<code>document.getElementById("Top5")
</code>```

and in you code :

```<code><script>
     function BxhNam() {
         document.getElementById("Top5").style.display = "block";
     }
</script>
<a href="javascript:void(0);" class="dropdown-item" onclick="return BxhNam();">Theo Năm</a>
<div id="Top5" style="display:none">
  <span>Content</span>
</div>
</code>```

Title: Show div using onclick on an a tag

Body:
i try to show my div using  onclick but my funciton doesnt run when i click it
  here is my code

Theo Năm

 Content

Body:
The 'getElementById()' method returns the element that has the ID attribute with the specified value. When you want to select an element with js selector by id you just must set an id with same id that was set as attribute(id) in html.
for select element by id "Top5" :

document.getElementById("Top5")

and in you code :

<script>
     function BxhNam() {
         document.getElementById("Top5").style.display = "block";
     }
</script>
<a href="javascript:void(0);" class="dropdown-item" onclick="return BxhNam();">Theo Năm</a>
<div id="Top5" style="display:none">
  <span>Content</span>
</div>


问:
How to deserialize BIG JSON data into DataGridView
I´d like to deserialize a big JSON File (~600MB) into DataGridView without facing "maxJsonLength" Error.

My Code is working fine for small JSON files. But for bigger JSON files I get the "maxJsonLength" Error. Is there a workaround or an easy way to solve this problem since I am not the most experienced coder?

```<code>Private Sub BtnOpenFile_Click(sender As Object, e As EventArgs) Handles BtnOpenFileOld.Click
        OpenFileDialog1.InitialDirectory = "C:\"

        If OpenFileDialog1.ShowDialog = DialogResult.Cancel Then
        End If

        Dim JSonFilePath As String = File.ReadAllText(OpenFileDialog1.FileName)
        LblFilePath.Text = OpenFileDialog1.FileName

        DataGridView1.Rows.Clear()
        DataGridView1.Refresh()

        Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(JSonFilePath)

        For Each item As Object In dict
            DataGridView1.Rows.Add(item("EMail").ToString, item("Timestamp").ToString, item("Number").ToString)
        Next

    End Sub
</code>```

My JSON File looks like

```<code>[
  {
    "EMail": "one@mail.com",
    "Timestamp": "2019-05-25T21:24:06.799381+02:00",
    "Number": 206074,
    "randomtrash1": "notneeded",
    "randomtrash2": "notneeded",
    "randomtrash3": "notneeded",
    "randomtrash4": "notneeded",
    "randomtrash5": "notneeded",
    "randomtrash6": "notneeded",
    "randomtrash7": "notneeded",
    "randomtrash8": "notneeded",
    "randomtrash9": "notneeded"
  },
  {
    "EMail": "two@mail.com",
    "Timestamp": "2019-05-25T21:24:06.8273826+02:00",
    "Number": 7397,
    "randomtrash1": "notneeded",
    "randomtrash2": "notneeded",
    "randomtrash3": "notneeded",
    "randomtrash4": "notneeded",
    "randomtrash5": "notneeded",
    "randomtrash6": "notneeded",
    "randomtrash7": "notneeded",
    "randomtrash8": "notneeded",
    "randomtrash9": "notneeded",
    "randomtrash10": "notneeded",
    "randomtrash11": "notneeded",
    "randomtrash12": "notneeded",
    "randomtrash13": "notneeded",
    "randomtrash14": "notneeded",
    "randomtrash15": "notneeded",
    "randomtrash16": "notneeded",
    "randomtrash17": "notneeded",
    "randomtrash18": "notneeded",
    "randomtrash19": "notneeded",
    "randomtrash20": "notneeded",
    "randomtrash21": "notneeded"
  }
]

</code>```

答:
```<code>Imports Newtonsoft.Json

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim str As String = _
            "[" + _
            "  {" + _
            "    ""EMail"": ""one@mail.com""," + _
            "    ""Timestamp"": ""2019-05-25T21:24:06.799381+02:00""," + _
            "    ""Number"": 206074," + _
            "  }," + _
            "  {" + _
            "    ""EMail"": ""two@mail.com""," + _
            "    ""Timestamp"": ""2019-05-25T21:24:06.8273826+02:00""," + _
            "    ""Number"": 7397," + _
            "  }," + _
            "]"

    Try
        Dim list As List(Of jsnn) = JsonConvert.DeserializeObject(Of List(Of jsnn))(str)

        For Each item As jsnn In list
            Console.WriteLine(item.EMail & ": " & item.Timestamp & ": " & item.Number)
        Next

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub

End Class

Public Class jsnn
    Public Property EMail As String
    Public Property Timestamp As DateTime
    Public Property Number As Integer
End Class
</code>```

here's a screenshot

Body:
I´d like to deserialize a big JSON File (~600MB) into DataGridView without facing "maxJsonLength" Error.

My Code is working fine for small JSON files. But for bigger JSON files I get the "maxJsonLength" Error. Is there a workaround or an easy way to solve this problem since I am not the most experienced coder?

Private Sub BtnOpenFile_Click(sender As Object, e As EventArgs) Handles BtnOpenFileOld.Click
        OpenFileDialog1.InitialDirectory = "C:\"

        If OpenFileDialog1.ShowDialog = DialogResult.Cancel Then
        End If

        Dim JSonFilePath As String = File.ReadAllText(OpenFileDialog1.FileName)
        LblFilePath.Text = OpenFileDialog1.FileName

        DataGridView1.Rows.Clear()
        DataGridView1.Refresh()

        Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(JSonFilePath)

        For Each item As Object In dict
            DataGridView1.Rows.Add(item("EMail").ToString, item("Timestamp").ToString, item("Number").ToString)
        Next

    End Sub

My JSON File looks like

[
  {
    "EMail": "one@mail.com",
    "Timestamp": "2019-05-25T21:24:06.799381+02:00",
    "Number": 206074,
    "randomtrash1": "notneeded",
    "randomtrash2": "notneeded",
    "randomtrash3": "notneeded",
    "randomtrash4": "notneeded",
    "randomtrash5": "notneeded",
    "randomtrash6": "notneeded",
    "randomtrash7": "notneeded",
    "randomtrash8": "notneeded",
    "randomtrash9": "notneeded"
  },
  {
    "EMail": "two@mail.com",
    "Timestamp": "2019-05-25T21:24:06.8273826+02:00",
    "Number": 7397,
    "randomtrash1": "notneeded",
    "randomtrash2": "notneeded",
    "randomtrash3": "notneeded",
    "randomtrash4": "notneeded",
    "randomtrash5": "notneeded",
    "randomtrash6": "notneeded",
    "randomtrash7": "notneeded",
    "randomtrash8": "notneeded",
    "randomtrash9": "notneeded",
    "randomtrash10": "notneeded",
    "randomtrash11": "notneeded",
    "randomtrash12": "notneeded",
    "randomtrash13": "notneeded",
    "randomtrash14": "notneeded",
    "randomtrash15": "notneeded",
    "randomtrash16": "notneeded",
    "randomtrash17": "notneeded",
    "randomtrash18": "notneeded",
    "randomtrash19": "notneeded",
    "randomtrash20": "notneeded",
    "randomtrash21": "notneeded"
  }
]

Body:
Imports Newtonsoft.Json

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim str As String = _
            "[" + _
            "  {" + _
            "    ""EMail"": ""one@mail.com""," + _
            "    ""Timestamp"": ""2019-05-25T21:24:06.799381+02:00""," + _
            "    ""Number"": 206074," + _
            "  }," + _
            "  {" + _
            "    ""EMail"": ""two@mail.com""," + _
            "    ""Timestamp"": ""2019-05-25T21:24:06.8273826+02:00""," + _
            "    ""Number"": 7397," + _
            "  }," + _
            "]"

    Try
        Dim list As List(Of jsnn) = JsonConvert.DeserializeObject(Of List(Of jsnn))(str)

        For Each item As jsnn In list
            Console.WriteLine(item.EMail & ": " & item.Timestamp & ": " & item.Number)
        Next

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub

End Class

Public Class jsnn
    Public Property EMail As String
    Public Property Timestamp As DateTime
    Public Property Number As Integer
End Class

here's a screenshot


问:
Changing a small region of my texture causes the rest of the texture to go black
I have an application that does some calculations on the CPU on multiple threads. Each thread calculates a 64x64 pixel region of an output image. When a thread has completed its calculations, it uploads the calculated pixel data to a MTLTexture via -[MTLTexture replaceRegion:]. Before any of the CPU threads start, I have placed a low-res version of the full result into the texture, and I'd like for the threads on the CPU to overwrite the image data as they calculate it at a higher resolution.

I have this working for the most part, but when the first call to -replaceRegion: happens, it appears to clear the texture to black, and then replaces the 64x64 region as requested.

Here's how I'm creating the texture:

```<code>MTLTextureDescriptor*   outputTextureDesc   = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
                                                                                width:viewportSize.width
                                                                                height:viewportSize.height
                                                                                mipmapped:NO];
outputTextureDesc.usage = MTLTextureUsageShaderWrite | MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget;
_outputTexture = [device newTextureWithDescriptor:outputTextureDesc];
</code>```

Then, when I want to put the low-res version of the output into the texture, I copy it from another texture like this:

```<code>const Vertex2D quadVertices[] =
{
    //Pixel Positions, Texture Coordinates
    { { viewportSize.x / 2.0,  viewportSize.y / -2.0 }, { right, bottom } },
    { { viewportSize.x / -2.0, viewportSize.y / -2.0 }, { left, bottom } },
    { { viewportSize.x / -2.0, viewportSize.y / 2.0 }, { left, top } },

    { { viewportSize.x / 2.0,  viewportSize.y / -2.0 }, { right, bottom } },
    { { viewportSize.x / -2.0, viewportSize.y / 2.0 }, { left, top } },
    { { viewportSize.x / 2.0, viewportSize.y / 2.0 }, { right, top } },
};

MTLRenderPassDescriptor *renderPassDescriptor = [MTLRenderPassDescriptor renderPassDescriptor];
renderPassDescriptor.colorAttachments [ 0 ].texture = _outputTexture;
renderPassDescriptor.colorAttachments [ 0 ].loadAction = MTLLoadActionDontCare;
renderPassDescriptor.colorAttachments [ 0 ].storeAction = MTLStoreActionStore;

if(renderPassDescriptor != nil)
{
    id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
    commandBuffer.label = @"Copy Selection Command Buffer";

    // Create a render command encoder so we can render into something
    id<MTLRenderCommandEncoder> renderEncoder =
        [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
    renderEncoder.label = @"Copy Selection Command Encoder";

    [renderEncoder setViewport:(MTLViewport){0.0, 0.0, viewportSize.x, viewportSize.y, -1.0, 1.0 }];

    [renderEncoder setRenderPipelineState:renderPipelineState];

    [renderEncoder setVertexBytes:quadVertices
                           length:sizeof(quadVertices)
                          atIndex:MBV_VertexIndex];

    [renderEncoder setVertexBytes:&viewportSize
                           length:sizeof(viewportSize)
                          atIndex:MBV_ViewportSize];

    [renderEncoder setFragmentTexture:oldRender
                              atIndex:MBF_Texture];

    // Draw the vertices of our triangles
    [renderEncoder drawPrimitives:MTLPrimitiveTypeTriangle
                      vertexStart:0
                      vertexCount:6];

    [renderEncoder endEncoding];
    [commandBuffer commit];
    [commandBuffer waitUntilCompleted];
}
</code>```

I also tried changing the renderPassDescriptor.colorAttachment [ 0 ].loadAction to MTLLoadActionLoad instead of MTLLoadActionDontCare, as the docs says:

The existing contents of the texture are preserved.

but it didn't make any difference.

Finally, when a thread finishes, it uploads its 64x64 pixel result by doing this:

```<code>MTLRegion currentRegion = { { colStart, rowStart, 0}, { colEnd - colStart, rowEnd - rowStart, 1 } };
[_outputTexture replaceRegion:currentRegion
                  mipmapLevel:0
                    withBytes:_outputBitmap + (rowStart * (int)viewportSize.width) + colStart
                  bytesPerRow:viewportSize.width * sizeof(*_outputBitmap)];
</code>```

If I use the Metal debugging tools to look at the texture after the initial copy of the low-res data, it contains the correct pixels. But after the first call to -replaceRegion:, everything other than the region replaced is black. Subsequent calls to -replaceRegion: work correctly and do not overwrite the previously written results.

I should mention that this texture is also being displayed as it's updated  by an MTKView. I do sometimes see the low-res copy for a frame or two before the high-res tiles start filling in. Any idea why the call to -replaceRegion: would clear the texture? (Or what else might be clearing the texture if it's not the call to -replaceRegion:?)

答:
Assuming this is on macOS and not iOS, the texture's storage mode defaults to MTLStorageModeManaged. That means that you must explicitly synchronize the texture to get the CPU to "see" any modifications made by the GPU. Since your initial low-resolution image is drawn into the texture, that's only on the GPU unless/until you synchronize. Since you're failing to do that, the CPU has uninitialized data. When you use the CPU to replace a region, it's modifying its (uninitialized) copy and then pushing that to the GPU. That replaces the drawn content.

To synchronize, you should create a blit command encoder (MTLBlitCommandEncoder) and use that to encode a synchronization command using -synchronizeResource: or (if you want to be more selective) -synchronizeTexture:slice:level:.

Finally, I'm not sure, but I'd be concerned about the thread safety of the various -replaceRegion:... calls. So, you should use a serial dispatch queue or something to serialize those.

Body:
I have an application that does some calculations on the CPU on multiple threads. Each thread calculates a 64x64 pixel region of an output image. When a thread has completed its calculations, it uploads the calculated pixel data to a MTLTexture via -[MTLTexture replaceRegion:]. Before any of the CPU threads start, I have placed a low-res version of the full result into the texture, and I'd like for the threads on the CPU to overwrite the image data as they calculate it at a higher resolution.

I have this working for the most part, but when the first call to -replaceRegion: happens, it appears to clear the texture to black, and then replaces the 64x64 region as requested.

Here's how I'm creating the texture:

MTLTextureDescriptor*   outputTextureDesc   = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
                                                                                width:viewportSize.width
                                                                                height:viewportSize.height
                                                                                mipmapped:NO];
outputTextureDesc.usage = MTLTextureUsageShaderWrite | MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget;
_outputTexture = [device newTextureWithDescriptor:outputTextureDesc];

Then, when I want to put the low-res version of the output into the texture, I copy it from another texture like this:

const Vertex2D quadVertices[] =
{
    //Pixel Positions, Texture Coordinates
    { { viewportSize.x / 2.0,  viewportSize.y / -2.0 }, { right, bottom } },
    { { viewportSize.x / -2.0, viewportSize.y / -2.0 }, { left, bottom } },
    { { viewportSize.x / -2.0, viewportSize.y / 2.0 }, { left, top } },

    { { viewportSize.x / 2.0,  viewportSize.y / -2.0 }, { right, bottom } },
    { { viewportSize.x / -2.0, viewportSize.y / 2.0 }, { left, top } },
    { { viewportSize.x / 2.0, viewportSize.y / 2.0 }, { right, top } },
};

MTLRenderPassDescriptor *renderPassDescriptor = [MTLRenderPassDescriptor renderPassDescriptor];
renderPassDescriptor.colorAttachments [ 0 ].texture = _outputTexture;
renderPassDescriptor.colorAttachments [ 0 ].loadAction = MTLLoadActionDontCare;
renderPassDescriptor.colorAttachments [ 0 ].storeAction = MTLStoreActionStore;

if(renderPassDescriptor != nil)
{
    id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
    commandBuffer.label = @"Copy Selection Command Buffer";

    // Create a render command encoder so we can render into something
    id<MTLRenderCommandEncoder> renderEncoder =
        [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
    renderEncoder.label = @"Copy Selection Command Encoder";

    [renderEncoder setViewport:(MTLViewport){0.0, 0.0, viewportSize.x, viewportSize.y, -1.0, 1.0 }];

    [renderEncoder setRenderPipelineState:renderPipelineState];

    [renderEncoder setVertexBytes:quadVertices
                           length:sizeof(quadVertices)
                          atIndex:MBV_VertexIndex];

    [renderEncoder setVertexBytes:&viewportSize
                           length:sizeof(viewportSize)
                          atIndex:MBV_ViewportSize];

    [renderEncoder setFragmentTexture:oldRender
                              atIndex:MBF_Texture];

    // Draw the vertices of our triangles
    [renderEncoder drawPrimitives:MTLPrimitiveTypeTriangle
                      vertexStart:0
                      vertexCount:6];

    [renderEncoder endEncoding];
    [commandBuffer commit];
    [commandBuffer waitUntilCompleted];
}

I also tried changing the renderPassDescriptor.colorAttachment [ 0 ].loadAction to MTLLoadActionLoad instead of MTLLoadActionDontCare, as the docs says:

The existing contents of the texture are preserved.

but it didn't make any difference.

Finally, when a thread finishes, it uploads its 64x64 pixel result by doing this:

MTLRegion currentRegion = { { colStart, rowStart, 0}, { colEnd - colStart, rowEnd - rowStart, 1 } };
[_outputTexture replaceRegion:currentRegion
                  mipmapLevel:0
                    withBytes:_outputBitmap + (rowStart * (int)viewportSize.width) + colStart
                  bytesPerRow:viewportSize.width * sizeof(*_outputBitmap)];

If I use the Metal debugging tools to look at the texture after the initial copy of the low-res data, it contains the correct pixels. But after the first call to -replaceRegion:, everything other than the region replaced is black. Subsequent calls to -replaceRegion: work correctly and do not overwrite the previously written results.

I should mention that this texture is also being displayed as it's updated  by an MTKView. I do sometimes see the low-res copy for a frame or two before the high-res tiles start filling in. Any idea why the call to -replaceRegion: would clear the texture? (Or what else might be clearing the texture if it's not the call to -replaceRegion:?)


问:
How do I get Flask to serve my .js files?
I am doing some coding with Python, Flask and .js files all with some HTML and CSS linked in as well. My problem is that I have a dropdown menu and a button that can hide and unhide password text but when running in Flask, this side of things is not working and I believe that it has something to do with the javascript. This function works perfectly when I am running the HTML file locally and not through flask, but I am completely lost as to where to go from here?

In terms of what I have done already is to ensure that my file structure is correct and that these .js files are within the static folder (where CSS stylesheets are being pulled from perfectly fine). My script tags where I link the .js files are all at the end of the body tag and do not sit within the head tag.

```<code><script src="../static/js/vendor/jquery.js"></script>
<script src="../static/js/app.js"></script>
<script src="../static/js/vendor/foundation.js"></script>
<script src="../static/js/vendor/what-input.js"></script>
</code>```

This is the app file that I am using for Flask and the simple code used to run this if it helps?

```<code>from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route("/")

def render_static():

    return render_template('splash_page.html')

@app.route("/account")

def account_page():

    return render_template('account.html')

if __name__ == '__main__':
    app.run(debug = True)
</code>```

Below you will find my HTML code used as a template in Flask, this is it before the changes suggested below -

```<code><!doctype html>
<html class="no-js" lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>

    <link href="../static/css/app.css" rel="stylesheet" type="text/css">
    <link href="../static/css/foundation.css" rel="stylesheet" type="text/css">

  </head>

  <body>
    <div class="top-bar">
  <div class="top-bar-left">
    <ul class="dropdown menu" data-dropdown-menu>
      <li class="menu-text">Premier League Pro</li>
      <li>
        <a href="/account">Account</a>
        <ul class="menu vertical">
          <li><a href="/my account">My Account</a></li>
          <li><a href="#">Settings</a></li>
          <li><a href="#">Log Out</a></li>
        </ul>
      </li>
      <li><a href="#">Predictor</a></li>
      <li><a href="#">Odds Calculator</a></li>
    </ul>
  </div>
  <div class="top-bar-right">
    <ul class="menu">
      <li><input type="search" placeholder="Search"></li>
      <li><button type="button" class="button">Search</button></li>
    </ul>
  </div>
</div>

<div class="row">
    <div class="columns large-3"></div>
    <div class="columns large-6">
        <br>
        <br>
        <form class="show-password">
          <label for="username">Your login</label>
          <input type="text" value="" placeholder="Enter Username" id="username">
          <div class="password-wrapper">
            <label for="password">Your password</label>
            <input type="password" value="" placeholder="Enter Password" id="password" class="password">
            <button class="unmask" type="button" title="Mask/Unmask password to check content">Unmask</button>
          </div>
        </form>
    </div>

    <a class="button small" href="#">Sign In</a>
    <div class="columns large-3"></div>
</div>

    <script src="../static/js/app.js"></script>
    <script src="../static/js/vendor/foundation.js"></script>
    <script src="../static/js/vendor/what-input.js"></script>
    <script src="../static/js/vendor/jquery.js"></script>

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

If it helps to mention I am using Foundation as a CSS to help edit and make my webpages look nice.

When using the methods suggested below in terms of changing the script tags I get an error in the browser as follows -

```<code>jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'static'
</code>```

答:
you should link your js files using this:

```<code><script src="{{ url_for('static', filename='js/vendor/jquery.js') }}"></script>
</code>```

do this for all js files.
Hope that helps. If you still have any problem, please let me know.

for further investigation enable flask debug mode
To enable debug mode you can export the FLASK_DEBUG environment variable before running the server:

```<code>$ export FLASK_DEBUG=1
$ flask run
</code>```

this will show you more detailed errors and stack traces in the browser.

Body:
I am doing some coding with Python, Flask and .js files all with some HTML and CSS linked in as well. My problem is that I have a dropdown menu and a button that can hide and unhide password text but when running in Flask, this side of things is not working and I believe that it has something to do with the javascript. This function works perfectly when I am running the HTML file locally and not through flask, but I am completely lost as to where to go from here?

In terms of what I have done already is to ensure that my file structure is correct and that these .js files are within the static folder (where CSS stylesheets are being pulled from perfectly fine). My script tags where I link the .js files are all at the end of the body tag and do not sit within the head tag.

This is the app file that I am using for Flask and the simple code used to run this if it helps?

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route("/")

def render_static():

    return render_template('splash_page.html')

@app.route("/account")

def account_page():

    return render_template('account.html')

if __name__ == '__main__':
    app.run(debug = True)

Below you will find my HTML code used as a template in Flask, this is it before the changes suggested below -

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>

    <link href="../static/css/app.css" rel="stylesheet" type="text/css">
    <link href="../static/css/foundation.css" rel="stylesheet" type="text/css">

Premier League Pro

        Account

My Account

Settings

Log Out

Predictor

Odds Calculator

<input type="search" placeholder="Search">

<button type="button" class="button">Search</button>

        <form class="show-password">
          Your login
          <input type="text" value="" placeholder="Enter Username" id="username">

            Your password
            <input type="password" value="" placeholder="Enter Password" id="password" class="password">
            <button class="unmask" type="button" title="Mask/Unmask password to check content">Unmask</button>

        </form>

    Sign In

If it helps to mention I am using Foundation as a CSS to help edit and make my webpages look nice.

When using the methods suggested below in terms of changing the script tags I get an error in the browser as follows -

jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'static'

Body:
you should link your js files using this:

<script src="{{ url_for('static', filename='js/vendor/jquery.js') }}"></script>

do this for all js files.
Hope that helps. If you still have any problem, please let me know.

for further investigation enable flask debug mode
To enable debug mode you can export the FLASK_DEBUG environment variable before running the server:

$ export FLASK_DEBUG=1
$ flask run

this will show you more detailed errors and stack traces in the browser.


问:
How to *correctly* ask for permissions?
I'm developing an Android app that requires 3 permissions on startup. I have to wait until the user to responds at the dialogs, if not, the app crashes as the permissions are mandatory.

What is the correct way to ask for those permissions? I wrote the below code, but the app freezes when responding the first permission (either rejecting or accepting).

Here is what I made:

```<code>    String[] perms = {"Manifest.permission.READ_PHONE_STATE", "Manifest.permission.ACCESS_COARSE_LOCATION","Manifest.permission.CALL_PHONE"};

    int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_PHONE_STATE);
    int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
    int result3 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CALL_PHONE);

    if ((result1 == PackageManager.PERMISSION_GRANTED) && (result2 == PackageManager.PERMISSION_GRANTED) && (result3 == PackageManager.PERMISSION_GRANTED)) {
        onPermissionGranted();
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(perms, PERMISSION_REQUEST_CODE);
        } else {
            ActivityCompat.requestPermissions(this, perms, PERMISSION_REQUEST_CODE);
        }

    }

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted();
                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {
                Toast.makeText(MainActivity.this, R.string.permission_required, Toast.LENGTH_LONG).show();
                // permission denied, boo! Disable the
                // functionality that depends on this permission.

            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}
</code>```

答:
Go to the android manifest and add

This works with xamarin and unity</p>

Title: How to *correctly* ask for permissions?

Body:
I'm developing an Android app that requires 3 permissions on startup. I have to wait until the user to responds at the dialogs, if not, the app crashes as the permissions are mandatory.

What is the correct way to ask for those permissions? I wrote the below code, but the app freezes when responding the first permission (either rejecting or accepting).

Here is what I made:

    String[] perms = {"Manifest.permission.READ_PHONE_STATE", "Manifest.permission.ACCESS_COARSE_LOCATION","Manifest.permission.CALL_PHONE"};

    int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_PHONE_STATE);
    int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
    int result3 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CALL_PHONE);

    if ((result1 == PackageManager.PERMISSION_GRANTED) && (result2 == PackageManager.PERMISSION_GRANTED) && (result3 == PackageManager.PERMISSION_GRANTED)) {
        onPermissionGranted();
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(perms, PERMISSION_REQUEST_CODE);
        } else {
            ActivityCompat.requestPermissions(this, perms, PERMISSION_REQUEST_CODE);
        }

    }

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted();
                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {
                Toast.makeText(MainActivity.this, R.string.permission_required, Toast.LENGTH_LONG).show();
                // permission denied, boo! Disable the
                // functionality that depends on this permission.

            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}


问:
Why this sqlite3 code in PYTHON 3.7 program about employees and their first name,last name and salaries is not getting printed in the output?
I have a sqlite3 program in which I have to connect to a database stored in 'employees.db'. I will enter the first name, last name and salary and then print it. For printing, I will use fetchall(). But when I print the output, what I get is this-->

```<code>[]
</code>```

only 2 square brackets?
What is wrong?

I have started to learn python 2 weeks ago. But my course where I am learning is going too fast. I don't know what I am doing in this program is the correct approach or not?

HERE IS MY CODE--->>>

```<code>import sqlite3;

conn=sqlite3.connect('employees.db');
c=conn.cursor();

c.execute("""CREATE TABLE employees(first text,last text,pay integer)""");

c.execute("INSERT INTO employees VALUES('Tendo','Sinha',600000)");
c.execute("INSERT INTO employees VALUES('Krit','Kumar',40000)");

print(c.fetchall());

conn.commit();
conn.close
</code>```

I don't get any error. The output only shows:-

```<code>[]
</code>```

Only 2 square brackets.

答:
You are inserting rows into the table but not retrieving them at all.

Try adding a SELECT statement:

```<code>import sqlite3

conn = sqlite3.connect("employees.db")
c = conn.cursor()

# Create table, insert things...
c.execute(
    """CREATE TABLE IF NOT EXISTS employees(first text,last text,pay integer)"""
)
c.execute("INSERT INTO employees VALUES('Kritin','Sinha',600000)")
c.execute("INSERT INTO employees VALUES('Krit','Kumar',40000)")

# Commit the changes.
conn.commit()

# Retrieve from the table.
c.execute("SELECT * FROM employees")
print(c.fetchall())
</code>```

Body:
I have a sqlite3 program in which I have to connect to a database stored in 'employees.db'. I will enter the first name, last name and salary and then print it. For printing, I will use fetchall(). But when I print the output, what I get is this-->

[]

only 2 square brackets?
What is wrong?

I have started to learn python 2 weeks ago. But my course where I am learning is going too fast. I don't know what I am doing in this program is the correct approach or not?

HERE IS MY CODE--->>>

import sqlite3;

conn=sqlite3.connect('employees.db');
c=conn.cursor();

c.execute("""CREATE TABLE employees(first text,last text,pay integer)""");

c.execute("INSERT INTO employees VALUES('Tendo','Sinha',600000)");
c.execute("INSERT INTO employees VALUES('Krit','Kumar',40000)");

print(c.fetchall());

conn.commit();
conn.close

I don't get any error. The output only shows:-

[]

Only 2 square brackets.

Body:
You are inserting rows into the table but not retrieving them at all.

Try adding a SELECT statement:

import sqlite3

conn = sqlite3.connect("employees.db")
c = conn.cursor()

# Create table, insert things...
c.execute(
    """CREATE TABLE IF NOT EXISTS employees(first text,last text,pay integer)"""
)
c.execute("INSERT INTO employees VALUES('Kritin','Sinha',600000)")
c.execute("INSERT INTO employees VALUES('Krit','Kumar',40000)")

# Commit the changes.
conn.commit()

# Retrieve from the table.
c.execute("SELECT * FROM employees")
print(c.fetchall())


问:
Executing unix shell commands using PHP
A text box will be used to capture the command. I've been told that I have to use the exec() function to execute UNIX shell commands.

Something like this, user types ls in the text box. The exec() function will execute the UNIX command and the command will be displayed on the web page.

What I want to know how will I get the output of the shell command and display in the web browser using PHP.

I don't know where to start since I'm very new to PHP.

I'm using Ubuntu.

答:
Try $output = shell_exec('ls -lart');

doc shell_exec

ContentLicense: CC BY-SA 3.0

Title: Executing unix shell commands using PHP


问:
Completely hide products from unauthorized users in WooCommerce
I'm trying to remove a product/products completely from Users that are not logged in and if user is not specific role (e.g Verified Buyer).

I have been able to create a new role called Verified Buyer using the code below;

```<code>add_role(
    'verified_buyer',
    __( 'Verified Buyer', 'text-domain' ),
    array(
       'read'         => true,
        'edit_posts'   => false,
    )
);
//This Role is same role capability as the WooCommerce Customer role
</code>```

and i have as well added a checkbox to the WooCommerce Add New Product page using the code below

```<code>function hide_product_from_unathorised_users() {
  $args = array(
    'id' => '_hide_from_unauthorize_users',
    'label' => 'Hide Product from unauthorized users',
    'desc_tip' => true,
    'description' => __('Check this to hide this product from unauthorized users', 'text-domain')
  );
  woocommerce_wp_checkbox( $args );
}

add_action( 'woocommerce_product_options_advanced', 'hide_product_from_unathorised_users' );

// Save Fields
function product_custom_fields_save($post_id){
    // Custom Product Text Field
    $hide_product_unathorised_users = isset( $_POST['_hide_from_unauthorize_users'] ) ? 'yes' : 'no';
        update_post_meta($post_id, '_hide_from_unauthorize_users', esc_attr( $hide_product_unathorised_users ));
}
add_action('woocommerce_process_product_meta', 'product_custom_fields_save');
</code>```

Now that i have this two options (user role and a checkbox to know which product to hide) ... I want to Hide such product if the following conditions are met;

HIDE PRODUCT COMPLETELY (Even from search Queries) IF;

1. Checkbox is checked on product & User is not logged in

2. Checkbox is checked on product & User logged in & not Verified Buyer or admin Role

Like this

```<code>function hide_product_completely_conditionally() {

global $post;

$hide_product_checkbox = get_post_meta( $post->ID, '_hide_from_unauthorize_users', true )

$user = wp_get_current_user();
$authorized_user_role = in_array( 'verified_buyer', (array) $user->roles );
$admin_role = in_array( 'administrator', (array) $user->roles );

    if ( ($hide_product_checkbox == 'yes' && !is_user_loggedin()) || ($hide_product_checkbox == 'yes' && is_user_loggedin() && (!$authorized_user_role || !$admin_role) ) ) {

     //(...) HIDE SUCH PRODUCT COMPLETELY CODE THAT I'M NOT SURE HOW TO WRITE

    }
}
</code>```

Thanks for your help in advance.

答:
When you say "Remove" I'm assuming you are actually trying to hide the product.

So, using pre_get_posts action hook is your way to go.

The code below will hide any product which has its field _hide_from_unauthorize_users set to yes from users that are not logged in and from users that are logged in but are not a verified_buyer nor an administrator.

Put the snippet below in your functions.php file and pay attention to the comments:

```<code><?php

/**
 * @param WP_Query $query
 */
function _hide_products_from_certain_users( $query ) {
    if ( is_admin() ) {
        return;
    }

    /**
     * Create the query which will make sure only products that are allowed to bee seen will show up.
     */
    $meta_query[] = array(
        'key'     => '_hide_from_unauthorize_users',
        'value'   => 'yes',
        'compare' => '!=',
    );

    $user = wp_get_current_user();

    // If user is not logged in.
    if ( ! is_user_logged_in() ) {
        $query->set( 'meta_query', $meta_query );
    } else {
        $authorized_user_role = in_array( 'verified_buyer', (array) $user->roles );
        $admin_role           = in_array( 'administrator', (array) $user->roles );

        // If the current user is not a verified_buyer nor an administrator.
        if ( ! $authorized_user_role && ! $admin_role ) {
            $query->set( 'meta_query', $meta_query );
        }
    }
}

add_action( 'pre_get_posts', '_hide_products_from_certain_users' );
</code>```

Btw, you had a few syntax mistakes in your code, I fixed them.

Body:
I'm trying to remove a product/products completely from Users that are not logged in and if user is not specific role (e.g Verified Buyer).

I have been able to create a new role called Verified Buyer using the code below;

add_role(
    'verified_buyer',
    __( 'Verified Buyer', 'text-domain' ),
    array(
       'read'         => true,
        'edit_posts'   => false,
    )
);
//This Role is same role capability as the WooCommerce Customer role

and i have as well added a checkbox to the WooCommerce Add New Product page using the code below

function hide_product_from_unathorised_users() {
  $args = array(
    'id' => '_hide_from_unauthorize_users',
    'label' => 'Hide Product from unauthorized users',
    'desc_tip' => true,
    'description' => __('Check this to hide this product from unauthorized users', 'text-domain')
  );
  woocommerce_wp_checkbox( $args );
}

add_action( 'woocommerce_product_options_advanced', 'hide_product_from_unathorised_users' );

// Save Fields
function product_custom_fields_save($post_id){
    // Custom Product Text Field
    $hide_product_unathorised_users = isset( $_POST['_hide_from_unauthorize_users'] ) ? 'yes' : 'no';
        update_post_meta($post_id, '_hide_from_unauthorize_users', esc_attr( $hide_product_unathorised_users ));
}
add_action('woocommerce_process_product_meta', 'product_custom_fields_save');

Now that i have this two options (user role and a checkbox to know which product to hide) ... I want to Hide such product if the following conditions are met;

HIDE PRODUCT COMPLETELY (Even from search Queries) IF;

1. Checkbox is checked on product & User is not logged in

2. Checkbox is checked on product & User logged in & not Verified Buyer or admin Role

Like this

function hide_product_completely_conditionally() {

global $post;

$hide_product_checkbox = get_post_meta( $post->ID, '_hide_from_unauthorize_users', true )

$user = wp_get_current_user();
$authorized_user_role = in_array( 'verified_buyer', (array) $user->roles );
$admin_role = in_array( 'administrator', (array) $user->roles );

    if ( ($hide_product_checkbox == 'yes' && !is_user_loggedin()) || ($hide_product_checkbox == 'yes' && is_user_loggedin() && (!$authorized_user_role || !$admin_role) ) ) {

     //(...) HIDE SUCH PRODUCT COMPLETELY CODE THAT I'M NOT SURE HOW TO WRITE

    }
}

Thanks for your help in advance.

Body:
When you say "Remove" I'm assuming you are actually trying to hide the product.

So, using pre_get_posts action hook is your way to go.

The code below will hide any product which has its field _hide_from_unauthorize_users set to yes from users that are not logged in and from users that are logged in but are not a verified_buyer nor an administrator.

Put the snippet below in your functions.php file and pay attention to the comments:

<?php

/**
 * @param WP_Query $query
 */
function _hide_products_from_certain_users( $query ) {
    if ( is_admin() ) {
        return;
    }

    /**
     * Create the query which will make sure only products that are allowed to bee seen will show up.
     */
    $meta_query[] = array(
        'key'     => '_hide_from_unauthorize_users',
        'value'   => 'yes',
        'compare' => '!=',
    );

    $user = wp_get_current_user();

    // If user is not logged in.
    if ( ! is_user_logged_in() ) {
        $query->set( 'meta_query', $meta_query );
    } else {
        $authorized_user_role = in_array( 'verified_buyer', (array) $user->roles );
        $admin_role           = in_array( 'administrator', (array) $user->roles );

        // If the current user is not a verified_buyer nor an administrator.
        if ( ! $authorized_user_role && ! $admin_role ) {
            $query->set( 'meta_query', $meta_query );
        }
    }
}

add_action( 'pre_get_posts', '_hide_products_from_certain_users' );

Btw, you had a few syntax mistakes in your code, I fixed them.


问:
Processing attrbutes issue
I'm trying to write function which take columns attributes and transform them into appropriate strings.

My data has variable labels (description of column), variable names, type (factor, numeric, character), and defined factor levels (f.e. 1=yes, 2=no). I'd like to use function which generates string which contains all info in appropriate order:

```<code>Q B
Q [varname] vallab
T S #type
R yes
R no
Q E
</code>```

I wrote function like this:

```<code>WriteQ<-function(VarLab,VarName,Responses,VarType) {
  cond<-sapply(VarType, switch,
               factor="T S\n",
               numeric="T I\n",
               character="T C\n")
  mystr<-paste0("Q B\nQ [",VarName,"] ", VarLab, "\n",cond,"L0L2\n",paste("R",Responses, collapse =  "\n"),"\nQ E")
  return(mystr)
}
</code>```

And trying to call this like:

attributes(data)$qps<-WriteQ(attributes(data)$variable.labels,
                               attributes(data)$names,
                               unlist(lapply(data, attr, "levels")),
                               unlist(lapply(data, class)))
```

<p>While VarLab, VarName and VarType works fine, I have a problem with Responses.
It prints all levels form entire dataframe in each section. How I should pass list of levels separately for each column?</p>

<p>Structure of file:</p>

```
structure(list(id = c(1, 2), q23 = structure(1:2, .Label = c("yes",
"no", "don't know"), class = "factor"), gender = structure(c(1L,
1L), .Label = c("male", "female"), class = "factor"), age = c(33,
44)), row.names = 1:2, variable.labels = c("id", "Do you like flowers?",
"Select gender...", "How old are you?"), class = "data.frame")
```

答:
Here's a shot:

WriteQ <- function(VarLab, VarName, Responses, VarType) {
  Qs <- sprintf("Q [%s] %s", VarName, VarLab)
  Ts <- sapply(VarType, switch,
               factor="T S",
               numeric="T I",
               character="T C")
  Rs <- lapply(Responses, function(r) sprintf("R %s L0L2", r))
  QEs <- rep("Q E", length(VarLab))
  out <- Map(c, Qs, Ts, Rs, QEs)
  out
  # setNames(out, VarName)
  # setNames(lapply(out, paste, collapse = "\n"), VarName)
  # unlist(out, use.names = FALSE)
  # paste(unlist(out), collapse = "\n")
}
```

<p>The default output is:</p>

<pre class="lang-r prettyprint-override"><code>out
# $`Q [id] id`
# [1] "Q [id] id" "T I"       "Q E"
# $`Q [q23] Do you like flowers?`
# [1] "Q [q23] Do you like flowers?" "T S"
# [3] "R yes L0L2"                   "R no L0L2"
# [5] "R don't know L0L2"            "Q E"
# $`Q [gender] Select gender...`
# [1] "Q [gender] Select gender..." "T S"
# [3] "R male L0L2"                 "R female L0L2"
# [5] "Q E"
# $`Q [age] How old are you?`
# [1] "Q [age] How old are you?" "T I"
# [3] "Q E"
</code>```

Alternative output formats, depending on your needs:

setNames(out, VarName)
# $id
# [1] "Q [id] id" "T I"       "Q E"
# $q23
# [1] "Q [q23] Do you like flowers?" "T S"
# [3] "R yes L0L2"                   "R no L0L2"
# [5] "R don't know L0L2"            "Q E"
# $gender
# [1] "Q [gender] Select gender..." "T S"
# [3] "R male L0L2"                 "R female L0L2"
# [5] "Q E"
# $age
# [1] "Q [age] How old are you?" "T I"
# [3] "Q E"

setNames(lapply(out, paste, collapse = "\n"), VarName)
# $id
# [1] "Q [id] id\nT I\nQ E"
# $q23
# [1] "Q [q23] Do you like flowers?\nT S\nR yes L0L2\nR no L0L2\nR don't know L0L2\nQ E"
# $gender
# [1] "Q [gender] Select gender...\nT S\nR male L0L2\nR female L0L2\nQ E"
# $age
# [1] "Q [age] How old are you?\nT I\nQ E"

unlist(out, use.names = FALSE)
#  [1] "Q [id] id"                    "T I"
#  [3] "Q E"                          "Q [q23] Do you like flowers?"
#  [5] "T S"                          "R yes L0L2"
#  [7] "R no L0L2"                    "R don't know L0L2"
#  [9] "Q E"                          "Q [gender] Select gender..."
# [11] "T S"                          "R male L0L2"
# [13] "R female L0L2"                "Q E"
# [15] "Q [age] How old are you?"     "T I"
# [17] "Q E"

paste(unlist(out), collapse = "\n")
# [1] "Q [id] id\nT I\nQ E\nQ [q23] Do you like flowers?\nT S\nR yes L0L2\nR no L0L2\nR don't know L0L2\nQ E\nQ [gender] Select gender...\nT S\nR male L0L2\nR female L0L2\nQ E\nQ [age] How old are you?\nT I\nQ E"
```

Title: Processing attrbutes issue

Body:
I'm trying to write function which take columns attributes and transform them into appropriate strings.

My data has variable labels (description of column), variable names, type (factor, numeric, character), and defined factor levels (f.e. 1=yes, 2=no). I'd like to use function which generates string which contains all info in appropriate order:

Q B
Q [varname] vallab
T S #type
R yes
R no
Q E

I wrote function like this:

WriteQ<-function(VarLab,VarName,Responses,VarType) {
  cond<-sapply(VarType, switch,
               factor="T S\n",
               numeric="T I\n",
               character="T C\n")
  mystr<-paste0("Q B\nQ [",VarName,"] ", VarLab, "\n",cond,"L0L2\n",paste("R",Responses, collapse =  "\n"),"\nQ E")
  return(mystr)
}

And trying to call this like:

attributes(data)$qps<-WriteQ(attributes(data)$variable.labels,
                               attributes(data)$names,
                               unlist(lapply(data, attr, "levels")),
                               unlist(lapply(data, class)))

While VarLab, VarName and VarType works fine, I have a problem with Responses.
It prints all levels form entire dataframe in each section. How I should pass list of levels separately for each column?

Structure of file:

structure(list(id = c(1, 2), q23 = structure(1:2, .Label = c("yes",
"no", "don't know"), class = "factor"), gender = structure(c(1L,
1L), .Label = c("male", "female"), class = "factor"), age = c(33,
44)), row.names = 1:2, variable.labels = c("id", "Do you like flowers?",
"Select gender...", "How old are you?"), class = "data.frame")

Body:
Here's a shot:

WriteQ <- function(VarLab, VarName, Responses, VarType) {
  Qs <- sprintf("Q [%s] %s", VarName, VarLab)
  Ts <- sapply(VarType, switch,
               factor="T S",
               numeric="T I",
               character="T C")
  Rs <- lapply(Responses, function(r) sprintf("R %s L0L2", r))
  QEs <- rep("Q E", length(VarLab))
  out <- Map(c, Qs, Ts, Rs, QEs)
  out
  # setNames(out, VarName)
  # setNames(lapply(out, paste, collapse = "\n"), VarName)
  # unlist(out, use.names = FALSE)
  # paste(unlist(out), collapse = "\n")
}

The default output is:

out
# $`Q [id] id`
# [1] "Q [id] id" "T I"       "Q E"
# $`Q [q23] Do you like flowers?`
# [1] "Q [q23] Do you like flowers?" "T S"
# [3] "R yes L0L2"                   "R no L0L2"
# [5] "R don't know L0L2"            "Q E"
# $`Q [gender] Select gender...`
# [1] "Q [gender] Select gender..." "T S"
# [3] "R male L0L2"                 "R female L0L2"
# [5] "Q E"
# $`Q [age] How old are you?`
# [1] "Q [age] How old are you?" "T I"
# [3] "Q E"

Alternative output formats, depending on your needs:

setNames(out, VarName)
# $id
# [1] "Q [id] id" "T I"       "Q E"
# $q23
# [1] "Q [q23] Do you like flowers?" "T S"
# [3] "R yes L0L2"                   "R no L0L2"
# [5] "R don't know L0L2"            "Q E"
# $gender
# [1] "Q [gender] Select gender..." "T S"
# [3] "R male L0L2"                 "R female L0L2"
# [5] "Q E"
# $age
# [1] "Q [age] How old are you?" "T I"
# [3] "Q E"

setNames(lapply(out, paste, collapse = "\n"), VarName)
# $id
# [1] "Q [id] id\nT I\nQ E"
# $q23
# [1] "Q [q23] Do you like flowers?\nT S\nR yes L0L2\nR no L0L2\nR don't know L0L2\nQ E"
# $gender
# [1] "Q [gender] Select gender...\nT S\nR male L0L2\nR female L0L2\nQ E"
# $age
# [1] "Q [age] How old are you?\nT I\nQ E"

unlist(out, use.names = FALSE)
#  [1] "Q [id] id"                    "T I"
#  [3] "Q E"                          "Q [q23] Do you like flowers?"
#  [5] "T S"                          "R yes L0L2"
#  [7] "R no L0L2"                    "R don't know L0L2"
#  [9] "Q E"                          "Q [gender] Select gender..."
# [11] "T S"                          "R male L0L2"
# [13] "R female L0L2"                "Q E"
# [15] "Q [age] How old are you?"     "T I"
# [17] "Q E"

paste(unlist(out), collapse = "\n")
# [1] "Q [id] id\nT I\nQ E\nQ [q23] Do you like flowers?\nT S\nR yes L0L2\nR no L0L2\nR don't know L0L2\nQ E\nQ [gender] Select gender...\nT S\nR male L0L2\nR female L0L2\nQ E\nQ [age] How old are you?\nT I\nQ E"


问:
What's the current advice on CURLOPT_SSL_VERIFYPEER?
What's the current advice on CURLOPT_SSL_VERIFYPEER? I've traditionally always set it to false, because it always kept causing issues when fetching https:// URLs.

But now I read a comment saying that this allows "man in the middle" attacks, which I vaguely knew already, and that I should be downloading the https://curl.haxx.se/docs/caextract.html file and set the curl.cainfo config directive. And that can ONLY be set in the php.ini file, which makes everything a mess. I'd like to set it in my actual application if anything. Preferably not have to set it all, which I still don't understand why it's necessary in the first place...

What should I do? I don't want MITM attacks. Why doesn't PHP come with a proper such file? What's the problem?

答:
Good answer from https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software#verify-peer

What Happens If You Disable CURLOPT_SSL_VERIFYPEER? If you disable
  this check, you're opting out of the Certificate Authority
  infrastructure, which means you've elected to blindly accept
  self-signed certificates.

This exposes you to extremely trivial man-in-the-middle attacks. All
  the intercepting proxy needs to do is offer a self-signed certificate
  and PHP will just trust it, but only if you turn this off.

In today's ecosystem, the only real reason to use this is if you're
  using CURLOPT_PINNEDPUBLICKEY and for some reason can't use
  LetsEncrypt.

You should keep it on and make sure any sites you are curling have good certs from a trusted CA (like a paid one or a free cert from LetsEncrypt)

Setting up the up to date file of what certs should be valid and trusted can be done at the application level. More detail is in that link above and there is an opensource project that does it by the same author of the post: https://github.com/paragonie/certainty

You can use that if you want or just look at what it does and build it in yourself.


问:
Need explanation of looping java recursion code

This code is for finding the smallest number divisible by all num from 1 to 20
  I dont understand how this code works on recursion can u pleases explain this it wil be helpful

```<code>static long gcd(long a, long b)
{
   if(a%b != 0)
      return gcd(b,a%b);
   else
      return b;
}

// Function returns the lcm of first n numbers
static long lcm(long n)
{
    long ans = 1;
    for (long i = 1; i <= n; i++)
        ans = (ans * i)/(gcd(ans, i));
    return ans;
}

// Driver program to test the above function
public static void main(String []args)
{
    long n = 20;
    System.out.println(lcm(n));

}
</code>```

答:
This is very mathy, but gcd stands for "greatest common denominator" and lcm stands for "lowest common multiple".

The main algorithm keeps track of the current lowest common multiple "ans", and iterates "i" from 1 to "n" which in this case is 20. It then multiplies the current value by each "i" and divides by the greatest common denominator between "ans" and "i".

The gcd() method uses Euclid's algorithm to calculate the greatest common denominator

The reason that algorithm works is more a question for https://math.stackexchange.com/

Body:
This code is for finding the smallest number divisible by all num from 1 to 20
  I dont understand how this code works on recursion can u pleases explain this it wil be helpful

static long gcd(long a, long b)
{
   if(a%b != 0)
      return gcd(b,a%b);
   else
      return b;
}

// Function returns the lcm of first n numbers
static long lcm(long n)
{
    long ans = 1;
    for (long i = 1; i <= n; i++)
        ans = (ans * i)/(gcd(ans, i));
    return ans;
}

// Driver program to test the above function
public static void main(String []args)
{
    long n = 20;
    System.out.println(lcm(n));

}


问:
PHP fpassthru - How to output the file data without printing it on screen?
How can I output the file data without printing it on screen?

```<code>$file = "G:/...7F0D23C62002546097485FC518222504D29693FC8D2FCBB7.tgz";

// Open the file in a binary mode
$fp = fopen($file, 'rb');

// Dump the tar and stop the script
$success = fpassthru($fp);

fclose($fp);

if(!$success) {
    throw new Exception('Unable to downlonad');
} else {
   echo 'success!';
}
</code>```

Result,

��m�U�Vmo�6�O��\%��W�&0Xۤmծ�aZ&�'�^C����1$m��ꮪ���O>��>�c;;U�km��G���A0>C���LhH�&����w��#�W�lv�ZUl��~_��ŝg�^{Ww�0�+��%J�/A�!��AD��8"�P��3�K�D�$  �K�V;�����,Uf{Өn��6EW�}�ԧϭ�@g����������X?aI�$¶��1��s&3�8%���#�S�/:�z
  �80������s��Je��撟O�*�O.@
  �5^.{,v��.�[�����iZ���4e1.u�Pm�\��MU˅�Bf��Y.�f���k>���C���z�И]i�ت)}i�^��JYz֪2z�=����l��^w��|����^'�}亩V�;6y``��]A��  ����ߗ�6_w���Mg�#��
  �����۟0W��w���v�L����4�DS)b�""�3F9��h��
  ƶ&t%���i�,��?��a�i,m��e��̗���䒢Dʄeh*�ǒ=W��Q�d<)i{��%�X�QEO�:ƛm��o�J��P�'noKS�T���U&?q�u�+��V��FM;m��j-��ih�1�l;��N�o�Ԏ�t=��l��>G�[Cݬ��'d�����0�!3��s�P�dI�S�RI1�����O�7V,�|�%$~Lx6�g"LJRNq"� i
  ��18�mL(G0�����8�%a��cȌ���kB/�}����,G���C   'q�x!X\�"A!C��H_H)p�+�g��ٷ�����*������ޫA�6�G�
  6p���d�$*m�;�7�U,l��T��������~�v|P~Q��E��T'�����
  ��qb$##����/)�h%
  ?��1�Q�Ә>�kB?#h"�Q<    9�p�$���O|8�"FI,�L��?���&�����[��k�5gB������&}�^-��~��^�Ms;��p�����r�f�__��?����:#��3��Z=�!s{X���[��.pA�h�Tƌ��˺�v��'}�7���֫�qd)ӝ��t����7�����(success!

But I just want

success!

Is it possible?

答:
This is an old question but maybe the answer is usefull for somebody.

```<code>ob_start();
var_dump(fpassthru($fp));

$success = ob_get_clean();
</code>```

... then check the $success  for "success!" text.

Body:
How can I output the file data without printing it on screen?

$file = "G:/...7F0D23C62002546097485FC518222504D29693FC8D2FCBB7.tgz";

// Open the file in a binary mode
$fp = fopen($file, 'rb');

// Dump the tar and stop the script
$success = fpassthru($fp);

fclose($fp);

if(!$success) {
    throw new Exception('Unable to downlonad');
} else {
   echo 'success!';
}

Result,

��m�U�Vmo�6�O��\%��W�&0Xۤmծ�aZ&�'�^C����1$m��ꮪ���O>��>�c;;U�km��G���A0>C���LhH�&����w��#�W�lv�ZUl��~_��ŝg�^{Ww�0�+��%J�/A�!��AD��8"�P��3�K�D�$  �K�V;�����,Uf{Өn��6EW�}�ԧϭ�@g����������X?aI�$¶��1��s&3�8%���#�S�/:�z
  �80������s��Je��撟O�*�O.@
  �5^.{,v��.�[�����iZ���4e1.u�Pm�\��MU˅�Bf��Y.�f���k>���C���z�И]i�ت)}i�^��JYz֪2z�=����l��^w��|����^'�}亩V�;6y``��]A��  ����ߗ�6_w���Mg�#��
  �����۟0W��w���v�L����4�DS)b�""�3F9��h��
  ƶ&t%���i�,��?��a�i,m��e��̗���䒢Dʄeh*�ǒ=W��Q�d<)i{��%�X�QEO�:ƛm��o�J��P�'noKS�T���U&?q�u�+��V��FM;m��j-��ih�1�l;��N�o�Ԏ�t=��l��>G�[Cݬ��'d�����0�!3��s�P�dI�S�RI1�����O�7V,�|�%$~Lx6�g"LJRNq"� i
  ��18�mL(G0�����8�%a��cȌ���kB/�}����,G���C   'q�x!X\�"A!C��H_H)p�+�g��ٷ�����*������ޫA�6�G�
  6p���d�$*m�;�7�U,l��T��������~�v|P~Q��E��T'�����
  ��qb$##����/)�h%
  ?��1�Q�Ә>�kB?#h"�Q<    9�p�$���O|8�"FI,�L��?���&�����[��k�5gB������&}�^-��~��^�Ms;��p�����r�f�__��?����:#��3��Z=�!s{X���[��.pA�h�Tƌ��˺�v��'}�7���֫�qd)ӝ��t����7�����(success!

But I just want

success!

Is it possible?

Body:
This is an old question but maybe the answer is usefull for somebody.

ob_start();
var_dump(fpassthru($fp));

$success = ob_get_clean();

... then check the $success  for "success!" text.


问:
Downloading multiple stocks at once from Yahoo Finance
I have a question about the function of Yahoo Finance using the pandas data reader. I'm using for months now a list with stock tickers and execute it in the following lines:

```<code>import pandas_datareader as pdr
import datetime

stocks = ["stock1","stock2",....]
start = datetime.datetime(2012,5,31)
end = datetime.datetime(2018,3,1)

f = pdr.DataReader(stocks, 'yahoo',start,end)
</code>```

Since yesterday I get the error "IndexError: list index out of range", which appears only if I try to get multiple stocks.

Has anything changed in recent days, which I have to consider, or do you have a better solution for my problem?

答:
yahoo_finance no longer works, since Yahoo has changed the format, fix_yahoo_finance is good enough to download data. However, to parse, you'll need other libraries.

import numpy as np #python library for scientific computing
import pandas as pd #python library for data manipulation and analysis
import matplotlib.pyplot as plt #python library for charting
import fix_yahoo_finance as yf #python library to scrape data from yahoo finance
from pandas_datareader import data as pdr #extract data from internet sources into pandas data frame

yf.pdr_override()

data = pdr.get_data_yahoo(‘^DJI’, start=”2006–01–01")
data2 = pdr.get_data_yahoo(“MSFT”, start=”2006–01–01")
data3 = pdr.get_data_yahoo(“AAPL”, start=”2006–01–01")
data4 = pdr.get_data_yahoo(“BB.TO”, start=”2006–01–01")

ax = (data[‘Close’] / data[‘Close’].iloc[0] * 100).plot(figsize=(15, 6))
(data2[‘Close’] / data2[‘Close’].iloc[0] * 100).plot(ax=ax, figsize=(15,6))
(data3[‘Close’] / data3[‘Close’].iloc[0] * 100).plot(ax=ax, figsize=(15,6))
(data4[‘Close’] / data5[‘Close’].iloc[0] * 100).plot(ax=ax, figsize=(15,6))

plt.legend([‘Dow Jones’, ‘Microsoft’, ‘Apple’, ‘Blackberry’], loc=’upper left’)
plt.show()

```

Visit Charting stocks price from Yahoo Finance using fix-yahoo-finance library  for the code explanation.

Body:
I have a question about the function of Yahoo Finance using the pandas data reader. I'm using for months now a list with stock tickers and execute it in the following lines:

import pandas_datareader as pdr
import datetime

stocks = ["stock1","stock2",....]
start = datetime.datetime(2012,5,31)
end = datetime.datetime(2018,3,1)

f = pdr.DataReader(stocks, 'yahoo',start,end)

Since yesterday I get the error "IndexError: list index out of range", which appears only if I try to get multiple stocks.

Has anything changed in recent days, which I have to consider, or do you have a better solution for my problem?

Body:
yahoo_finance no longer works, since Yahoo has changed the format, fix_yahoo_finance is good enough to download data. However, to parse, you'll need other libraries.

import numpy as np #python library for scientific computing
import pandas as pd #python library for data manipulation and analysis
import matplotlib.pyplot as plt #python library for charting
import fix_yahoo_finance as yf #python library to scrape data from yahoo finance
from pandas_datareader import data as pdr #extract data from internet sources into pandas data frame

yf.pdr_override()

data = pdr.get_data_yahoo(‘^DJI’, start=”2006–01–01")
data2 = pdr.get_data_yahoo(“MSFT”, start=”2006–01–01")
data3 = pdr.get_data_yahoo(“AAPL”, start=”2006–01–01")
data4 = pdr.get_data_yahoo(“BB.TO”, start=”2006–01–01")

ax = (data[‘Close’] / data[‘Close’].iloc[0] * 100).plot(figsize=(15, 6))
(data2[‘Close’] / data2[‘Close’].iloc[0] * 100).plot(ax=ax, figsize=(15,6))
(data3[‘Close’] / data3[‘Close’].iloc[0] * 100).plot(ax=ax, figsize=(15,6))
(data4[‘Close’] / data5[‘Close’].iloc[0] * 100).plot(ax=ax, figsize=(15,6))

plt.legend([‘Dow Jones’, ‘Microsoft’, ‘Apple’, ‘Blackberry’], loc=’upper left’)
plt.show()

Visit Charting stocks price from Yahoo Finance using fix-yahoo-finance library  for the code explanation.


答:
you have to run a query for fetching all rows.

add these lines to your code-

```<code>data = c.execute("Select * FROM employees").fetchall()

print(data);
</code>```

Title: Why this sqlite3 code in PYTHON 3.7 program about employees and their first name,last name and salaries is not getting printed in the output?

Body:
you have to run a query for fetching all rows.

add these lines to your code-

data = c.execute("Select * FROM employees").fetchall()

print(data);


问:
Are there situations when self-assignment is useful?
It is commonly known that when implementing an assignment operator one has to protect against self-assignment, at least when the class has non-POD members. Usually it is (or is equivalent to):

```<code>Foo& operator=(const Foo& other)
{
  if (&other == this)
     return *this;
  ... // Do copy
}
</code>```

What were the reasons for not inserting the self-assignment protection automatically? Are there use cases when self-assignment does something non-trivial and practically useful?

```<code>Foo& operator=(const Foo& other)
{
  if (&other == this)
  {
    // Do something non-trivial
  }
  else
  {
    // Do copy
  }
  return *this;
}
</code>```

To summarize the answers and discussion by now

Looks like non-trivial self-assignment can never be really useful. The only option proposed was to put an assert there in order to detect some logical errors. But there are quite legitimate self-assignment cases like a = std::min(a, b), so even this option is highly dubious.

But there are two possible implementations of a trivial self-assignment:

Do nothing if &other == this. Always work, though may have negative performance impact due to an extra branching. But in a user-defined assignment operator the test must be almost always explicitly made.

Copy each member to itself. This is what is done by default. If the members use default assignment operators as well, it may be faster, because doesn't requre an extra branching.

I still don't see why the C++ standard could not guarantee that in a user-defined assignment operator &other != this. If you want no branching, use the default operator. If you are redefining the operator, some test is needed anyway...

答:
There are algorithms where it can happen.

You know the lhs and rhs might be the same but it is just simpler to do the assignment than check.  E.g., consider a = std::min(a,b); - simpler and perhaps easier to understand than if (a > b) a = b; - now consider more complicated examples of similar things.

You don't know whether lhs and rhs might be the same, because they may have been passed in from somewhere else.

These algorithms where it can happen are not uncommon.

Body:
It is commonly known that when implementing an assignment operator one has to protect against self-assignment, at least when the class has non-POD members. Usually it is (or is equivalent to):

Foo& operator=(const Foo& other)
{
  if (&other == this)
     return *this;
  ... // Do copy
}

What were the reasons for not inserting the self-assignment protection automatically? Are there use cases when self-assignment does something non-trivial and practically useful?

Foo& operator=(const Foo& other)
{
  if (&other == this)
  {
    // Do something non-trivial
  }
  else
  {
    // Do copy
  }
  return *this;
}

To summarize the answers and discussion by now

Looks like non-trivial self-assignment can never be really useful. The only option proposed was to put an assert there in order to detect some logical errors. But there are quite legitimate self-assignment cases like a = std::min(a, b), so even this option is highly dubious.

But there are two possible implementations of a trivial self-assignment:

Do nothing if &other == this. Always work, though may have negative performance impact due to an extra branching. But in a user-defined assignment operator the test must be almost always explicitly made.

Copy each member to itself. This is what is done by default. If the members use default assignment operators as well, it may be faster, because doesn't requre an extra branching.

I still don't see why the C++ standard could not guarantee that in a user-defined assignment operator &other != this. If you want no branching, use the default operator. If you are redefining the operator, some test is needed anyway...


问:
Unity license error on startup
i'm having an issue at launching unity.

I just install Unity, log-in via google and had that error.

Now, the bug appears with not even login in.

I tried to reinstall, remove registry and it stills happen with not even login in anymore.

There's the link where you can see the bucle it keeps doing.

https://gfycat.com/gifs/detail/AdmiredIcyAmericanwirehair

As you can see it keeps refreshing the license screen like it's trying to load something.

Thank you for any help you can provide.

答: Just delete the unity_lic.ulf found in program data and open unity and it will works!</p>

Title: Unity license error on startup


问:
how can display image from this query in php throw json
```<code>"NewsML":   [
        {
 "Identification": {"NewsIdentifier":       {
        "ProviderId": "timesofindia.com",
        "NewsItemId": "7954765"
      }},
      "NewsLines":       {
        "HeadLine": "I want KKR to win for Ganguly: Shah Rukh",
        "DateLine": "IANS, Apr 12, 2011, 04.41am IST"
      },
      "NewsComponent":       [
                {
          "Role": {"@FormalName": "WebURL"},
          "ContentItem":           {
            "MediaType": {"@FormalName": "Link"},
            "DataContent": {"media-caption": "http://timesofindia.indiatimes.com/sports/cricket/ipl-2011/news/I-want-KKR-to-win-for-Ganguly-Shah-Rukh/articleshow/7954765.cms"}
          }
        },
                {
          "Role": {"@FormalName": "Caption"},
          "ContentItem":           {
            "MediaType": {"@FormalName": "Text"},
            "DataContent": {"media-caption": "Aware of the negative vibes in Kolkata after the exclusion of Dada from the team, Shah Rukh Khan dedicated his team's victory to Sourav Ganguly."}
          }
        },
                {
          "Role": {"@FormalName": "Keywords"},
          "ContentItem":           {
            "MediaType": {"@FormalName": "Text"},
            "DataContent": {"media-keyword": "Sourav Ganguly, Shah Rukh Khan, KKR, IPL"}
          }
        },
                {
          "Role": {"@FormalName": "Photo"},
          "ContentItem":           {
            "@Href": "http://timesofindia.indiatimes.com/photo.cms?photoid=7954812&phototype=1&width=400&height=300",
            "MediaType": {"@FormalName": "Photo"},
            "Format": {"@FormalName": "JPEG Baseline"},
            "Characteristics":             [
                            {
                "@FormalName": "Width",
                "@Value": "450"
              },
                            {
                "@FormalName": "Height",
                "@Value": "300"
              }
            ]
          }
        },
                {
          "Role": {"@FormalName": "Photo-Caption"},
          "ContentItem":           {
            "MediaType": {"@FormalName": "Text"},
            "DataContent": {"media-caption": "Kolkata Knight Riders owner Saha Rukh Khan greets his supporters during their IPL match against Deccan Chargers at Eden Gardens. (PTI photo)"}
          }
        },
                {
          "Role": {"@FormalName": "Thumb"},
          "ContentItem":           {
            "@Href": "http://timesofindia.indiatimes.com/thumb.cms?photoid=7954812",
            "MediaType": {"@FormalName": "Photo"},
            "Format": {"@FormalName": "JPEG Baseline"}
          }
        },
                {
          "Role": {"@FormalName": "Story"},
          "ContentItem":           {
            "MediaType": {"@FormalName": "Text"},
            "DataContent": {"body": {"body.content": "KOLKATA: Aware of the negative vibes in Kolkata after the exclusion of local boy Sourav Ganguly from the team, Kolkata Knight Riders co-owner Shah Rukh Khan on Monday night dedicated his team's nine-run victory to Sourav Ganguly and the sports loving people of the city.\n\nI came back only for the fans. I wanted to do this for Knight Riders, the fans of Kolkata, I wanted to do this for Sourav Ganguly.\n\nI want my team KKR to win the IPL for Kolkata and Sourav Ganguly, said the matinee idol.\n\nI am very happy. It was really a cool moment. (Skipper Gautam) Gambhir and (Jacques) Kallis were really cool. It was really a cool moment as our team is unused to wins, said Shah Rukh Khan after KKR clinched their first win in IPL edition four.\n\nShah Rukh also expressed his disappointment over unnecessary controversies revolving the team for the last three seasons.\n\nA win is always welcome. We had lot of unnecessary controversies in the last three seasons, said Shah Rukh. "}}
          }
        }
      ]
    },
      }
]
</code>```

答:
Json is incorrect checkout http://www.jsonlint.com/

changed json =

```<code>{
    "NewsML": [
        {
            "Identification": {
                "NewsIdentifier": {
                    "ProviderId": "timesofindia.com",
                    "NewsItemId": "7954765"
                }
            },
            "NewsLines": {
                "HeadLine": "I want KKR to win for Ganguly: Shah Rukh",
                "DateLine": "IANS, Apr 12, 2011, 04.41am IST"
            },
            "NewsComponent": [
                {
                    "Role": {
                        "@FormalName": "WebURL"
                    },
                    "ContentItem": {
                        "MediaType": {
                            "@FormalName": "Link"
                        },
                        "DataContent": {
                            "media-caption": "http://timesofindia.indiatimes.com/sports/cricket/ipl-2011/news/I-want-KKR-to-win-for-Ganguly-Shah-Rukh/articleshow/7954765.cms"
                        }
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Caption"
                    },
                    "ContentItem": {
                        "MediaType": {
                            "@FormalName": "Text"
                        },
                        "DataContent": {
                            "media-caption": "Aware of the negative vibes in Kolkata after the exclusion of Dada from the team, Shah Rukh Khan dedicated his team's victory to Sourav Ganguly."
                        }
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Keywords"
                    },
                    "ContentItem": {
                        "MediaType": {
                            "@FormalName": "Text"
                        },
                        "DataContent": {
                            "media-keyword": "Sourav Ganguly, Shah Rukh Khan, KKR, IPL"
                        }
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Photo"
                    },
                    "ContentItem": {
                        "@Href": "http://timesofindia.indiatimes.com/photo.cms?photoid=7954812&phototype=1&width=400&height=300",
                        "MediaType": {
                            "@FormalName": "Photo"
                        },
                        "Format": {
                            "@FormalName": "JPEG Baseline"
                        },
                        "Characteristics": [
                            {
                                "@FormalName": "Width",
                                "@Value": "450"
                            },
                            {
                                "@FormalName": "Height",
                                "@Value": "300"
                            }
                        ]
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Photo-Caption"
                    },
                    "ContentItem": {
                        "MediaType": {
                            "@FormalName": "Text"
                        },
                        "DataContent": {
                            "media-caption": "Kolkata Knight Riders owner Saha Rukh Khan greets his supporters during their IPL match against Deccan Chargers at Eden Gardens. (PTI photo)"
                        }
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Thumb"
                    },
                    "ContentItem": {
                        "@Href": "http://timesofindia.indiatimes.com/thumb.cms?photoid=7954812",
                        "MediaType": {
                            "@FormalName": "Photo"
                        },
                        "Format": {
                            "@FormalName": "JPEG Baseline"
                        }
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Story"
                    },
                    "ContentItem": {
                        "MediaType": {
                            "@FormalName": "Text"
                        },
                        "DataContent": {
                            "body": {
                                "body.content": "KOLKATA: Aware of the negative vibes in Kolkata after the exclusion of local boy Sourav Ganguly from the team, Kolkata Knight Riders co-owner Shah Rukh Khan on Monday night dedicated his team's nine-run victory to Sourav Ganguly and the sports loving people of the city.\n\nI came back only for the fans. I wanted to do this for Knight Riders, the fans of Kolkata, I wanted to do this for Sourav Ganguly.\n\nI want my team KKR to win the IPL for Kolkata and Sourav Ganguly, said the matinee idol.\n\nI am very happy. It was really a cool moment. (Skipper Gautam) Gambhir and (Jacques) Kallis were really cool. It was really a cool moment as our team is unused to wins, said Shah Rukh Khan after KKR clinched their first win in IPL edition four.\n\nShah Rukh also expressed his disappointment over unnecessary controversies revolving the team for the last three seasons.\n\nA win is always welcome. We had lot of unnecessary controversies in the last three seasons, said Shah Rukh. "
                            }
                        }
                    }
                }
            ]
        }
    ]
}
</code>```

Body:
Json is incorrect checkout http://www.jsonlint.com/

changed json =

{
    "NewsML": [
        {
            "Identification": {
                "NewsIdentifier": {
                    "ProviderId": "timesofindia.com",
                    "NewsItemId": "7954765"
                }
            },
            "NewsLines": {
                "HeadLine": "I want KKR to win for Ganguly: Shah Rukh",
                "DateLine": "IANS, Apr 12, 2011, 04.41am IST"
            },
            "NewsComponent": [
                {
                    "Role": {
                        "@FormalName": "WebURL"
                    },
                    "ContentItem": {
                        "MediaType": {
                            "@FormalName": "Link"
                        },
                        "DataContent": {
                            "media-caption": "http://timesofindia.indiatimes.com/sports/cricket/ipl-2011/news/I-want-KKR-to-win-for-Ganguly-Shah-Rukh/articleshow/7954765.cms"
                        }
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Caption"
                    },
                    "ContentItem": {
                        "MediaType": {
                            "@FormalName": "Text"
                        },
                        "DataContent": {
                            "media-caption": "Aware of the negative vibes in Kolkata after the exclusion of Dada from the team, Shah Rukh Khan dedicated his team's victory to Sourav Ganguly."
                        }
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Keywords"
                    },
                    "ContentItem": {
                        "MediaType": {
                            "@FormalName": "Text"
                        },
                        "DataContent": {
                            "media-keyword": "Sourav Ganguly, Shah Rukh Khan, KKR, IPL"
                        }
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Photo"
                    },
                    "ContentItem": {
                        "@Href": "http://timesofindia.indiatimes.com/photo.cms?photoid=7954812&phototype=1&width=400&height=300",
                        "MediaType": {
                            "@FormalName": "Photo"
                        },
                        "Format": {
                            "@FormalName": "JPEG Baseline"
                        },
                        "Characteristics": [
                            {
                                "@FormalName": "Width",
                                "@Value": "450"
                            },
                            {
                                "@FormalName": "Height",
                                "@Value": "300"
                            }
                        ]
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Photo-Caption"
                    },
                    "ContentItem": {
                        "MediaType": {
                            "@FormalName": "Text"
                        },
                        "DataContent": {
                            "media-caption": "Kolkata Knight Riders owner Saha Rukh Khan greets his supporters during their IPL match against Deccan Chargers at Eden Gardens. (PTI photo)"
                        }
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Thumb"
                    },
                    "ContentItem": {
                        "@Href": "http://timesofindia.indiatimes.com/thumb.cms?photoid=7954812",
                        "MediaType": {
                            "@FormalName": "Photo"
                        },
                        "Format": {
                            "@FormalName": "JPEG Baseline"
                        }
                    }
                },
                {
                    "Role": {
                        "@FormalName": "Story"
                    },
                    "ContentItem": {
                        "MediaType": {
                            "@FormalName": "Text"
                        },
                        "DataContent": {
                            "body": {
                                "body.content": "KOLKATA: Aware of the negative vibes in Kolkata after the exclusion of local boy Sourav Ganguly from the team, Kolkata Knight Riders co-owner Shah Rukh Khan on Monday night dedicated his team's nine-run victory to Sourav Ganguly and the sports loving people of the city.\n\nI came back only for the fans. I wanted to do this for Knight Riders, the fans of Kolkata, I wanted to do this for Sourav Ganguly.\n\nI want my team KKR to win the IPL for Kolkata and Sourav Ganguly, said the matinee idol.\n\nI am very happy. It was really a cool moment. (Skipper Gautam) Gambhir and (Jacques) Kallis were really cool. It was really a cool moment as our team is unused to wins, said Shah Rukh Khan after KKR clinched their first win in IPL edition four.\n\nShah Rukh also expressed his disappointment over unnecessary controversies revolving the team for the last three seasons.\n\nA win is always welcome. We had lot of unnecessary controversies in the last three seasons, said Shah Rukh. "
                            }
                        }
                    }
                }
            ]
        }
    ]
}


问:
Scraping the path of a m3u8 file
I'm currently trying to scrape a unique value in the m3u8 url path of an embedded video for self-study. Each embedded video on the site shares the same url path except for the unique value.

For example, from the https://headlines.yahoo.co.jp/videonews/ann?a=20190526-00000026-ann-int page, I can find the m3u8 path through the inspector's network tab:

https://gw-yvpub.c.yimg.jp/v1/hls/CFukHuaO2W13gxbJ/video.m3u8

The unique value here is CFukHuaO2W13gxbJ. However, I cannot for the life of me find this value anywhere in the page source or anywhere else in the inspector tabs. Is it possible to find this url link in the page source or where this url is generated?

Side note: A request call is made to this blob url right before request calls to the m3u8 file:

blob:https://s.yimg.jp/f23ed5ca-7a95-4409-bf66-c26c577157d2

Thanks in advance for any guidance!

答:
The m3u8 urls are present in request made to this url:

```<code>https://feapi-yvpub.yahooapis.jp/v1/content/1576087?appid=dj0zaiZpPVZMTVFJR0FwZWpiMyZzPWNvbnN1bWVyc2VjcmV0Jng9YjU-&output=json&space_id=2078710316&domain=headlines.yahoo.co.jp&ak=044ddff76151606c2d97ada9daa3ea45&device_type=1100&thumb_width=1204&thumb_height=676&thumb_priority=l&thumb_bd=0
</code>```

Values for that come from your given url here:

```
</div>
</div>
</p>

<p>As well as content id seen, for example</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><script type="text/javascript" class="yvpub-player" src="https://s.yimg.jp/images/yvpub/player/js/embed.js?contentid=1576087&width=602&height=338&propertyname=jp_news&spaceid=2078710316&repeat=0&recommend=0&autostart=1" data-composed="1"></script></code>```

This 044ddff76151606c2d97ada9daa3ea45  is an access key I think. Not sure if that is something you can re-use across requests. Perhaps also look at the API documentation if there is any. Has a whiff of random hash (probably governed by length) - that could pose problems.

Title: Scraping the path of a m3u8 file

Body:
The m3u8 urls are present in request made to this url:

https://feapi-yvpub.yahooapis.jp/v1/content/1576087?appid=dj0zaiZpPVZMTVFJR0FwZWpiMyZzPWNvbnN1bWVyc2VjcmV0Jng9YjU-&output=json&space_id=2078710316&domain=headlines.yahoo.co.jp&ak=044ddff76151606c2d97ada9daa3ea45&device_type=1100&thumb_width=1204&thumb_height=676&thumb_priority=l&thumb_bd=0

Values for that come from your given url here:

<script type="text/javascript">
YAHOO.JP.srch.dlink.onLoad(function(sl) {
    sl.setParams({"serviceCode":"nws","appID":"dj0zaiZpPWlzQ3RiOHo1cGxBNSZzPWNvbnN1bWVyc2VjcmV0Jng9ODQ-","articleID":"20190526-00000026-ann","category":null,"mediaID":"ann","spaceID":2078710316,"linkCount":"5","launchAfterDocLoad":false});
});
</script>

As well as content id seen, for example

<script type="text/javascript" class="yvpub-player" src="https://s.yimg.jp/images/yvpub/player/js/embed.js?contentid=1576087&amp;width=602&amp;height=338&amp;propertyname=jp_news&amp;spaceid=2078710316&amp;repeat=0&amp;recommend=0&amp;autostart=1" data-composed="1"></script>

This 044ddff76151606c2d97ada9daa3ea45  is an access key I think. Not sure if that is something you can re-use across requests. Perhaps also look at the API documentation if there is any. Has a whiff of random hash (probably governed by length) - that could pose problems.


问:
Is there a way to round a decimals that i get in the coefficients of the function poly.calc?
I'm working with the poly.calc() function to interpolate some points, the problem is that I need to print the polynomial with maximum two decimals for each coefficient

I know that in R there is a function like round (...) and it can do this but with numbers, i don't know if it works with the expression that i get from poly.calc().

A example:

```<code>library(PolynomF)

x=c(1:4)
y=c(15,12,14,17)

pol = poly.calc(x,y)
pol
</code>```

This is the result:

27 - 17.83333*x + 6.5*x^2 - 0.6666667*x^3

And i need something like this:

27 - 17.83*x + 6.5*x^2 - 0.66*x^3

答:
You'd try to use the round function as shown in following example and edit for your needs:</p>

```<code># --- calculate parameters lm -----------------------------------------
model <- lm(Pegel$D00 ~ Pegel$dss)
# summary(model)
a = round(as.vector(coef(model)[1]), 2)
b = round(as.vector(coef(model)[2]*365), 2) # scaled for year
r2 = round(summary(model)$r.squared, 2)
</code>```

Body:
I'm working with the poly.calc() function to interpolate some points, the problem is that I need to print the polynomial with maximum two decimals for each coefficient

I know that in R there is a function like round (...) and it can do this but with numbers, i don't know if it works with the expression that i get from poly.calc().

A example:

library(PolynomF)

x=c(1:4)
y=c(15,12,14,17)

pol = poly.calc(x,y)
pol

This is the result:

27 - 17.83333*x + 6.5*x^2 - 0.6666667*x^3

And i need something like this:

27 - 17.83*x + 6.5*x^2 - 0.66*x^3

Body:
You'd try to use the round function as shown in following example and edit for your needs:

# --- calculate parameters lm -----------------------------------------
model <- lm(Pegel$D00 ~ Pegel$dss)
# summary(model)
a = round(as.vector(coef(model)[1]), 2)
b = round(as.vector(coef(model)[2]*365), 2) # scaled for year
r2 = round(summary(model)$r.squared, 2)