问:
Cuts the header of a web page when viewing through a smartphone browser (ASP.net Core MVC 3.1)
Created a web application on the ASP.net Core MVC 3.1 stack. There are web pages that are cropped (in the header and to the table) when viewed from a mobile phone at a resolution of 360 by 740. When viewed from a tablet or PC, everything is fine. I tried to change both the _Layout file and the View file. But no have positive effect.

It's ok here:

When viewing from a mobile cut in "Head" and below:

_Layout.cshtml:

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>

    <link rel="stylesheet" asp-href-include="lib/bootstrap/dist/css/*.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/fontawesome.min.css" />
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css" />

        <button class="w3-bar-item w3-button w3-large w3-hide-large w3-hover-white" onclick="w3_close()">×</button>

HOMIE

              Домой

        <button class="w3-button w3-block w3-left-align w3-hover-white" onclick="myAccSeriesFunc()">
              Сериалы
        </button>

                  Просмотр

                  Архив

              Сигары

          Выход

            <button class="w3-button w3-xlarge w3-hide-large" onclick="w3_open()">☰</button>

@ViewBag.HeaderTitle

            @RenderBody()

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

<p><strong>Index.cshtml:</strong></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-html lang-html prettyprint-override"><code>@using Homie.Models
@model IndexViewModel

@addTagHelper *, Homie

@{
    ViewBag.Title = "Список выкуренных сигар";
    ViewBag.HeaderTitle = "Сигары - - - - [ История ]";
}

<style>
    .table-striped > tbody > tr:nth-child(odd) > td,
    .table-striped > tbody > tr:nth-child(odd) > th {
        background-color: sandybrown;
    }
</style>

Добавить
<p></p>

<form method="get">
    <div class="form-inline">
        <label>Название: </label>
        <input name="name" value="@Model.FilterViewModel.SelectedName" class="form-control" />

        <label>Формат: </label>
        <select name="format" asp-items="Model.FilterViewModel.Formats" class="form-control"></select>

        <input type="submit" value="Фильтр" class="btn btn-outline-dark" />
    </div>
</form>
<p></p>

<div>
    <label>Количество сигар: @Model.PageViewModel.CountPages</label>
</div>

<table class="table table-bordered table-striped table-sm">
    <tr>
        <th>
            Название
        </th>
        <th>Страна</th>
        <th>Цена</th>
        <th>Рейтинг</th>
        <th>
            Формат
        </th>
        <th></th>
    </tr>
    @foreach (var p in Model.Cigars)
    {
        <tr>
            <td>@p.Name</td>
            <td>@p.Country</td>
            <td>@p.Price</td>
            <td>@p.Rating</td>
            <td>@p.Shape</td>
            <td>

                Изменить
                Удалить
            </td>
        </tr>

    }
</table>
<p></p>
<page-link page-model="Model.PageViewModel" page-action="Index"
           page-url-name="@(Model.FilterViewModel.SelectedName)"
           page-url-company="@(Model.FilterViewModel.SelectedFormat)"
           page-url-sortorder="@(Model.SortViewModel.Current)"></page-link></code>```

答:
The nature of
 is that they are fixed-width. You need to make your table have a scroll bar when it exceeds the parent width, or find some way to collapse the columns on mobile (DataTables.js has some good tools for this out of the box). Below is the example of making the table scroll:

https://jsfiddle.net/Lv3sw20g/6/

Body:
Created a web application on the ASP.net Core MVC 3.1 stack. There are web pages that are cropped (in the header and to the table) when viewed from a mobile phone at a resolution of 360 by 740. When viewed from a tablet or PC, everything is fine. I tried to change both the _Layout file and the View file. But no have positive effect.

It's ok here:

When viewing from a mobile cut in "Head" and below:

_Layout.cshtml:

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>

    <link rel="stylesheet" asp-href-include="lib/bootstrap/dist/css/*.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/fontawesome.min.css" />
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css" />

        <button class="w3-bar-item w3-button w3-large w3-hide-large w3-hover-white" onclick="w3_close()">×</button>

HOMIE

              Домой

        <button class="w3-button w3-block w3-left-align w3-hover-white" onclick="myAccSeriesFunc()">
              Сериалы
        </button>

                  Просмотр

                  Архив

              Сигары

          Выход

            <button class="w3-button w3-xlarge w3-hide-large" onclick="w3_open()">☰</button>

@ViewBag.HeaderTitle

            @RenderBody()

Index.cshtml:

@using Homie.Models
@model IndexViewModel

@addTagHelper *, Homie

@{
    ViewBag.Title = "Список выкуренных сигар";
    ViewBag.HeaderTitle = "Сигары - - - - [ История ]";
}

Добавить

<form method="get">

        Название:
        <input name="name" value="@Model.FilterViewModel.SelectedName" class="form-control" />

        Формат:
        <select name="format" asp-items="Model.FilterViewModel.Formats" class="form-control"></select>

        <input type="submit" value="Фильтр" class="btn btn-outline-dark" />

</form>

    Количество сигар: @Model.PageViewModel.CountPages

            Название

        Страна
        Цена
        Рейтинг

            Формат

    @foreach (var p in Model.Cigars)
    {

            @p.Name
            @p.Country
            @p.Price
            @p.Rating
            @p.Shape

                Изменить
                Удалить

    }

<page-link page-model="Model.PageViewModel" page-action="Index"
           page-url-name="@(Model.FilterViewModel.SelectedName)"
           page-url-company="@(Model.FilterViewModel.SelectedFormat)"
           page-url-sortorder="@(Model.SortViewModel.Current)"></page-link>

Body:
The nature of <table> is that they are fixed-width. You need to make your table have a scroll bar when it exceeds the parent width, or find some way to collapse the columns on mobile (DataTables.js has some good tools for this out of the box). Below is the example of making the table scroll:

https://jsfiddle.net/Lv3sw20g/6/


来源: stackexchange

问:
Importing web data
I trying to import web data to excel using vba with below code but it seems like not working.Hopefully someone can help to fix this issue, thank you very much!</p>

```<code>Sub ExchangeRate()
Dim ieObj As InternetExplorer
Dim htmlEle As IHTMLElement
Dim i As Integer

i = 1

Set ieObj = New InternetExplorer
ieObj.Visible = True
ieObj.navigate "https://www.imf.org/external/np/fin/ert/GUI/Pages/Report.aspx?CU=%27SGD%27&EX=REP&P=OneWeek&CF=Compressed&CUF=Period&DS=Ascending&DT=Blank"

Application.Wait Now + TimeValue("00:00:05")

For Each htmlEle In ieObj.document.getElementsByClassName("default").Item(2).getElementsByClassName("row1").Item(4)
    With ActiveSheet
      .Range("A" & i).Value = htmlEle.Children(0).textContent
      .Range("B" & i).Value = htmlEle.Children(1).textContent
      .Range("C" & i).Value = htmlEle.Children(3).textContent
      .Range("D" & i).Value = htmlEle.Children(4).textContent
    End With

    i = i + 1

Next htmlEle

End Sub
</code>```

答:
I think your issue is the line where your selecting the elements you want to read data from.</p>

```<code>Sub ExchangeRate()
Dim ieObj As InternetExplorer
Dim htmlEle As IHTMLElement
Dim htmlEleCollection As IHTMLElementCollection
Dim i As Integer

i = 1

Set ieObj = New InternetExplorer
ieObj.Visible = True
ieObj.navigate "https://www.imf.org/external/np/fin/ert/GUI/Pages/Report.aspx?CU=%27SGD%27&EX=REP&P=OneWeek&CF=Compressed&CUF=Period&DS=Ascending&DT=Blank"

' Application.Wait Now + TimeValue("00:00:05")
While ieObj.readyState <> 4 Or ieObj.Busy: DoEvents: Wend
' using application.wait may work, but if it takes more than 5s for the page to load your code may fail.
' waiting for the browser to be ready is better.

Set htmlEleCollection = ieObj.Document.getElementsByClassName("default").Item(0).getElementsByClassName("row1")
' i dont think you are selecting the right object with your code, i think this is what you were aiming for?

For Each htmlEle In htmlEleCollection
    If htmlEle.Children.Length > 1 Then
' the table header has one child, the data rows have more
        With ActiveSheet
            .Range("A" & i).Value = htmlEle.Children(0).textContent
            .Range("B" & i).Value = htmlEle.Children(1).textContent
'            .Range("C" & i).Value = htmlEle.Children(3).textContent
'            .Range("D" & i).Value = htmlEle.Children(4).textContent
' children 3 and 4 do not exist when i view the page so your code will fail with them in.
        End With
    End If

    i = i + 1

Next htmlEle
ieObj.Quit
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Title: Importing web data

Body:
I trying to import web data to excel using vba with below code but it seems like not working.Hopefully someone can help to fix this issue, thank you very much!

Sub ExchangeRate()
Dim ieObj As InternetExplorer
Dim htmlEle As IHTMLElement
Dim i As Integer

i = 1

Set ieObj = New InternetExplorer
ieObj.Visible = True
ieObj.navigate "https://www.imf.org/external/np/fin/ert/GUI/Pages/Report.aspx?CU=%27SGD%27&EX=REP&P=OneWeek&CF=Compressed&CUF=Period&DS=Ascending&DT=Blank"

Application.Wait Now + TimeValue("00:00:05")

For Each htmlEle In ieObj.document.getElementsByClassName("default").Item(2).getElementsByClassName("row1").Item(4)
    With ActiveSheet
      .Range("A" & i).Value = htmlEle.Children(0).textContent
      .Range("B" & i).Value = htmlEle.Children(1).textContent
      .Range("C" & i).Value = htmlEle.Children(3).textContent
      .Range("D" & i).Value = htmlEle.Children(4).textContent
    End With

    i = i + 1

Next htmlEle

End Sub

Body:
I think your issue is the line where your selecting the elements you want to read data from.

Sub ExchangeRate()
Dim ieObj As InternetExplorer
Dim htmlEle As IHTMLElement
Dim htmlEleCollection As IHTMLElementCollection
Dim i As Integer

i = 1

Set ieObj = New InternetExplorer
ieObj.Visible = True
ieObj.navigate "https://www.imf.org/external/np/fin/ert/GUI/Pages/Report.aspx?CU=%27SGD%27&EX=REP&P=OneWeek&CF=Compressed&CUF=Period&DS=Ascending&DT=Blank"

' Application.Wait Now + TimeValue("00:00:05")
While ieObj.readyState <> 4 Or ieObj.Busy: DoEvents: Wend
' using application.wait may work, but if it takes more than 5s for the page to load your code may fail.
' waiting for the browser to be ready is better.

Set htmlEleCollection = ieObj.Document.getElementsByClassName("default").Item(0).getElementsByClassName("row1")
' i dont think you are selecting the right object with your code, i think this is what you were aiming for?

For Each htmlEle In htmlEleCollection
    If htmlEle.Children.Length > 1 Then
' the table header has one child, the data rows have more
        With ActiveSheet
            .Range("A" & i).Value = htmlEle.Children(0).textContent
            .Range("B" & i).Value = htmlEle.Children(1).textContent
'            .Range("C" & i).Value = htmlEle.Children(3).textContent
'            .Range("D" & i).Value = htmlEle.Children(4).textContent
' children 3 and 4 do not exist when i view the page so your code will fail with them in.
        End With
    End If

    i = i + 1

Next htmlEle
ieObj.Quit
End Sub


问:
The following required field is missing from the launch file: <jnlp>
I have a web page containing an applet. This references a JNLP file.
The web app is served by Tomcat.

I've verified that the JNLP is valid using JaNeLA. To test this locally, I tried putting all the resource files in one directory and launching the web page - applet was displayed successfully in the browser.

However when trying to serve up the web page via Tomcat I get this error

```<code>The following required field is missing from the launch file: <jnlp>
</code>```

I suspect that the JNLP file is not being found, but after trying to place it within various locations under the Tomcat webapps directory, and various settings of the codebase parameter, still no joy.

Here's my JNLP file

```<code><?xml version="1.0" encoding="utf-8"?>

   <jnlp href="WWJApplet.jnlp">
    <information>
        <title>World Wind Java Applet Demo</title>
        <vendor>NASA</vendor>
        <homepage href="http://worldwind.arc.nasa.gov"/>
        <description>World Wind Java Applet Demo</description>
        <description kind="short">World Wind Java Applet Demo</description>
        <offline-allowed/>
    </information>
    <security>
        <all-permissions/>
    </security>
     <resources os="Windows">
       <property name="sun.java2d.noddraw" value="true"/>
     </resources>
     <resources>
        <!--property name="sun.java2d.noddraw" value="true"/-->
        <java version="1.5+"/>
        <j2se href="http://java.sun.com/products/autodl/j2se" version="1.5+" initial-heap-size="512m" max-heap-size="512m"/>
        <jar href="mapviewapplet.jar" main="true"/>
        <!--jar href="WWJApplet.jar" main="true"/-->
        <jar href="worldwind.jar"/>
        <jar href="httpclient-4.0.1.jar"/>
        <jar href="httpcore-4.0.1.jar"/>
        <extension name="jogl"
                   href="http://download.java.net/media/jogl/builds/archive/jsr-231-webstart-current/jogl.jnlp"/>
     </resources>
     <!-- Width and heigth are overwritten by the surrounding web page -->
     <applet-desc
         name="WWJ Applet"
         main-class="com.pwr.mapviewer.ui.MapApplet"
         width="800" height="600">
        <param name="separate_jvm" value="true" />
     </applet-desc>
   </jnlp>
</code>```

Here is my applet tag within the HTML

```<code>    <applet
          code="org.jdesktop.applet.util.JNLPAppletLauncher"
          width=600
          height=400
          archive="mapviewapplet.jar,
                   jogl.jar,
                   gluegen-rt.jar,
                   worldwind.jar">
           <param name="jnlp_href" value="WWJApplet.jnlp"/> <!-- Picked up by new plugin -->
           <param name="codebase_lookup" value="false"/>
           <param name="subapplet.classname" value="com.pwr.mapviewer.ui.MapApplet"/>
           <param name="subapplet.displayname" value="World Wind Applet"/>
           <param name="noddraw.check" value="true"/>
           <param name="progressbar" value="true"/>
           <param name="jnlpNumExtensions" value="1"/>

     </applet>
</code>```

Edit: I placed the JNLP, along with all my other resources in the Apache web server root directory, and used a URL in my jnlp_href attribute -

```<code><param name="jnlp_href" value="http://localhost:80/WWJApplet.jnlp"/>
</code>```

I'm still not sure how this should be deployed within Tomcat, but for now the above resolves my problem

答: Not sure what you mean by "picked up by new plugin" in your HTML. However, according to http://download.oracle.com/javase/tutorial/deployment/applet/html.html, the JNLP file should be referenced by the "jnlp_ref" attribute within the applet tag.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a web page containing an applet. This references a JNLP file.
The web app is served by Tomcat.

I've verified that the JNLP is valid using JaNeLA. To test this locally, I tried putting all the resource files in one directory and launching the web page - applet was displayed successfully in the browser.

However when trying to serve up the web page via Tomcat I get this error

The following required field is missing from the launch file: <jnlp>

I suspect that the JNLP file is not being found, but after trying to place it within various locations under the Tomcat webapps directory, and various settings of the codebase parameter, still no joy.

Here's my JNLP file

<?xml version="1.0" encoding="utf-8"?>

   <jnlp href="WWJApplet.jnlp">
    <information>
        <title>World Wind Java Applet Demo</title>
        <vendor>NASA</vendor>
        <homepage href="http://worldwind.arc.nasa.gov"/>
        <description>World Wind Java Applet Demo</description>
        <description kind="short">World Wind Java Applet Demo</description>
        <offline-allowed/>
    </information>
    <security>
        <all-permissions/>
    </security>
     <resources os="Windows">
       <property name="sun.java2d.noddraw" value="true"/>
     </resources>
     <resources>

        <java version="1.5+"/>
        <j2se href="http://java.sun.com/products/autodl/j2se" version="1.5+" initial-heap-size="512m" max-heap-size="512m"/>
        <jar href="mapviewapplet.jar" main="true"/>

        <jar href="worldwind.jar"/>
        <jar href="httpclient-4.0.1.jar"/>
        <jar href="httpcore-4.0.1.jar"/>
        <extension name="jogl"
                   href="http://download.java.net/media/jogl/builds/archive/jsr-231-webstart-current/jogl.jnlp"/>
     </resources>

     <applet-desc
         name="WWJ Applet"
         main-class="com.pwr.mapviewer.ui.MapApplet"
         width="800" height="600">
        <param name="separate_jvm" value="true" />
     </applet-desc>
   </jnlp>

Here is my applet tag within the HTML

    <applet
          code="org.jdesktop.applet.util.JNLPAppletLauncher"
          width=600
          height=400
          archive="mapviewapplet.jar,
                   jogl.jar,
                   gluegen-rt.jar,
                   worldwind.jar">
           <param name="jnlp_href" value="WWJApplet.jnlp"/>
           <param name="codebase_lookup" value="false"/>
           <param name="subapplet.classname" value="com.pwr.mapviewer.ui.MapApplet"/>
           <param name="subapplet.displayname" value="World Wind Applet"/>
           <param name="noddraw.check" value="true"/>
           <param name="progressbar" value="true"/>
           <param name="jnlpNumExtensions" value="1"/>

     </applet>

Edit: I placed the JNLP, along with all my other resources in the Apache web server root directory, and used a URL in my jnlp_href attribute -

<param name="jnlp_href" value="http://localhost:80/WWJApplet.jnlp"/>

I'm still not sure how this should be deployed within Tomcat, but for now the above resolves my problem


问:
How to amplify or exaggerate a small change in value of a variable as compared to previous value?
I have an object that is very slightly changing its value on the y-axis. I want to amplify this change so that its is more noticeable.

My idea is to simply compare the current vale and previous value, find the difference and then add that difference to the y axis value along with an amplification factor. So this is what I came up with:

```<code>public float amplifyBy = 1.5f;
void Update()
    {
        // This calculates the center position of 4 objects and sets the transform of this object to this position
        optimalCentre = (targetAnchor1.position + targetAnchor2.position + targetAnchor3.position + targetAnchor4.position) / 4;

        // below is to amplify the y movement as there is almost no visible bounciness.
        if (optimalCentre.y != previousY)
        {
            // find difference in change
            float diff_ = previousY - optimalCentre.y;
            transform.position = new Vector3(optimalCentre.x, optimalCentre.y + (diff_ * amplifyBy), optimalCentre.z);
            Debug.Log(diff_);
        }
        else
        {
            transform.position = optimalCentre;
        }

        previousY = transform.position.y;
    }
</code>```

This is not working as expected, As what appears to be happening is that any amplification factor applied is incremented up until infinity and the gameObject very quickly goes beyond bounds.

Thank you

答:
Declare a tolerance value like

```<code>const float Tolerance = 0.1f;
</code>```

then compare it like

```<code>if(Math.Abs(optimalCentre.y - previousY) < Tolerance)
    {
        // find difference in change
        float diff_ = previousY - optimalCentre.y;
        transform.position = new Vector3(optimalCentre.x, optimalCentre.y + (diff_ * amplifyBy), optimalCentre.z);
        Debug.Log(diff_);
    }
</code>```

Body:
I have an object that is very slightly changing its value on the y-axis. I want to amplify this change so that its is more noticeable.

My idea is to simply compare the current vale and previous value, find the difference and then add that difference to the y axis value along with an amplification factor. So this is what I came up with:

public float amplifyBy = 1.5f;
void Update()
    {
        // This calculates the center position of 4 objects and sets the transform of this object to this position
        optimalCentre = (targetAnchor1.position + targetAnchor2.position + targetAnchor3.position + targetAnchor4.position) / 4;

        // below is to amplify the y movement as there is almost no visible bounciness.
        if (optimalCentre.y != previousY)
        {
            // find difference in change
            float diff_ = previousY - optimalCentre.y;
            transform.position = new Vector3(optimalCentre.x, optimalCentre.y + (diff_ * amplifyBy), optimalCentre.z);
            Debug.Log(diff_);
        }
        else
        {
            transform.position = optimalCentre;
        }

        previousY = transform.position.y;
    }

This is not working as expected, As what appears to be happening is that any amplification factor applied is incremented up until infinity and the gameObject very quickly goes beyond bounds.

Thank you

Body:
Declare a tolerance value like

const float Tolerance = 0.1f;

then compare it like

if(Math.Abs(optimalCentre.y - previousY) < Tolerance)
    {
        // find difference in change
        float diff_ = previousY - optimalCentre.y;
        transform.position = new Vector3(optimalCentre.x, optimalCentre.y + (diff_ * amplifyBy), optimalCentre.z);
        Debug.Log(diff_);
    }


问:
How to insert Items from a list into QlistWidget?
I want to insert a list of items into a QlistWidget.
Below is the code i am using:

```<code>names = ['apple', 'banana', 'Cherry']
for item in names:
   self.listWidget.insertItems(item)
</code>```

But i am having an error that below :

TypeError: insertItems(self, int, Iterable[str]): argument 1 has
  unexpected type 'str'

Please let me know the issue is.

答:
If you check the docs:

void QListWidget::insertItems(int row, const QStringList &labels)

Inserts items from the list of labels into the list, starting at the
  given row.

It is observed that the method X needs to have the initial position from where it will be inserted, so when not giving information where you want to add it will show 2 solutions:

add at start:

```<code>self.listWidget.insertItems(0, names)
</code>```

add it at the end:

```<code>self.listWidget.insertItems(self.listWidget.count(), names)
</code>```

For the last case it is better to use the addItems() method:

```<code>self.listWidget.addItems(names)
</code>```

Body:
I want to insert a list of items into a QlistWidget.
Below is the code i am using:

names = ['apple', 'banana', 'Cherry']
for item in names:
   self.listWidget.insertItems(item)

But i am having an error that below :

TypeError: insertItems(self, int, Iterable[str]): argument 1 has
  unexpected type 'str'

Please let me know the issue is.

Body:
If you check the docs:

void QListWidget::insertItems(int row, const QStringList &labels)

Inserts items from the list of labels into the list, starting at the
  given row.

It is observed that the method X needs to have the initial position from where it will be inserted, so when not giving information where you want to add it will show 2 solutions:

add at start:

self.listWidget.insertItems(0, names)

add it at the end:

self.listWidget.insertItems(self.listWidget.count(), names)

For the last case it is better to use the addItems() method:

self.listWidget.addItems(names)


问:
LinkedIn shared link image is not updating with custom url
while I am clicking  the contents are being shared. but the image is not being updated. I am working in a single page website application.

```<code>var customshareurlLnkd = 'https://www.linkedin.com/shareArticle?mini=true&url=' + encodeURI(globalConfig.main_site_root + '&title=' + data.content.title +'&source=CMS') ;

detailhtml += '&nbsp<a class="sharebtn" href="' + customshareurlLnkd + '" target="_blank">LinkedIn Share</a>';
</code>```

I have tried this link: http://beta.beantin.se/clearing-linkedin-link-sharing-preview-cache/   , but still stuck for hours. any solution ?
thanks in advance

答:
To have LinkedIn show preview data in the share dialogue when a user is about to share, you need to set the og: tags in the  block of your HTML, something like...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

Even if you are using something like ReactJS or NodeJS, you can still set index.html's  block to contain the appropriate og: tags.

You can find out if you've done everything correctly by using your URL with the LinkedIn Post Inspector.

I have also coded up my own working demo, which uses og: tags to make LinkedIn sharing work appropriately.  Check it out: www.sortwords.com.

Body:
while I am clicking  the contents are being shared. but the image is not being updated. I am working in a single page website application.

var customshareurlLnkd = 'https://www.linkedin.com/shareArticle?mini=true&url=' + encodeURI(globalConfig.main_site_root + '&title=' + data.content.title +'&source=CMS') ;

detailhtml += '&nbspLinkedIn Share';

I have tried this link: http://beta.beantin.se/clearing-linkedin-link-sharing-preview-cache/   , but still stuck for hours. any solution ?
thanks in advance

Body:
To have LinkedIn show preview data in the share dialogue when a user is about to share, you need to set the og: tags in the <head> block of your HTML, something like...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

Even if you are using something like ReactJS or NodeJS, you can still set index.html's <head> block to contain the appropriate og: tags.

You can find out if you've done everything correctly by using your URL with the LinkedIn Post Inspector.

I have also coded up my own working demo, which uses og: tags to make LinkedIn sharing work appropriately.  Check it out: www.sortwords.com.


问:
ModelMapper failed to convert java.lang.String to java.lang.Long
I have rest models that I use to build JSON that I send.

A rest model

```<code>@Getter @Setter
@ToString
public class OrderRequestModel {
    private String orderKeyId;
    private String paymentMode;
    private double totalAmount;
    private List<ProductRequestModel> orderProducts;
    private UserDetailsRequestModel seller;
    private Date createdAt;
}
</code>```

The ProductRequestModel is similar

```<code>@Getter @Setter
@ToString
public class ProductRequestModel {
    private String productKeyId;
    private String name;
    private double price;
    private int qty;
    private String imgPath;

    private CategoryRequestModel category;
}
</code>```

I'm passing the models to a DTO layer which is in relation with database (they include a long Id):

```<code>@Getter @Setter
@ToString
public class OrderDto implements Serializable {
    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private static final long serialVersionUID = 1L;

    private Long id;
    private String orderKeyId;
    private String paymentMode;
    private double totalAmount;
    private List<ProductDto> orderProducts;
    private UserDto seller;
    private Date createdAt;
}
</code>```

And my ProductDto :

```<code>@Getter @Setter
@ToString
public class ProductDto implements Serializable {
    // ommit this member and do not generate getter / setter
    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private static final long serialVersionUID = 1L;

    private Long id;
    private String productKeyId;
    private String name;
    private double price;
    private int qty;
    private String imgPath;

    private CategoryDto category = new CategoryDto();
}
</code>```

When i try to map OrderDto with the associated model i do it implicitelly :

```<code>OrderDto orderDto = modelMapper.map(orderRequestModel, OrderDto.class);
</code>```

In theory, orderKeyId from the model should match with its equivalent in the Dto. Unfortunatelly It returns an error :

```<code>Converter org.modelmapper.internal.converter.NumberConverter@3e36f4cc failed to convert java.lang.String to java.lang.Long.
Caused by: org.modelmapper.MappingException: ModelMapper mapping errors:
</code>```

I do need the Id in the DTO because if i want to make an update I do use "id"

答:
This issue is caused because of the Mapping Strategies. We can set the Mapping Strategies to STRICT so that when mapping from source object property to target object's property it only maps only those property which are perfectly matching in property name as well as it's data type. Below is an example.

```<code>public ModelMapper modelMapper() {
    ModelMapper modelMapper = new ModelMapper();
    modelMapper.getConfiguration()
        .setMatchingStrategy(MatchingStrategies.STRICT);
}
</code>```

FYI:
http://modelmapper.org/user-manual/configuration/#matching-strategies

Body:
I have rest models that I use to build JSON that I send.

A rest model

@Getter @Setter
@ToString
public class OrderRequestModel {
    private String orderKeyId;
    private String paymentMode;
    private double totalAmount;
    private List<ProductRequestModel> orderProducts;
    private UserDetailsRequestModel seller;
    private Date createdAt;
}

The ProductRequestModel is similar

@Getter @Setter
@ToString
public class ProductRequestModel {
    private String productKeyId;
    private String name;
    private double price;
    private int qty;
    private String imgPath;

    private CategoryRequestModel category;
}

I'm passing the models to a DTO layer which is in relation with database (they include a long Id):

@Getter @Setter
@ToString
public class OrderDto implements Serializable {
    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private static final long serialVersionUID = 1L;

    private Long id;
    private String orderKeyId;
    private String paymentMode;
    private double totalAmount;
    private List<ProductDto> orderProducts;
    private UserDto seller;
    private Date createdAt;
}

And my ProductDto :

@Getter @Setter
@ToString
public class ProductDto implements Serializable {
    // ommit this member and do not generate getter / setter
    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private static final long serialVersionUID = 1L;

    private Long id;
    private String productKeyId;
    private String name;
    private double price;
    private int qty;
    private String imgPath;

    private CategoryDto category = new CategoryDto();
}

When i try to map OrderDto with the associated model i do it implicitelly :

OrderDto orderDto = modelMapper.map(orderRequestModel, OrderDto.class);

In theory, orderKeyId from the model should match with its equivalent in the Dto. Unfortunatelly It returns an error :

Converter org.modelmapper.internal.converter.NumberConverter@3e36f4cc failed to convert java.lang.String to java.lang.Long.
Caused by: org.modelmapper.MappingException: ModelMapper mapping errors:

I do need the Id in the DTO because if i want to make an update I do use "id"

Body:
This issue is caused because of the Mapping Strategies. We can set the Mapping Strategies to STRICT so that when mapping from source object property to target object's property it only maps only those property which are perfectly matching in property name as well as it's data type. Below is an example.

public ModelMapper modelMapper() {
    ModelMapper modelMapper = new ModelMapper();
    modelMapper.getConfiguration()
        .setMatchingStrategy(MatchingStrategies.STRICT);
}

FYI:
http://modelmapper.org/user-manual/configuration/#matching-strategies


问:
Pass file into jar
I have jar file that contains this code

```<code>import java.io.File
import java.nio.file.Paths

import org.cassandraunit.utils.EmbeddedCassandraServerHelper

object CassandraMockBootable extends App {
  println("Running embedded Cassandra.........")
  val file = Paths.get("/target/classes/cassandra.yaml").toFile
  assert(file.exists())
  EmbeddedCassandraServerHelper.startEmbeddedCassandra(file, 50000)
}
</code>```

This jar is used in another application by a maven plugin that run a java process

```<code> <plugin>
        <groupId>com.bazaarvoice.maven.plugins</groupId>
        <artifactId>process-exec-maven-plugin</artifactId>
        <version>0.8</version>
        <executions>
          <execution>
            <id>Embedded-Cassandra</id>
            <phase>pre-integration-test</phase>
            <goals>
              <goal>start</goal>
            </goals>
            <configuration>
              <name>Embedded-Cassandra</name>
              <skip>${skipStartService}</skip>
              <arguments>
                <argument>java</argument>
                <argument>-XX:+HeapDumpOnOutOfMemoryError</argument>
                <argument>-Xss1M</argument>
                <argument>-XX:+UseParallelGC</argument>
                <argument>-cp</argument>
                <argument>../../mock-service/target/lib/*</argument>
                <argument>mocks.bootables.CassandraMockBootable</argument>
              </arguments>
            </configuration>
          </execution>
    </executions>
</plugin>
</code>```

I dont know how, but I've been unable to pass the cassandra.yaml to that process, and the assert never works.

I tried to put that file into the resources of src and test in the generated jar project, and the consumer project but nothing. The assert always fail.

Any idea what I'm doing wrong here?

Regards

答:
You appear to be using a relative path. Remove the first slash:

val file = Paths.get("target/classes/cassandra.yaml").toFile
```

<p>Or, add a dot:</p>

<pre class="lang-scala prettyprint-override"><code>val file = Paths.get("./target/classes/cassandra.yaml").toFile
</code>```

Or provide the full path

val file = Paths.get("/full/path/target/classes/cassandra.yaml").toFile
```

Title: Pass file into jar

Body:
I have jar file that contains this code

import java.io.File
import java.nio.file.Paths

import org.cassandraunit.utils.EmbeddedCassandraServerHelper

object CassandraMockBootable extends App {
  println("Running embedded Cassandra.........")
  val file = Paths.get("/target/classes/cassandra.yaml").toFile
  assert(file.exists())
  EmbeddedCassandraServerHelper.startEmbeddedCassandra(file, 50000)
}

This jar is used in another application by a maven plugin that run a java process

 <plugin>
        <groupId>com.bazaarvoice.maven.plugins</groupId>
        <artifactId>process-exec-maven-plugin</artifactId>
        <version>0.8</version>
        <executions>
          <execution>
            <id>Embedded-Cassandra</id>
            <phase>pre-integration-test</phase>
            <goals>
              <goal>start</goal>
            </goals>
            <configuration>
              <name>Embedded-Cassandra</name>
              <skip>${skipStartService}</skip>
              <arguments>
                <argument>java</argument>
                <argument>-XX:+HeapDumpOnOutOfMemoryError</argument>
                <argument>-Xss1M</argument>
                <argument>-XX:+UseParallelGC</argument>
                <argument>-cp</argument>
                <argument>../../mock-service/target/lib/*</argument>
                <argument>mocks.bootables.CassandraMockBootable</argument>
              </arguments>
            </configuration>
          </execution>
    </executions>
</plugin>

I dont know how, but I've been unable to pass the cassandra.yaml to that process, and the assert never works.

I tried to put that file into the resources of src and test in the generated jar project, and the consumer project but nothing. The assert always fail.

Any idea what I'm doing wrong here?

Regards

Body:
You appear to be using a relative path. Remove the first slash:

val file = Paths.get("target/classes/cassandra.yaml").toFile

Or, add a dot:

val file = Paths.get("./target/classes/cassandra.yaml").toFile

Or provide the full path

val file = Paths.get("/full/path/target/classes/cassandra.yaml").toFile


问:
Do I need to release the dispatch_queue_t created by dispatch_queue_create
Developing an iOS application with ARC enabled, and I need to an instance of dispatch_queue_t to carry on some background task.

Wonder do I need to call dispatch_release for the dispatch_queue_t created by dispatch_queue_create within an ARC environment?

Thanks,

答:
In short, no, you don’t call dispatch_release when using ARC.

The documentation says:

Important

If your app is built with a deployment target of macOS 10.8 and later or iOS v6.0 and later, dispatch queues are typically managed by ARC, so you do not need to retain or release the dispatch queues.

If you try calling dispatch_release, it will report an error which makes this very clear:

'release' is unavailable: not available in automatic reference counting mode

FWIW, while one wouldn’t generally do this nowadays, it’s worth noting that one can opt out of ARC management of GCD objects by defining OS_OBJECT_USE_OBJC to be 0 (e.g. a build setting that sets the C flags with -DOS_OBJECT_USE_OBJC=0). If you opt out of ARC management of GCD objects, then you do would need dispatch_release (and all the concomitant challenges that manual management of GCD objects entails). Otherwise, ARC projects would not use dispatch_release.

If you’re dealing with a contemporary project, this is not a practical concern. But if you’re dealing with older projects or source that might be included in legacy projects, then you might want to check (with #if) for OS_OBJECT_USE_OBJC and make a decision from that.


问:
Ion-item will not center on the page
I have a problem with trying to center an ion-item as seen below.It's slightly off-center.

I have tried text-align: center and also change the padding to no padding in ion-content, which doesn't do the trick.

I have the following html

```<code><ion-content no padding >
 <div  style =" text-align: center !important;">
  <ion-item style =" text-align: center;"id="projectTitle" color="transparent">
      <ion-input  placeholder="Project Title" [(ngModel)]="title"></ion-input>
  </ion-item>
  <div style="text-align: center !important" >
     <ion-button color ="transparent">maybe later</ion-button>
  </div>
 </div>
</ion-content>
</code>```

And the css

```<code>#projectTitle {
     margin-top: 300px;
     color: white !important;
}
</code>```

Please help me

答:
I was able to reproduce your problem on an iOS simulator and indeed, there are 5px offset to the left for list items - but this only holds true for iOS devices. Web browsers and Android devices do not have this offset.

Although, I was not able to pinpoint the exact location of where these 5px offset are introduced, I have a potential workaround for you. You can just add this snippet to the (S)CSS of your component and should be fine:

ion-list.list-ios>ion-item>* {
  transform: translate3d( -5px, 0px, 0px); // Fix x-offset for iOS, while preserving z reset of :host
}```
</div>
</div>
</p>

<p>If you are planning to use ion-sliding-item elements just change the first line to:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>  ion-list.list-ios>ion-item-sliding>ion-item>* {</code>```

Title: Ion-item will not center on the page

Body:
I have a problem with trying to center an ion-item as seen below.It's slightly off-center.

I have tried text-align: center and also change the padding to no padding in ion-content, which doesn't do the trick.

I have the following html

<ion-content no padding >

  <ion-item style =" text-align: center;"id="projectTitle" color="transparent">
      <ion-input  placeholder="Project Title" [(ngModel)]="title"></ion-input>
  </ion-item>

     <ion-button color ="transparent">maybe later</ion-button>

</ion-content>

And the css

#projectTitle {
     margin-top: 300px;
     color: white !important;
}

Please help me

Body:
I was able to reproduce your problem on an iOS simulator and indeed, there are 5px offset to the left for list items - but this only holds true for iOS devices. Web browsers and Android devices do not have this offset.

Although, I was not able to pinpoint the exact location of where these 5px offset are introduced, I have a potential workaround for you. You can just add this snippet to the (S)CSS of your component and should be fine:

ion-list.list-ios>ion-item>* {
  transform: translate3d( -5px, 0px, 0px); // Fix x-offset for iOS, while preserving z reset of :host
}

If you are planning to use ion-sliding-item elements just change the first line to:

  ion-list.list-ios>ion-item-sliding>ion-item>* {


问:
hello, How to combine these two vi labview files together?
I have this car project of 3 Gauges ( RPM, temperatue, and fuel) , RPM and fuel are working together , and fuel code is working alone , i just need some help to combine the all together, any help appreciated.</p>

答:
Unfortunately, merging VIs is difficult to impossible through automatic means.  You will have to copy the code manually if you want it all in the same VI.

However, there are ways to view VIs in a subpanel.  You would want to move to a more advanced architecture to really get the benefit.  Here are a few links to help get you started.  I hope this helps!

Programming Elements

Insert VI into SubPanel

Run VI


问:
How to convert two different date formats from a pandas dataframe column into same format?
I have two different date formats in a pandas column such as - DD-MM-YYYY and MM/DD/YYYY and I want to convert them into the same format.

I tried using the code -

```<code>data['SALE DATE'] = pd.to_datetime(data['SALE DATE']).dt.strftime('%m/%d/%Y')
</code>```

but this converts the dates into
DD/MM/YYYY and MM/DD/YYYY into the output - data['SALE DATE']

I want a python solution to overcome this problem. Any leads will be very helpful.

答:
If you are using pandas version 1.xx you can use the following solution:

```<code>pd.to_datetime(["11-08-2018", "05-03-2016", "08/30/2017", "09/21/2018"], infer_datetime_format=True, dayfirst=True).strftime("%m/%d/%Y")
</code>```

This gives the following result:

```<code>Index(['08/11/2018', '03/05/2016', '08/30/2017', '09/21/2018'], dtype='object')
</code>```

... the important argument here is dayfirst=True.

See pd.to_datetime docs for more.

Body:
I have two different date formats in a pandas column such as - DD-MM-YYYY and MM/DD/YYYY and I want to convert them into the same format.

I tried using the code -

data['SALE DATE'] = pd.to_datetime(data['SALE DATE']).dt.strftime('%m/%d/%Y')

but this converts the dates into
DD/MM/YYYY and MM/DD/YYYY into the output - data['SALE DATE']

I want a python solution to overcome this problem. Any leads will be very helpful.

Body:
If you are using pandas version 1.xx you can use the following solution:

pd.to_datetime(["11-08-2018", "05-03-2016", "08/30/2017", "09/21/2018"], infer_datetime_format=True, dayfirst=True).strftime("%m/%d/%Y")

This gives the following result:

Index(['08/11/2018', '03/05/2016', '08/30/2017', '09/21/2018'], dtype='object')

... the important argument here is dayfirst=True.

See pd.to_datetime docs for more.


问:
Bash, compare string to arrayvalue
i try to match a parameter with some array content. At the if clauses should be true, but it wont be.
At the output before compare i got this:

VAL:  drei_01 AND: drei

```<code>#!/bin/bash

array=( null_01 eins_01 zwei_01 drei_01 vier_01 )

lookarr() {
    maxc=${#array[@]}
    mbool=0

    for((i=0; i<$maxc; i++))
    do
        val=${array[$i]}
        echo "VAL:  $val AND: $1"

        if [[ $1 == *" $val "* ]]; then
            echo "TESTENTRY1"
            #do something
            mbool=1
            break
        fi
    done

    if [[ $mbool -eq 0 ]]; then
        echo "TESTENTRY2"
        #do something else
    fi

}

lookarr drei

</code>```

thanks

答:
Your if statement isn't matching because it is back-to-front and has extra spaces. For drei to match drei_01 you can replace your if statement with: </p>

```<code>if [[ "$val" == *"$1"* ]]; then
</code>```

Title: Bash, compare string to arrayvalue

Body:
i try to match a parameter with some array content. At the if clauses should be true, but it wont be.
At the output before compare i got this:

VAL:  drei_01 AND: drei

#!/bin/bash

array=( null_01 eins_01 zwei_01 drei_01 vier_01 )

lookarr() {
    maxc=${#array[@]}
    mbool=0

    for((i=0; i<$maxc; i++))
    do
        val=${array[$i]}
        echo "VAL:  $val AND: $1"

        if [[ $1 == *" $val "* ]]; then
            echo "TESTENTRY1"
            #do something
            mbool=1
            break
        fi
    done

    if [[ $mbool -eq 0 ]]; then
        echo "TESTENTRY2"
        #do something else
    fi

}

lookarr drei

thanks

Body:
Your if statement isn't matching because it is back-to-front and has extra spaces. For drei to match drei_01 you can replace your if statement with:

if [[ "$val" == *"$1"* ]]; then


问:
Laravel Excel vertical align center
How can I verticaly align center cells with laravel Excel ?

My code :

```<code>$sheet->cells('A1:'.$column_end.$i, function ($cells) {
                $cells->setBackground('#d8d8d8');
                $cells->setFontWeight('bold');
                $cells->setValignment('middle');
            });
</code>```

But it doesn't work, most of my cells are vertically align bottom.

Maybe it's not middle !

I tried 'center' but it didn't work neither. When I tried 'top' or 'bottom' it worked.

So why 'middle' or 'center' didn't ?

Thank for your help.

答:
Try this

$sheet->cell('A1:G1',function($cell){
$cell->setAlignment('center');
$cell->setFontWeight('bold');
});

Title: Laravel Excel vertical align center

Body:
How can I verticaly align center cells with laravel Excel ?

My code :

$sheet->cells('A1:'.$column_end.$i, function ($cells) {
                $cells->setBackground('#d8d8d8');
                $cells->setFontWeight('bold');
                $cells->setValignment('middle');
            });

But it doesn't work, most of my cells are vertically align bottom.

Maybe it's not middle !

I tried 'center' but it didn't work neither. When I tried 'top' or 'bottom' it worked.

So why 'middle' or 'center' didn't ?

Thank for your help.


问:
C# - pass on variable amount of parameters to other method within a method
I know the title is a little bit tricky to understand, but the following example should clarify what I mean:

Imagine you have a method with 2 overloads:

```<code>void Method(int i)
{
    Console.WriteLine("Method(int) called");
}

void Method(int i, string s)
{
    Console.WriteLine("Method(int, string) called");
}
</code>```

Then you have another method that takes a variable amount of parameters:

```<code>void MethodOverload(params dynamic[] parameters)
{
    Method(parameters); // Call one of the overloading methods depending on the parameter amount and their type
}
</code>```

The method above accepts any amount of parameters with any type. I want to call one of the overloading methods depending on the amount of passed parameters and their type.

For example:

```<code>void Run()
{
    TestFuncOverload(5);                 // Output: "testFunc(int) called"
    TestFuncOverload(5, "some text");    // Output: "testFunc(int, string) called"

    TestFuncOverload(5, 5);              //Error
}
</code>```

How does one achieve this in C#?

答:
You could do it with reflection but I don't recommend it. Reflection is slow and to do this you need to use it a lot. You should try to solve it with a different approach, but in case you really need to do it this way, this should do the trick:

```<code>    public void MethodOverload(params dynamic[] parameters)
    {
        //Check if the array is null
        if (parameters == null)
            throw new ArgumentNullException(nameof(parameters));

        //Create a list of the types in the dynamic[]
        var inputParameterTypes = new Type[parameters.Length];
        for (int i = 0; i < parameters.Length; i++)
        {
            inputParameterTypes[i] = parameters[i].GetType();
        }

        const string NameOfMethod = nameof(Method); //This should be the name of your method which will be called

        //Get every method from this class which has the name you are looking for
        var methods = this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(x => x.Name == NameOfMethod);

        foreach (var method in methods)
        {
            //Get the parameters of the method
            var methodParameters = method.GetParameters();

            if (methodParameters.Length != inputParameterTypes.Length)
                continue;

            //Check if the types match with the input parameters
            var match = true;
            for (int i = 0; i < methodParameters.Length; i++)
            {
                //Check if the type matches
                if (methodParameters[i].ParameterType == inputParameterTypes[i])
                    continue;

                //Doesn't match
                match = false;
            }
            if (!match)
                continue;

            //Call the method and return
            method.Invoke(this, parameters);
            return;
        }

        //If this is reached no valid methods were found
        throw new Exception("No valid methods found!");
    }
</code>```

(This code assumes that all methods are in the same class)

After doing some measurements with this code:

```<code>        var a = new Foo();

        var parameters = new dynamic[][]
            {
                new dynamic[] { 1, "Test" },
                new dynamic[] { 2 }
            };

        var sw = Stopwatch.StartNew();
        for (int i = 0; i < Num; i++)
        {
            a.MethodOverload(parameters[i % 2]);
        }
        sw.Stop();
        Console.WriteLine($"{Num} iterations took {sw.Elapsed.TotalMilliseconds} milliseconds. Average time: {sw.Elapsed.TotalMilliseconds / Num} milliseconds");
</code>```

(Removed the Console.WriteLine from the called functions)

here are the results:

```<code>10000000 iterations took 5283.9398 milliseconds. Average time: 0.00052839398 milliseconds
100000000 iterations took 51244.9142 milliseconds. Average time: 0.000512449142 milliseconds
</code>```

Body:
I know the title is a little bit tricky to understand, but the following example should clarify what I mean:

Imagine you have a method with 2 overloads:

void Method(int i)
{
    Console.WriteLine("Method(int) called");
}

void Method(int i, string s)
{
    Console.WriteLine("Method(int, string) called");
}

Then you have another method that takes a variable amount of parameters:

void MethodOverload(params dynamic[] parameters)
{
    Method(parameters); // Call one of the overloading methods depending on the parameter amount and their type
}

The method above accepts any amount of parameters with any type. I want to call one of the overloading methods depending on the amount of passed parameters and their type.

For example:

void Run()
{
    TestFuncOverload(5);                 // Output: "testFunc(int) called"
    TestFuncOverload(5, "some text");    // Output: "testFunc(int, string) called"

    TestFuncOverload(5, 5);              //Error
}

How does one achieve this in C#?

Body:
You could do it with reflection but I don't recommend it. Reflection is slow and to do this you need to use it a lot. You should try to solve it with a different approach, but in case you really need to do it this way, this should do the trick:

    public void MethodOverload(params dynamic[] parameters)
    {
        //Check if the array is null
        if (parameters == null)
            throw new ArgumentNullException(nameof(parameters));

        //Create a list of the types in the dynamic[]
        var inputParameterTypes = new Type[parameters.Length];
        for (int i = 0; i < parameters.Length; i++)
        {
            inputParameterTypes[i] = parameters[i].GetType();
        }

        const string NameOfMethod = nameof(Method); //This should be the name of your method which will be called

        //Get every method from this class which has the name you are looking for
        var methods = this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(x => x.Name == NameOfMethod);

        foreach (var method in methods)
        {
            //Get the parameters of the method
            var methodParameters = method.GetParameters();

            if (methodParameters.Length != inputParameterTypes.Length)
                continue;

            //Check if the types match with the input parameters
            var match = true;
            for (int i = 0; i < methodParameters.Length; i++)
            {
                //Check if the type matches
                if (methodParameters[i].ParameterType == inputParameterTypes[i])
                    continue;

                //Doesn't match
                match = false;
            }
            if (!match)
                continue;

            //Call the method and return
            method.Invoke(this, parameters);
            return;
        }

        //If this is reached no valid methods were found
        throw new Exception("No valid methods found!");
    }

(This code assumes that all methods are in the same class)

After doing some measurements with this code:

        var a = new Foo();

        var parameters = new dynamic[][]
            {
                new dynamic[] { 1, "Test" },
                new dynamic[] { 2 }
            };

        var sw = Stopwatch.StartNew();
        for (int i = 0; i < Num; i++)
        {
            a.MethodOverload(parameters[i % 2]);
        }
        sw.Stop();
        Console.WriteLine($"{Num} iterations took {sw.Elapsed.TotalMilliseconds} milliseconds. Average time: {sw.Elapsed.TotalMilliseconds / Num} milliseconds");

(Removed the Console.WriteLine from the called functions)

here are the results:

10000000 iterations took 5283.9398 milliseconds. Average time: 0.00052839398 milliseconds
100000000 iterations took 51244.9142 milliseconds. Average time: 0.000512449142 milliseconds


问:
How to write a platform independent wrapper function in C++
I am using snprintf to send the output to the buffer. Using C++ 11 and for desktop application.

As of now I am doing it only for windows. But from now onwards it has to support for different platforms (Windows, Linux and Mac)

To support for multiple platforms, I am planning to write a wrapper function with #if tags.

but here the challenge I am facing is, when invoking WrapperSprintf from different places of the project the number of parameters are different.

How to write a common wrapper that can be used from different places with different no of parameters passed to WrapperSprintf function?

I tried the wrapper function like as shown below. Please help me how to proceed with this:

```<code>void WrapperSprintf( char buffer, const char *format, ... )
{
#if defined(_WIN32)
    _snprintf_s(buffer, sizeof(buffer), format,...);
#else
    snprintf(buffer, sizeof(buffer), format, ...);
#endif
}
</code>```

Calling WrapperSprintf function1:

```<code>char m_systemTime[20];

char* CUPSManager ::getSystemTime()
{
    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    WrapperSprintf(m_systemTime,"%d-%d-%d :%d:%d:%d" , timeinfo ->tm_year +1900,
             timeinfo ->tm_mon +1,
             timeinfo->tm_mday,
             timeinfo->tm_hour,
             timeinfo->tm_min,
             timeinfo->tm_sec);
    return m_systemTime;
}
</code>```

Calling WrapperSprintf function2:

```<code>void getDevicePath()
{
    wstring strDevPath;
    strDevPath = (LPCWSTR)cDevicePath;
    char cDevPath[2048];
    WrapperSprintf(cDevPath,"%ls", strDevPath.c_str());
    int nPathLength = strlen(cDevPath);
...
}
</code>```

答:
I would not write it like that:

```<code>void WrapperSprintf( char buffer, const char *format, ... )
{
#if defined(_WIN32)
    _snprintf_s(buffer, sizeof(buffer), format,...);
#else
    snprintf(buffer, sizeof(buffer), format, ...);
#endif
}
</code>```

You don't need a function here. What you want is to select the correct function.

Rather do this:

```<code>#if defined(_WIN32)
#define WrapperSprintf    _snprintf_s
#else
#define WrapperSprintf    snprintf
#endif
</code>```

If you want to get complex and have the ability rearrange argumetns then we can take it one step further:

```<code>#if defined(_WIN32)
#define WrapperSprintf(buffer, size, ...)    _snprintf_s(buffer, size, __VA_ARGS__)
#elif defined(_WIERDYSTEM)
#define WrapperSprintf(buffer, size, ...)    wierdsnprintf(size, buffer, __VA_ARGS__)
#else
#define WrapperSprintf(buffer, size, ...)    snprintf(buffer, size, __VA_ARGS__)
#endif
</code>```

Note: __VA_ARGS__ must match at least one argument (i.e. it can not match zero). So use if for "format and format-arguments" as potentially there may be zero "format-arguments" if there are no % markers in the format string.

Body:
I am using snprintf to send the output to the buffer. Using C++ 11 and for desktop application.

As of now I am doing it only for windows. But from now onwards it has to support for different platforms (Windows, Linux and Mac)

To support for multiple platforms, I am planning to write a wrapper function with #if tags.

but here the challenge I am facing is, when invoking WrapperSprintf from different places of the project the number of parameters are different.

How to write a common wrapper that can be used from different places with different no of parameters passed to WrapperSprintf function?

I tried the wrapper function like as shown below. Please help me how to proceed with this:

void WrapperSprintf( char buffer, const char *format, ... )
{
#if defined(_WIN32)
    _snprintf_s(buffer, sizeof(buffer), format,...);
#else
    snprintf(buffer, sizeof(buffer), format, ...);
#endif
}

Calling WrapperSprintf function1:

char m_systemTime[20];

char* CUPSManager ::getSystemTime()
{
    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    WrapperSprintf(m_systemTime,"%d-%d-%d :%d:%d:%d" , timeinfo ->tm_year +1900,
             timeinfo ->tm_mon +1,
             timeinfo->tm_mday,
             timeinfo->tm_hour,
             timeinfo->tm_min,
             timeinfo->tm_sec);
    return m_systemTime;
}

Calling WrapperSprintf function2:

void getDevicePath()
{
    wstring strDevPath;
    strDevPath = (LPCWSTR)cDevicePath;
    char cDevPath[2048];
    WrapperSprintf(cDevPath,"%ls", strDevPath.c_str());
    int nPathLength = strlen(cDevPath);
...
}

Body:
I would not write it like that:

void WrapperSprintf( char buffer, const char *format, ... )
{
#if defined(_WIN32)
    _snprintf_s(buffer, sizeof(buffer), format,...);
#else
    snprintf(buffer, sizeof(buffer), format, ...);
#endif
}

You don't need a function here. What you want is to select the correct function.

Rather do this:

#if defined(_WIN32)
#define WrapperSprintf    _snprintf_s
#else
#define WrapperSprintf    snprintf
#endif

If you want to get complex and have the ability rearrange argumetns then we can take it one step further:

#if defined(_WIN32)
#define WrapperSprintf(buffer, size, ...)    _snprintf_s(buffer, size, __VA_ARGS__)
#elif defined(_WIERDYSTEM)
#define WrapperSprintf(buffer, size, ...)    wierdsnprintf(size, buffer, __VA_ARGS__)
#else
#define WrapperSprintf(buffer, size, ...)    snprintf(buffer, size, __VA_ARGS__)
#endif

Note: __VA_ARGS__ must match at least one argument (i.e. it can not match zero). So use if for "format and format-arguments" as potentially there may be zero "format-arguments" if there are no % markers in the format string.


问:
How to center react-dialog?
I try to create a simple resizable dialog but I don't know how to set properties on the dialog.

My code:

```<code>import React, {Component} from 'react';
import Panel from 'react-bootstrap/lib/Panel'
import Button from 'react-bootstrap/lib/Button'
import CustomerDetails from './CustomerDetails'
import axios from 'axios'
import Dialog from 'react-dialog'

export default class Customers extends Component {

  constructor(props) {
    super(props)
    this.state = {
      selectedCustomer: 1,
      isDialogOpen: false,
    }
  }

  //function which is called the first time the component loads
  componentDidMount() {
    this.getCustomerData();
  }

  //Function to get the Customer Data from json
  getCustomerData() {
    axios.get('assets/samplejson/customerlist.json').then(response => {
      this.setState({customerList: response})
    })
  };

  openDialog = () => this.setState({ isDialogOpen: true })

  handleClose = () => this.setState({ isDialogOpen: false })

  render() {
    if (!this.state.customerList)
      return (<p>Loading data</p>)
    return (<div className="addmargin">

      <div className="col-md-4">
        {
          this.state.customerList.data.map(customer => <Panel bsStyle="info" key={customer.name} className="centeralign">
            <Panel.Heading>
              <Panel.Title componentClass="h3"><b>{customer.name}</b></Panel.Title>
            </Panel.Heading>
            <Panel.Body>
              <p>{customer.information}</p>
              <p>{customer.fullkitcctv}</p>
              <p>{customer.additionalInfo}</p>
              <Button bsStyle="info" onClick={() => this.setState({selectedCustomer: customer.id

              })} >

                Вижте за подробности

              </Button>
              <p>За да видите съдържанието, отидете най-долу в сайта</p>
            </Panel.Body>
          </Panel>)
        }
      </div>

      <div className="col-md-4">
      <button type="button" onClick={this.openDialog}>Open Dialog</button>
                {
                    this.state.isDialogOpen &&
                    <Dialog
                        title="Dialog Title"
                        modal={true}
                        onClose={this.handleClose}
                        buttons={
                            [{
                                text: "Затвори",
                                onClick: () => this.handleClose()
                            }]
                        }>
                        <CustomerDetails val={this.state.selectedCustomer}/>
                    </Dialog>
                }
      </div>
    </div>)
  }
}
</code>```

Picture

How to set property on react-dialog-npm. I visit website https://www.npmjs.com/package/react-dialog but I cannot see any properties.
I visit the demo site but I cannot see the source code from there. https://mohitgupta8888.github.io/react-dialog/?selectedKind=React%20Dialog&selectedStory=isResizable%3Atrue&full=0&down=0&left=1&panelRight=0

I really need to set properties because the users cant see all content of my information when websites visited by phones or tablets.

答:
You can try adding alignSelf: "center" to dialogue styles.

If this doesn't work then,

write the dialogue code in the outermost div having a full screen access and then add

{
   alignSelf: "center"
 }

to dialogue styles.

Hope that it'll help you.

Title: How to center react-dialog?

Body:
I try to create a simple resizable dialog but I don't know how to set properties on the dialog.

My code:

import React, {Component} from 'react';
import Panel from 'react-bootstrap/lib/Panel'
import Button from 'react-bootstrap/lib/Button'
import CustomerDetails from './CustomerDetails'
import axios from 'axios'
import Dialog from 'react-dialog'

export default class Customers extends Component {

  constructor(props) {
    super(props)
    this.state = {
      selectedCustomer: 1,
      isDialogOpen: false,
    }
  }

  //function which is called the first time the component loads
  componentDidMount() {
    this.getCustomerData();
  }

  //Function to get the Customer Data from json
  getCustomerData() {
    axios.get('assets/samplejson/customerlist.json').then(response => {
      this.setState({customerList: response})
    })
  };

  openDialog = () => this.setState({ isDialogOpen: true })

  handleClose = () => this.setState({ isDialogOpen: false })

  render() {
    if (!this.state.customerList)
      return (
Loading data
)
    return (

        {
          this.state.customerList.data.map(customer => <Panel bsStyle="info" key={customer.name} className="centeralign">
            <Panel.Heading>
              <Panel.Title componentClass="h3">{customer.name}</Panel.Title>
            </Panel.Heading>
            <Panel.Body>

{customer.information}

{customer.fullkitcctv}

{customer.additionalInfo}

              <Button bsStyle="info" onClick={() => this.setState({selectedCustomer: customer.id

              })} >

                Вижте за подробности

              </Button>

За да видите съдържанието, отидете най-долу в сайта

            </Panel.Body>
          </Panel>)
        }

      <button type="button" onClick={this.openDialog}>Open Dialog</button>
                {
                    this.state.isDialogOpen &&
                    <Dialog
                        title="Dialog Title"
                        modal={true}
                        onClose={this.handleClose}
                        buttons={
                            [{
                                text: "Затвори",
                                onClick: () => this.handleClose()
                            }]
                        }>
                        <CustomerDetails val={this.state.selectedCustomer}/>
                    </Dialog>
                }

)
  }
}

Picture

How to set property on react-dialog-npm. I visit website https://www.npmjs.com/package/react-dialog but I cannot see any properties.
I visit the demo site but I cannot see the source code from there. https://mohitgupta8888.github.io/react-dialog/?selectedKind=React%20Dialog&selectedStory=isResizable%3Atrue&full=0&down=0&left=1&panelRight=0

I really need to set properties because the users cant see all content of my information when websites visited by phones or tablets.


问:
Create new column from existing dataframe column with condition
GroupID column has two values one alphanumeric and other is numeric, I want use alphanumeric part of column to create new column, with some condition like if alphanumeric is present in o_dict then it should return value else it should just return "NOT IN DIC"

```<code>GroupID
0   ad32s;#1214;#rf343;#4343
1   wd435;#6464;#ed532;#5454
2   av345e:#3132
3   ok132d;#8897
4   tn123h;#0980
5   as845;#657;#un567t;#456;#qw147;#123
6   ok132d;#8897
7   as845;#657;#un567t;#456;#qw147;#123
8   wd435;#6464;#ed532;#5454

o_dict= {"ad32s":"rupesh","ed532":"Frank","dr501u":"David","ok132d":"Ripal",
         "qw147":"ilesh","av345e":'carls'}
</code>```

below is my code:

```<code>def function01(row):
o_dict= {"ad32s":"rupesh","ed532":"Frank","dr501u":"David","ok132d":"Ripal","qw147":"ilesh","av345e":'carls'}
    if element.isalnum():
        if element in o_dict:
            return owner_dict[element]
        else:
            return "NOT IN DIC"
    else:
        continue
df['New_column'] = df.apply(lambda x: function01(x), axis=1)
</code>```

This code works if the alphanumeric value is at first position but does not work if it is at 3 or 5 position. It works for row 0,2,3,4 6, but does not work for 1,5,7,8.

O/p should have two columns with values from dict which matched with groupid else it should be populated with  "NOT IN DIC".

I not sure what i can do now, is there another approach to get this values ?
is there any search function which can be used to search for this values ??

Thanks for helping :)

答:
you may want to use numpy.select

```<code>    import numpy
    import pandas

    d = {
        "GroupID": [
            "ad32s;#1214;#rf343;#4343",
            "wd435;#6464;#ed532;#5454",
            "av345e:#3132",
            "ok132d;#8897",
            "tn123h;#0980",
            "as845;#657;#un567t;#456;#qw147;#123",
            "ok132d;#8897",
            "as845;#657;#un567t;#456;#qw147;#123",
            "wd435;#6464;#ed532;#5454",
        ]
    }

    o_dict = {
        "ad32s": "rupesh",
        "ed532": "Frank",
        "dr501u": "David",
        "ok132d": "Ripal",
        "qw147": "ilesh",
        "av345e": "carls",
    }

    df = pandas.DataFrame.from_dict(d)

    values = []
    def fn(k):
        values.append(o_dict[k])
        return df["GroupID"].str.find(k) != -1
    conditions = list(map(fn, o_dict))

    df["New_column"] = numpy.select(conditions, values, default="NOT IN DIC")
    print(df)
</code>```

Body:
GroupID column has two values one alphanumeric and other is numeric, I want use alphanumeric part of column to create new column, with some condition like if alphanumeric is present in o_dict then it should return value else it should just return "NOT IN DIC"

GroupID
0   ad32s;#1214;#rf343;#4343
1   wd435;#6464;#ed532;#5454
2   av345e:#3132
3   ok132d;#8897
4   tn123h;#0980
5   as845;#657;#un567t;#456;#qw147;#123
6   ok132d;#8897
7   as845;#657;#un567t;#456;#qw147;#123
8   wd435;#6464;#ed532;#5454

o_dict= {"ad32s":"rupesh","ed532":"Frank","dr501u":"David","ok132d":"Ripal",
         "qw147":"ilesh","av345e":'carls'}

below is my code:

def function01(row):
o_dict= {"ad32s":"rupesh","ed532":"Frank","dr501u":"David","ok132d":"Ripal","qw147":"ilesh","av345e":'carls'}
    if element.isalnum():
        if element in o_dict:
            return owner_dict[element]
        else:
            return "NOT IN DIC"
    else:
        continue
df['New_column'] = df.apply(lambda x: function01(x), axis=1)

This code works if the alphanumeric value is at first position but does not work if it is at 3 or 5 position. It works for row 0,2,3,4 6, but does not work for 1,5,7,8.

O/p should have two columns with values from dict which matched with groupid else it should be populated with  "NOT IN DIC".

I not sure what i can do now, is there another approach to get this values ?
is there any search function which can be used to search for this values ??

Thanks for helping :)

Body:
you may want to use numpy.select

    import numpy
    import pandas

    d = {
        "GroupID": [
            "ad32s;#1214;#rf343;#4343",
            "wd435;#6464;#ed532;#5454",
            "av345e:#3132",
            "ok132d;#8897",
            "tn123h;#0980",
            "as845;#657;#un567t;#456;#qw147;#123",
            "ok132d;#8897",
            "as845;#657;#un567t;#456;#qw147;#123",
            "wd435;#6464;#ed532;#5454",
        ]
    }

    o_dict = {
        "ad32s": "rupesh",
        "ed532": "Frank",
        "dr501u": "David",
        "ok132d": "Ripal",
        "qw147": "ilesh",
        "av345e": "carls",
    }

    df = pandas.DataFrame.from_dict(d)

    values = []
    def fn(k):
        values.append(o_dict[k])
        return df["GroupID"].str.find(k) != -1
    conditions = list(map(fn, o_dict))

    df["New_column"] = numpy.select(conditions, values, default="NOT IN DIC")
    print(df)


问:
Send two request simultaneously 1st request with C# WebClient and 2nd request with Ajax
hey guys,
i have a page in asp.net c#, in that im doin' some video upload functionality, so my video upload code is in Page_Load() method and i'm using WebClient to upload a video file.
and i have a animated gif image on page

Now the problem is when Page_Load() method is called my files getting uploaded using WebClient, while that time the Page is not yet render, so i get a blank page.. i want that gif image get animated while uploading is goin' on...

Note: i have to use WebClient's UploadFile() method only.

So i was thinking is there any way that i can run my Upload functionality in new thread and let the page be Rendered.. or can ajax be helpfull in this scenario ??

```<code>protected void Page_Load(object sender, EventArgs e)
{
   UploadFile();//this method actually calls an API which uses WebClient to upload file
}
</code>```

Another problem is to get a track of upload, that API gives a url which sends json response saying how much percent upload completed, so i also what to send request to this upload tracking url while my Uploading is goin' on simultaneously..

答:
Yes, asynchronous pages:

http://msdn.microsoft.com/es-es/magazine/cc163725(en-us).aspx

Body:
hey guys,
i have a page in asp.net c#, in that im doin' some video upload functionality, so my video upload code is in Page_Load() method and i'm using WebClient to upload a video file.
and i have a animated gif image on page

Now the problem is when Page_Load() method is called my files getting uploaded using WebClient, while that time the Page is not yet render, so i get a blank page.. i want that gif image get animated while uploading is goin' on...

Note: i have to use WebClient's UploadFile() method only.

So i was thinking is there any way that i can run my Upload functionality in new thread and let the page be Rendered.. or can ajax be helpfull in this scenario ??

protected void Page_Load(object sender, EventArgs e)
{
   UploadFile();//this method actually calls an API which uses WebClient to upload file
}

Another problem is to get a track of upload, that API gives a url which sends json response saying how much percent upload completed, so i also what to send request to this upload tracking url while my Uploading is goin' on simultaneously..


问:
Can I reuse a pointer after reallocating memory it points to?
I'm new to C. I knew that when I use realloc(), the pointer is deactivated as the new block of memory may be in another address (is it set to null?). But a pointer just stores the value of an address. So can I reuse that pointer to store another address after that? Moreover, can I do this:

```<code>ptr= realloc(ptr, newsize);
</code>```

答:
You can reuse it but you should first check that the reallocation has succeeded.

If the reallocation failed, then after

```<code>ptr= realloc(ptr, newsize);
</code>```

you've lost a reference to the old memory block, i.e., you have most likely created a memory leak.

What you probably want is:

```<code>void *newptr;
if ( (newptr=realloc(ptr,newsize)) ) ptr = newptr;
else /*handle the error*/;
</code>```

Body:
I'm new to C. I knew that when I use realloc(), the pointer is deactivated as the new block of memory may be in another address (is it set to null?). But a pointer just stores the value of an address. So can I reuse that pointer to store another address after that? Moreover, can I do this:

ptr= realloc(ptr, newsize);

Body:
You can reuse it but you should first check that the reallocation has succeeded.

If the reallocation failed, then after

ptr= realloc(ptr, newsize);

you've lost a reference to the old memory block, i.e., you have most likely created a memory leak.

What you probably want is:

void *newptr;
if ( (newptr=realloc(ptr,newsize)) ) ptr = newptr;
else /*handle the error*/;


问:
Display data from MySQL to PHP page problem
I'm trying to display  some specific data from MySQL to the PHP web but I'm always getting 0 results .
the code i used is:</p>

```<code><?php
$conn = mysqli_connect("localhost", "root", "", "summary");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user= .$_SESSION["username"];
$sql = "SELECT money FROM users WHERE username= .$user";
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["money"];
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
</code>```

答:
first of all you should use prepared statement in case to avoid sql injection

try to change code to this:

```<code><?php

// create connection
$conn = new mysqli("localhost", "root", "", "summary");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$user = $_SESSION["username"];
$sql = "SELECT money FROM users WHERE username = ?";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("s",$user);
    if ($stmt->execute()) {
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo $row["money"];
            }
            $stmt->close();
            $conn->close();
        }else{ echo "0 result"; }
    }
}

?>
</code>```

Body:
I'm trying to display  some specific data from MySQL to the PHP web but I'm always getting 0 results .
the code i used is:

<?php
$conn = mysqli_connect("localhost", "root", "", "summary");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user= .$_SESSION["username"];
$sql = "SELECT money FROM users WHERE username= .$user";
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
" . $row["money"];
}
echo "
";
} else { echo "0 results"; }
$conn->close();
?>

Body:
first of all you should use prepared statement in case to avoid sql injection

try to change code to this:

<?php

// create connection
$conn = new mysqli("localhost", "root", "", "summary");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$user = $_SESSION["username"];
$sql = "SELECT money FROM users WHERE username = ?";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("s",$user);
    if ($stmt->execute()) {
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo $row["money"];
            }
            $stmt->close();
            $conn->close();
        }else{ echo "0 result"; }
    }
}

?>


问:
Create Internet Explorer extension changing content of a webpage
I'd like to develop an Internet Explorer extension that changes the content of a specific webpage, like content scripts in Google Chrome. (eg. when I go to the website Google and I search for "car" I'd like to have a div created on the page with the word "car" inside).

I've been looking on SO but haven't found clear evidences if this kind of thing is possible.

What I'm specifically looking for is a clear tutorial or some example of how to do this.

Bruno,

答:
This is one of the best I found. http://www.enhanceie.com/ie/dev.asp It has give sample scripts as well. Which will help you.

Another one is open source and stable version : firebreath

same kind question is also asked How to get started with developing Internet Explorer extensions?


问:
How to check if any application is running in docker container?
How to check if any application is running in docker container ? What is the command for it.</p>

答: A container only runs one process.  If that process exits, the container exits too.  There's not anything to check beyond what you can see with docker ps -a.


问:
How can I get my Audio on my start function to be on a loop so that it plays the whole time during gameplay in javascript?
I am trying to get myMusic that is pulled from my .html file to run on a loop after the start game function is ran and I can't figure out how to do it. I figure there has to be something I can do in the startgame function to the myMusic.play(); but I can't figure it out. any help would be appreciated.

var myMusic = document.getElementById("myMusic");
var myStartSound = document.getElementById("myStartSound");
var myWinSound = document.getElementById("myWinSound");
var myLoseSound = document.getElementById("myLoseSound");
var themeMusic = document.getElementById("themeMusic");
var audio = new Audio("./assets/Sounds/Halo theme.mp3");
window.onload = function(){
    audio.play()
    .then(function () {
        console.log("ahhhhh");

    })
    .catch(function (err) {
        console.log(err);
        audio.currentTime = 1;
        audio.play()
        .then(function () {
            console.log("ahhhhh");

        })
        .catch(function (err) {
            console.log(err);
            audio.currentTime = 1;
            audio.play()
        })
    })

}

//alphabet array
var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
    'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
];

//array for users guessed letters
var guessedLetter = [];
//array for users correct guesses
var correctLetter = [];
//guessed letters that are incorrect
var incorrectGuess = [];

//Below is the functionality of the game
function startGame() {
    numGuesses = 12;
    blanksAndSuccess = [];
    guessedLetter = [];
    incorrectGuess = [];
    audio.pause();
    myMusic.play()
        .then(function () {
            console.log("ahhhhh");

        })
        .catch(function (err) {
  ```

答:
There is an extremely easy way to do it, both in HTML and Javascript.
HTML:

```<code>    <audio src = "" loop = true>
</code>```

Javascript:

```<code>    document.getElementById("audio").loop = true;
</code>```

I also integrated it into a function that plays music, and you can choose to loop it:

```<code>    var makePlayAudio = function(src, looping) {
        var aud = new Audio();
        aud.src = src;
        aud.loop = looping;
        aud.play();
    }
</code>```

I have tested it on chrome.

Body:
There is an extremely easy way to do it, both in HTML and Javascript.
HTML:

    <audio src = "" loop = true>

Javascript:

    document.getElementById("audio").loop = true;

I also integrated it into a function that plays music, and you can choose to loop it:

    var makePlayAudio = function(src, looping) {
        var aud = new Audio();
        aud.src = src;
        aud.loop = looping;
        aud.play();
    }

I have tested it on chrome.


问:
Simple way to combine many observables into one object
I need to build an object from couple of observables that comes from the ngrx state.

```<code>    public readonly comibiedToOneObject$ = zip(
    this.store$.select(selectObs1),
    this.store$.select(selectObs2),
    this.store$.select(selectObs3),

    ...

    this.store$.select(selectObsN),
  ).pipe(
    map(([
           obs1,
           obs2,
           obs3,

            ...

           obsN
         ]) => {
      return {
           obs1,
           obs2,
           obs3,

            ...

           obsN
      };
    }),
  );
</code>```

How can i make this more readable and better code?

答:
```<code>let observables = [selectObs1,selectObs2,selectObs3].map((obs) => this.store$.select(obs));

public readonly comibiedToOneObject$ = forkJoin(observables).pipe(map(res) => ({...res}));
</code>```

Body:
I need to build an object from couple of observables that comes from the ngrx state.

    public readonly comibiedToOneObject$ = zip(
    this.store$.select(selectObs1),
    this.store$.select(selectObs2),
    this.store$.select(selectObs3),

    ...

    this.store$.select(selectObsN),
  ).pipe(
    map(([
           obs1,
           obs2,
           obs3,

            ...

           obsN
         ]) => {
      return {
           obs1,
           obs2,
           obs3,

            ...

           obsN
      };
    }),
  );

How can i make this more readable and better code?


问:
Pydub Split on silence error: UnboundLocalError: local variable 'start_ii' referenced before assignment
I try to get a python code running with the pydub library that should split an audio file on silent parts. The code is pretty short but still I get errors that I can't understand. Thanks a lot for your help:

Complete error message:

```<code>Traceback (most recent call last):
  File "app.py", line 7, in <module>
    chunks = split_on_silence(sound,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pydub/silence.py", line 134, in split_on_silence
    chunks.append(audio_segment[max(start_min, start_ii - keep_silence):
UnboundLocalError: local variable 'start_ii' referenced before assignment
</code>```

Code:

```<code>from os import path
from pydub import AudioSegment
from pydub.silence import split_on_silence

sound = AudioSegment.from_mp3("test5.mp3")
chunks = split_on_silence(sound,
    # must be silent for at least half a second
    min_silence_len=500,

    # consider it silent if quieter than -16 dBFS
    silence_thresh=-16
)

for i, chunk in enumerate(chunks):
    chunk.export("chunk{0}.wav".format(i), format="wav")

</code>```

答: You need to adjust your silence_thresh argument. You can start by assigning it the value you get when you call sound.dBFS, then adjust the value till it works or you.

Body:
I try to get a python code running with the pydub library that should split an audio file on silent parts. The code is pretty short but still I get errors that I can't understand. Thanks a lot for your help:

Complete error message:

Traceback (most recent call last):
  File "app.py", line 7, in <module>
    chunks = split_on_silence(sound,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pydub/silence.py", line 134, in split_on_silence
    chunks.append(audio_segment[max(start_min, start_ii - keep_silence):
UnboundLocalError: local variable 'start_ii' referenced before assignment

Code:

from os import path
from pydub import AudioSegment
from pydub.silence import split_on_silence

sound = AudioSegment.from_mp3("test5.mp3")
chunks = split_on_silence(sound,
    # must be silent for at least half a second
    min_silence_len=500,

    # consider it silent if quieter than -16 dBFS
    silence_thresh=-16
)

for i, chunk in enumerate(chunks):
    chunk.export("chunk{0}.wav".format(i), format="wav")


问:
Android Vector Drawable <text> not support, <tspan> not support
```<code>In icon.svg
ERROR@ line 9 <text> is not supported
ERROR@ line 10 <tspan> is not supported
</code>```

How to export this type of svg to vector drawable? Is this even possible? Or should I look for a new svg?

答: If you are using adobe illustrator, Set 'font' to 'convert to outlines'...worked for me</p>

Body:
In icon.svg
ERROR@ line 9 <text> is not supported
ERROR@ line 10 <tspan> is not supported

How to export this type of svg to vector drawable? Is this even possible? Or should I look for a new svg?


答:
Yes, you can do that. It's nothing inherently wrong with it. However, it can make it impossible to recover from a failed allocation. If you're planning to exit the program if the allocation fails, it (usually) does not matter.

So this is perfectly fine:

```<code>ptr = realloc(ptr, newsize);
if(!ptr) exit(EXIT_FAILURE);
</code>```

And so is this:

```<code>tmpptr = realloc(ptr, newsize);
if(!tmpptr) puts("Allocation failed. Continuing anyway.");
else ptr = tmpptr;
</code>```

Note: It can be argued if it's ok to exit with a memory leak. In most cases, that does not matter, since the operating system will usually clean everything up upon exit. So be aware that in the first example, you will exit with a memory leak.

So if a memory leak does matter to you, even if you're exiting on failure, you can do something like this:

```<code>tmpptr = realloc(ptr, newsize);
if(!tmpptr) {
    free(ptr);
    exit(EXIT_FAILURE);
} else {
    ptr = tmpptr;
}
</code>```

However, do notice that this would only solve the problem for the ptr pointer. If you have a program of any complexity above simple school assignments, chances are pretty high that you have a few other allocations already going on. Keeping track of all that is possible, but far from trivial. Consider this very minimalistic example:

```<code>void foo() {
    void *ptr1 = malloc(SIZE);
    if(!ptr1) exit(EXIT_FAILURE);
    bar();
    free(ptr1);
}

void bar() {
    void *ptr2 = malloc(SIZE);
    if(!ptr2) {
        // Here we should call free on ptr1 to avoid memory leaks, but how?
        exit(EXIT_FAILURE);
    }
    // Do work
    free(ptr2);
}
</code>```

Of course, you could easily rewrite it:

```<code>void foo() {
    void *ptr1 = malloc(SIZE);
    if(!ptr1) exit(EXIT_FAILURE);
    if(!bar()) exit(EXIT_FAILURE);
    free(ptr1);
}

int bar() {
    void *ptr2 = malloc(SIZE);
    if(!ptr2) return 0;
    // Do work
    free(ptr2);
    return 1;
}
</code>```

In this case, it was easy, but keep in mind that this example is VERY trivial.

I would not bother unless I have a very good reason to care. It makes the code messy and is completely unnecessary on modern operating systems. Unless I'm writing code for an environment where it does matter, I would only care if I'm writing a function where I want it to be up to the caller to exit or not.

The bottom line here is that making sure that all allocated resources are freed by the program on exit can be a complete nightmare. And unless you have the need for it and are willing to spend quite a lot of time getting it right, then don't bother.

In practice, dealing with this would require you to take this into account for almost all aspects of the design. And that's very rarely a good tradeoff.

Related question: dangers of _exit() - memory leak?

Title: Can I reuse a pointer after reallocating memory it points to?

Body:
Yes, you can do that. It's nothing inherently wrong with it. However, it can make it impossible to recover from a failed allocation. If you're planning to exit the program if the allocation fails, it (usually) does not matter.

So this is perfectly fine:

ptr = realloc(ptr, newsize);
if(!ptr) exit(EXIT_FAILURE);

And so is this:

tmpptr = realloc(ptr, newsize);
if(!tmpptr) puts("Allocation failed. Continuing anyway.");
else ptr = tmpptr;

Note: It can be argued if it's ok to exit with a memory leak. In most cases, that does not matter, since the operating system will usually clean everything up upon exit. So be aware that in the first example, you will exit with a memory leak.

So if a memory leak does matter to you, even if you're exiting on failure, you can do something like this:

tmpptr = realloc(ptr, newsize);
if(!tmpptr) {
    free(ptr);
    exit(EXIT_FAILURE);
} else {
    ptr = tmpptr;
}

However, do notice that this would only solve the problem for the ptr pointer. If you have a program of any complexity above simple school assignments, chances are pretty high that you have a few other allocations already going on. Keeping track of all that is possible, but far from trivial. Consider this very minimalistic example:

void foo() {
    void *ptr1 = malloc(SIZE);
    if(!ptr1) exit(EXIT_FAILURE);
    bar();
    free(ptr1);
}

void bar() {
    void *ptr2 = malloc(SIZE);
    if(!ptr2) {
        // Here we should call free on ptr1 to avoid memory leaks, but how?
        exit(EXIT_FAILURE);
    }
    // Do work
    free(ptr2);
}

Of course, you could easily rewrite it:

void foo() {
    void *ptr1 = malloc(SIZE);
    if(!ptr1) exit(EXIT_FAILURE);
    if(!bar()) exit(EXIT_FAILURE);
    free(ptr1);
}

int bar() {
    void *ptr2 = malloc(SIZE);
    if(!ptr2) return 0;
    // Do work
    free(ptr2);
    return 1;
}

In this case, it was easy, but keep in mind that this example is VERY trivial.

I would not bother unless I have a very good reason to care. It makes the code messy and is completely unnecessary on modern operating systems. Unless I'm writing code for an environment where it does matter, I would only care if I'm writing a function where I want it to be up to the caller to exit or not.

The bottom line here is that making sure that all allocated resources are freed by the program on exit can be a complete nightmare. And unless you have the need for it and are willing to spend quite a lot of time getting it right, then don't bother.

In practice, dealing with this would require you to take this into account for almost all aspects of the design. And that's very rarely a good tradeoff.

Related question: dangers of _exit() - memory leak?


问:
What's the fastest way to load big image on iPhone?
HI there,

I am building a scrollview which swipes through 100 images of houses.
It works. But.... For every image viewed the allocated memory increases by 2.5 MB. In the end the app crashed because it ran out of memory.

I use the code for decompress the image.....
- (void)decompress {
    const CGImageRef cgImage = [self CGImage];

```<code>const int width = CGImageGetWidth(cgImage);
const int height = CGImageGetHeight(cgImage);

const CGColorSpaceRef colorspace = CGImageGetColorSpace(cgImage);
const CGContextRef context = CGBitmapContextCreate(
                                                   NULL, /* Where to store the data. NULL = don’t care */
                                                   width, height, /* width & height */
                                                   8, width * 4, /* bits per component, bytes per row */
                                                   colorspace, kCGImageAlphaNoneSkipFirst);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgImage);
CGContextRelease(context);
</code>```

}

but its not working,very time to take load the image.

答: You need to do some memory optimization. Here is a logic to save memory but you need to implement it your self. Don't add all the images to scrollview just add initally 5 images. Suppose user is viewing image1 and now he reaches to image3 when user reaches image 3 remove image1 from scrollView so that the memory can be freed. And as user scrolls forward add next images like when user is on image4 add image6 and do vice versa. When user is goes from image4 to image3 remove image6 from memory. This way there is only 5 images will be in memory.</p>

Body:
HI there,

I am building a scrollview which swipes through 100 images of houses.
It works. But.... For every image viewed the allocated memory increases by 2.5 MB. In the end the app crashed because it ran out of memory.

I use the code for decompress the image.....
- (void)decompress {
    const CGImageRef cgImage = [self CGImage];

const int width = CGImageGetWidth(cgImage);
const int height = CGImageGetHeight(cgImage);

const CGColorSpaceRef colorspace = CGImageGetColorSpace(cgImage);
const CGContextRef context = CGBitmapContextCreate(
                                                   NULL, /* Where to store the data. NULL = don’t care */
                                                   width, height, /* width & height */
                                                   8, width * 4, /* bits per component, bytes per row */
                                                   colorspace, kCGImageAlphaNoneSkipFirst);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgImage);
CGContextRelease(context);

}

but its not working,very time to take load the image.


问:
The request was aborted: Could not create SSL/TLS secure channel
My customer has informed my of issues with their SSL and Internet Explorer. They said they get trust issues when accessing the URL.

I am accessing JSON through HTTPS. The website sits on one server and I am using the console app on my local machine. I am trying to bypass the SSL Cert, however, my code still fails.

Can I alter HttpWebRequest to fix this problem?

I get this error using this code:

```<code>    // You must change the URL to point to your Web server.
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "GET";
        req.AllowAutoRedirect = true;

        // allows for validation of SSL conversations
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

        WebResponse respon = req.GetResponse();
        Stream res = respon.GetResponseStream();

        string ret = "";
        byte[] buffer = new byte[1048];
        int read = 0;
        while ((read = res.Read(buffer, 0, buffer.Length)) > 0)
        {
            //Console.Write(Encoding.ASCII.GetString(buffer, 0, read));
            ret += Encoding.ASCII.GetString(buffer, 0, read);
        }
        return ret;
</code>```

答:
Also received "Could not create SSL/TLS secure channel" error.  This is what worked for me.
System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)3072;</p>

Body:
My customer has informed my of issues with their SSL and Internet Explorer. They said they get trust issues when accessing the URL.

I am accessing JSON through HTTPS. The website sits on one server and I am using the console app on my local machine. I am trying to bypass the SSL Cert, however, my code still fails.

Can I alter HttpWebRequest to fix this problem?

I get this error using this code:

    // You must change the URL to point to your Web server.
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "GET";
        req.AllowAutoRedirect = true;

        // allows for validation of SSL conversations
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

        WebResponse respon = req.GetResponse();
        Stream res = respon.GetResponseStream();

        string ret = "";
        byte[] buffer = new byte[1048];
        int read = 0;
        while ((read = res.Read(buffer, 0, buffer.Length)) > 0)
        {
            //Console.Write(Encoding.ASCII.GetString(buffer, 0, read));
            ret += Encoding.ASCII.GetString(buffer, 0, read);
        }
        return ret;