问:
Java:using apache POI how to convert ms word file to pdf?
By using apache POI how to convert ms word file to pdf?

I an using the following code but its not working giving errors I guess I am importing the wrong classes?

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.apache.poi.hslf.record.Document;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class TestCon {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        POIFSFileSystem fs = null;
         Document document = new Document();

         try {
             System.out.println("Starting the test");
             fs = new POIFSFileSystem(new FileInputStream("/document/test2.doc"));

             HWPFDocument doc = new HWPFDocument(fs);
             WordExtractor we = new WordExtractor(doc);

             OutputStream file = new FileOutputStream(new File("/document/test.pdf"));

             PdfWriter writer = PdfWriter.getInstance(document, file);

             Range range = doc.getRange();
             document.open();
             writer.setPageEmpty(true);
             document.newPage();
             writer.setPageEmpty(true);

             String[] paragraphs = we.getParagraphText();
             for (int i = 0; i < paragraphs.length; i++) {

                 org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
                // CharacterRun run = pr.getCharacterRun(i);
                // run.setBold(true);
                // run.setCapitalized(true);
                // run.setItalic(true);
                 paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");
             System.out.println("Length:" + paragraphs[i].length());
             System.out.println("Paragraph" + i + ": " + paragraphs[i].toString());

             // add the paragraph to the document
             document.add(new Paragraph(paragraphs[i]));
             }

             System.out.println("Document testing completed");
         } catch (Exception e) {
             System.out.println("Exception during test");
             e.printStackTrace();
         } finally {
                         // close the document
            document.close();
                     }
         }
    }
</code>```

答:
Got It solved</p>

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class TestCon {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        POIFSFileSystem fs = null;
        Document document = new Document();

         try {
             System.out.println("Starting the test");
             fs = new POIFSFileSystem(new FileInputStream("D:/Resume.doc"));

             HWPFDocument doc = new HWPFDocument(fs);
             WordExtractor we = new WordExtractor(doc);

             OutputStream file = new FileOutputStream(new File("D:/test.pdf"));

             PdfWriter writer = PdfWriter.getInstance(document, file);

             Range range = doc.getRange();
             document.open();
             writer.setPageEmpty(true);
             document.newPage();
             writer.setPageEmpty(true);

             String[] paragraphs = we.getParagraphText();
             for (int i = 0; i < paragraphs.length; i++) {

                 org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
                // CharacterRun run = pr.getCharacterRun(i);
                // run.setBold(true);
                // run.setCapitalized(true);
                // run.setItalic(true);
                 paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");
             System.out.println("Length:" + paragraphs[i].length());
             System.out.println("Paragraph" + i + ": " + paragraphs[i].toString());

             // add the paragraph to the document
             document.add(new Paragraph(paragraphs[i]));
             }

             System.out.println("Document testing completed");
         } catch (Exception e) {
             System.out.println("Exception during test");
             e.printStackTrace();
         } finally {
                         // close the document
            document.close();
                     }
         }
    }
</code>```

Body:
By using apache POI how to convert ms word file to pdf?

I an using the following code but its not working giving errors I guess I am importing the wrong classes?

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.apache.poi.hslf.record.Document;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class TestCon {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        POIFSFileSystem fs = null;
         Document document = new Document();

         try {
             System.out.println("Starting the test");
             fs = new POIFSFileSystem(new FileInputStream("/document/test2.doc"));

             HWPFDocument doc = new HWPFDocument(fs);
             WordExtractor we = new WordExtractor(doc);

             OutputStream file = new FileOutputStream(new File("/document/test.pdf"));

             PdfWriter writer = PdfWriter.getInstance(document, file);

             Range range = doc.getRange();
             document.open();
             writer.setPageEmpty(true);
             document.newPage();
             writer.setPageEmpty(true);

             String[] paragraphs = we.getParagraphText();
             for (int i = 0; i < paragraphs.length; i++) {

                 org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
                // CharacterRun run = pr.getCharacterRun(i);
                // run.setBold(true);
                // run.setCapitalized(true);
                // run.setItalic(true);
                 paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");
             System.out.println("Length:" + paragraphs[i].length());
             System.out.println("Paragraph" + i + ": " + paragraphs[i].toString());

             // add the paragraph to the document
             document.add(new Paragraph(paragraphs[i]));
             }

             System.out.println("Document testing completed");
         } catch (Exception e) {
             System.out.println("Exception during test");
             e.printStackTrace();
         } finally {
                         // close the document
            document.close();
                     }
         }
    }

Body:
Got It solved

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class TestCon {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        POIFSFileSystem fs = null;
        Document document = new Document();

         try {
             System.out.println("Starting the test");
             fs = new POIFSFileSystem(new FileInputStream("D:/Resume.doc"));

             HWPFDocument doc = new HWPFDocument(fs);
             WordExtractor we = new WordExtractor(doc);

             OutputStream file = new FileOutputStream(new File("D:/test.pdf"));

             PdfWriter writer = PdfWriter.getInstance(document, file);

             Range range = doc.getRange();
             document.open();
             writer.setPageEmpty(true);
             document.newPage();
             writer.setPageEmpty(true);

             String[] paragraphs = we.getParagraphText();
             for (int i = 0; i < paragraphs.length; i++) {

                 org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
                // CharacterRun run = pr.getCharacterRun(i);
                // run.setBold(true);
                // run.setCapitalized(true);
                // run.setItalic(true);
                 paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");
             System.out.println("Length:" + paragraphs[i].length());
             System.out.println("Paragraph" + i + ": " + paragraphs[i].toString());

             // add the paragraph to the document
             document.add(new Paragraph(paragraphs[i]));
             }

             System.out.println("Document testing completed");
         } catch (Exception e) {
             System.out.println("Exception during test");
             e.printStackTrace();
         } finally {
                         // close the document
            document.close();
                     }
         }
    }


来源: stackexchange

问:
Binding Validation.HasError property in MVVM
I am currently implementing a ValidationRule to check if some invalid character are in a TextBox. I am happy that setting the class I have implemented that inherits ValidationRule on my TextBox sets it in red when such characters are found, but I would also like to use the Validation.HasError property or the Validation.Errors property to pop a messagebox telling the user that there are errors in the various textboxes in the page.

Is there a way to bind a property in my ViewModel to the Validation.HasError and/or to the Validation.Errors properties in order for me to have access to them in my ViewModel?

Here is my error style for the TextBox:

```<code><Style x:Key="ErrorValidationTextBox" TargetType="{x:Type pres:OneTextBox}">
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <DockPanel LastChildFill="True">
                    <TextBlock DockPanel.Dock="Right"
                    Foreground="Red"
                    FontSize="12pt"
                    Text="{Binding ElementName=MyAdorner,
                           Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                    </TextBlock>
                    <AdornedElementPlaceholder x:Name="MyAdorner"/>
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Here is how I declare my TextBox (OneTextBox encapsulates the regular WPF TextBox) in my XAML:

```<code><pres:OneTextBox Watermark="Name..." Margin="85,12,0,0" Style="{StaticResource ErrorValidationTextBox}"
                 AcceptsReturn="False" MaxLines="1" Height="22" VerticalAlignment="Top"
                 HorizontalAlignment="Left" Width="300" >
    <pres:OneTextBox.Text>
        <Binding Path="InterfaceSpecification.Name" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <interfaceSpecsModule:NoInvalidCharsRule/>
            </Binding.ValidationRules>
        </Binding>
    </pres:OneTextBox.Text>
</pres:OneTextBox>
</code>```

答:
all perfect work set NotifyOnValidationError="True" on binding;
(or maybe with binding group also possible)

then use

```<code><Button IsEnabled="{Binding ElementName=tbPeriod, Path=(Validation.HasError)}"
</code>```

sample with one textBox:

<val:RangeRulecan be changed to ms sample agerangerule etc

```<code><TextBox MaxLength="5" x:Name="tbPeriod" HorizontalAlignment="Left" VerticalAlignment="Top" Width="162" Margin="10,10,0,0" Style="{StaticResource TextBoxInError}">
            <TextBox.Text>
                <Binding Path="ReportPeriod" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
                    <Binding.ValidationRules>
                        <val:RangeRule Min="70" Max="5000" />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently implementing a ValidationRule to check if some invalid character are in a TextBox. I am happy that setting the class I have implemented that inherits ValidationRule on my TextBox sets it in red when such characters are found, but I would also like to use the Validation.HasError property or the Validation.Errors property to pop a messagebox telling the user that there are errors in the various textboxes in the page.

Is there a way to bind a property in my ViewModel to the Validation.HasError and/or to the Validation.Errors properties in order for me to have access to them in my ViewModel?

Here is my error style for the TextBox:

Here is how I declare my TextBox (OneTextBox encapsulates the regular WPF TextBox) in my XAML:

<pres:OneTextBox Watermark="Name..." Margin="85,12,0,0" Style="{StaticResource ErrorValidationTextBox}"
                 AcceptsReturn="False" MaxLines="1" Height="22" VerticalAlignment="Top"
                 HorizontalAlignment="Left" Width="300" >
    <pres:OneTextBox.Text>
        <Binding Path="InterfaceSpecification.Name" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <interfaceSpecsModule:NoInvalidCharsRule/>
            </Binding.ValidationRules>
        </Binding>
    </pres:OneTextBox.Text>
</pres:OneTextBox>

Body:
all perfect work set NotifyOnValidationError="True" on binding;
(or maybe with binding group also possible)

then use

<Button IsEnabled="{Binding ElementName=tbPeriod, Path=(Validation.HasError)}"

sample with one textBox:

<val:RangeRulecan be changed to ms sample agerangerule etc

<TextBox MaxLength="5" x:Name="tbPeriod" HorizontalAlignment="Left" VerticalAlignment="Top" Width="162" Margin="10,10,0,0" Style="{StaticResource TextBoxInError}">
            <TextBox.Text>
                <Binding Path="ReportPeriod" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
                    <Binding.ValidationRules>
                        <val:RangeRule Min="70" Max="5000" />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>

ContentLicense: CC BY-SA 4.0


问:
Angular Material & Flex: How set max width for whole app?
I want to set the width of the app content so that when screen sizes changes, the content stays in the middle and there are whitespace on left and right side. I am using Angular Material & Angular Flex. I have observed this is a common design in various websites including stack overflow. Pardon me if this is a common question and I'm unable to find it.

Here is an example:
I want the app content to be within the lines.

答:
You can use max-width for the style of your app-root

Sample:

```<code>.entire-app {
    max-width: 750px;

    /* Centers the class */
    margin-left: auto;
    margin-right: auto;
}
</code>```

Body:
You can use max-width for the style of your app-root

Sample:

.entire-app {
    max-width: 750px;

    /* Centers the class */
    margin-left: auto;
    margin-right: auto;
}


问:
Pack divs of random width and height together as tightly as possible
I don't know if this can be done fairly simply just with CSS and a bit of JavaScript, like I'm trying to do below. Some people have said it can't be done. I'm hoping you can show me the way.

I want to pack divs of random width and height together as tightly as possible. I want to create a sequence of about 100 divs with random widths and heights (random within a given range of values) such that they 'float' together to create more or less as little white space as possible.

Here's the idea. But this creates a lot of white space between/among the divs, which is not what we want.

init();

function init() {
  var n = 100;
  var minWidth = 20;
  var maxWidth = 50;
  var minHeight = 10;
  var maxHeight = 40;
  var container = document.getElementById("container");
  for (var i = 0; i < n; i++) {
    var width = randomInteger(minWidth, maxWidth);
    var height = randomInteger(minHeight, maxHeight);
    var div = document.createElement("div");
    div.classList.add("aDiv");
    div.style.width = width + 'px';
    div.style.height = height + 'px';
    var color = randomColor();
    div.style.backgroundColor = 'hsl(' + color.hue + ',' + color.saturation + '%,' + color.lightness + '%)';
    container.appendChild(div);
  }
}

function randomColor() {
  var hueCenter = 167;
  var hueRange = 25;
  var saturationCenter = 50;
  var saturationRange = 15;
  var lightnessCenter = 50;
  var lightnessRange = 20;
  var hue = randomInteger(hueCenter - hueRange, hueCenter + hueRange);
  var saturation = randomInteger(saturationCenter - saturationRange, saturationCenter + saturationRange);
  var lightness = randomInteger(lightnessCenter - lightnessRange, lightnessCenter + lightnessRange);
  return {
    hue: hue,
    saturation: saturation,
    lightness: lightness
  };

}

function randomInteger(min, max) {
  // Returns a random integer between min and max.
  return Math.floor(Math.random() * (max - min + 1)) + min;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.aDiv {
  display: inline-block;
  float: left;
}</code>```

```

答:
If you can use display: flex; on the div with ID container without any additional property on the children divs (i.e. divs with class aDiv), it would help. You only CSS would be:

#container {
display: flex;
flex-wrap: wrap;
align-content: flex-end; //put the appropriate value to position your children divs
}
```

Here in flexbox, the property align-content is the key. It is used for aligning items with multiple lines.

The possible values are:

align-content: flex-start | flex-end | center | space-between | space-around | stretch;

Hope this might help you.

Body:
I don't know if this can be done fairly simply just with CSS and a bit of JavaScript, like I'm trying to do below. Some people have said it can't be done. I'm hoping you can show me the way.

I want to pack divs of random width and height together as tightly as possible. I want to create a sequence of about 100 divs with random widths and heights (random within a given range of values) such that they 'float' together to create more or less as little white space as possible.

Here's the idea. But this creates a lot of white space between/among the divs, which is not what we want.

init();

function init() {
  var n = 100;
  var minWidth = 20;
  var maxWidth = 50;
  var minHeight = 10;
  var maxHeight = 40;
  var container = document.getElementById("container");
  for (var i = 0; i < n; i++) {
    var width = randomInteger(minWidth, maxWidth);
    var height = randomInteger(minHeight, maxHeight);
    var div = document.createElement("div");
    div.classList.add("aDiv");
    div.style.width = width + 'px';
    div.style.height = height + 'px';
    var color = randomColor();
    div.style.backgroundColor = 'hsl(' + color.hue + ',' + color.saturation + '%,' + color.lightness + '%)';
    container.appendChild(div);
  }
}

function randomColor() {
  var hueCenter = 167;
  var hueRange = 25;
  var saturationCenter = 50;
  var saturationRange = 15;
  var lightnessCenter = 50;
  var lightnessRange = 20;
  var hue = randomInteger(hueCenter - hueRange, hueCenter + hueRange);
  var saturation = randomInteger(saturationCenter - saturationRange, saturationCenter + saturationRange);
  var lightness = randomInteger(lightnessCenter - lightnessRange, lightnessCenter + lightnessRange);
  return {
    hue: hue,
    saturation: saturation,
    lightness: lightness
  };

}

function randomInteger(min, max) {
  // Returns a random integer between min and max.
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

.aDiv {
  display: inline-block;
  float: left;
}

Body:
If you can use display: flex; on the div with ID container without any additional property on the children divs (i.e. divs with class aDiv), it would help. You only CSS would be:

#container {
display: flex;
flex-wrap: wrap;
align-content: flex-end; //put the appropriate value to position your children divs
}

Here in flexbox, the property align-content is the key. It is used for aligning items with multiple lines.

The possible values are:

align-content: flex-start | flex-end | center | space-between | space-around | stretch;

Hope this might help you.


问:
How can I put this DRY code into a for loop?
I am formatting a legend in pyplot, and have successfully gotten the output I want. However, I'm trying to figure out how to format this code into a for loop.

This is the code I am trying to loop:

```<code>L.get_texts()[0].set_text('Global')
L.get_texts()[1].set_text('Bangkok')
L.get_texts()[2].set_text('NYC')
L.get_texts()[3].set_text('Perth')
L.get_texts()[4].set_text('Quito')
L.get_texts()[5].set_text('Santiago')
L.get_texts()[6].set_text('Singapore')
L.get_texts()[7].set_text('Tianjin')
</code>```

I can loop for each index[0,7], but I can't figure out how to loop for the set_text('argument') as well. This is what I have tried so far:

```<code>legend_labels = ['Global', 'Bangkok', 'NYC', 'Perth', 'Quito', 'Santiago',
'Singapore', 'Tianjin']

for i in range(8):
L.get_texts()[i].set_text(legend_labels)
</code>```

I made the list, legend_labels, that I want to loop through. I've tried a few different nested for loops, but can't seem to get it working.

From the code that I am trying now this is the output I get:
Notice only 'Tianjin' gets printed on the legend.

This is my desired output: Each item in list is printed on the legend.

答:
You'd need to assign the i'th label to the i't text:

```<code>for i in range(8):
    L.get_texts()[i].set_text(legend_labels[i])
</code>```

More pythonic would be

```<code>for text, label in zip(L.get_texts(), legend_labels):
    text.set_text(label)
</code>```

Body:
I am formatting a legend in pyplot, and have successfully gotten the output I want. However, I'm trying to figure out how to format this code into a for loop.

This is the code I am trying to loop:

L.get_texts()[0].set_text('Global')
L.get_texts()[1].set_text('Bangkok')
L.get_texts()[2].set_text('NYC')
L.get_texts()[3].set_text('Perth')
L.get_texts()[4].set_text('Quito')
L.get_texts()[5].set_text('Santiago')
L.get_texts()[6].set_text('Singapore')
L.get_texts()[7].set_text('Tianjin')

I can loop for each index[0,7], but I can't figure out how to loop for the set_text('argument') as well. This is what I have tried so far:

legend_labels = ['Global', 'Bangkok', 'NYC', 'Perth', 'Quito', 'Santiago',
'Singapore', 'Tianjin']

for i in range(8):
L.get_texts()[i].set_text(legend_labels)

I made the list, legend_labels, that I want to loop through. I've tried a few different nested for loops, but can't seem to get it working.

From the code that I am trying now this is the output I get:
Notice only 'Tianjin' gets printed on the legend.

This is my desired output: Each item in list is printed on the legend.

Body:
You'd need to assign the i'th label to the i't text:

for i in range(8):
    L.get_texts()[i].set_text(legend_labels[i])

More pythonic would be

for text, label in zip(L.get_texts(), legend_labels):
    text.set_text(label)


问:
NestJS passing Authorization header to HttpService
I have a NestJS application which acts as a proxy between a front-end and multiple other back-ends.

I basically want to be able to pass a specific header (Authorization) from incoming @Req (requests) in the controller to the HttpService that then talks to the other back-ends.

user controller (has access to request) ->
user service (injects httpService that somehow already picks the Authorization header) -> External backends.

Right now I need to extract the token from @Headers and then pass token to service which has to paste it to all HttpService calls.

Thanks in advance!

答:
I'm not sure if this will help you, but maybe if you get the header from the controller and put it in your services function...

// Controller:

```<code>@Get()
getAll(@Request() req){
    const header = req.headers;
    return this._zoneService.sendToHttp(header);
}
</code>```

Maybe microservices can be better ?

Body:
I'm not sure if this will help you, but maybe if you get the header from the controller and put it in your services function...

// Controller:

@Get()
getAll(@Request() req){
    const header = req.headers;
    return this._zoneService.sendToHttp(header);
}

Maybe microservices can be better ?


问:
Changing sign-in name in AAD B2C
I'm trying to implement Change Sign-in Name flow from AAD B2C samples. Basically the policy works but the problem is that the user is still logged in after changing his e-mail.

In my understanding changing the primary identity must invalidate all issued tokens/sessions immediately and force the user to re-authenticate. How come this can be secure and isn't addressed in the sample? How can I do it? I could redirect the request to the B2C sign-out endpoint but here is another issue:

When a user clicks "Change Sign-In Name" link he gets redirected to the policy endpoint with a specified redirect_uri query string param. In my case it's https://localhost:44300. The problem is he gets redirected back to my site when he finishes the flow and when he cancels the flow and I cannot distinguish between the two as there seems to be nothing in the request to check.

So, how can I get the user back to https://localhost:44300 if he cancels the flow (the email isn't changed) and perform Single Sign-Out if he finishes the flow?

答:
Why should changing a username invalidate the session? I can only agree with password change. B2C has no understanding of what is happening (except for password changes) it simply does what you’ve asked. All journeys issue a token at the end, you can put a self asserted page and disable the continue button, then use JavaScript to send the user to the app’s logout route if this is what you want.

In the successful policy execution, you get a token back with the unique policy id.

In a failure you get an error sent to the app. Use this to distinguish between them.

To manage the user cancelling, send an encoded state parameter with the auth request, it’ll be returned with the “cancel error” (AADB2C error user cancelled” to your app, then do the logout. Seems like very poor UX and no security gains.

Title: Changing sign-in name in AAD B2C


问:
Two JSFiddles with the exact same code but one works and the other doesn't
The following SJFiddle works fine.

http://jsfiddle.net/JMPerez/62wafrm7/

I created a second SJFiddle to test it and copied everything (HTML/CSS/JS) exactly the same from the first one. I also included the same resources but it doesn't work.

https://jsfiddle.net/kennethcode/dz1tubf6/

HTML is the same for both

```<code><div class="container">
    <h1>Displaying User Data</h1>
    <p>Log in with your Spotify account and this demo will display information about you fetched using the Spotify Web API</p>
    <button class="btn btn-primary" id="btn-login">Login</button>
    <div id="result"></div>
</div>
<script id="result-template" type="text/x-handlebars-template">
    <dl>
      <img src="{{images.0.url}}">
      <dt>User Name</dt>
      <dd>{{id}}</dd>
      <dt>Display Name</dt>
      <dd>{{display_name}}</dd>
      <dt>Country</dt>
      <dd>{{country}}</dd>
      <dt>Followers</dt>
      <dd>{{followers.total}}</dd>
      <dt>Profile</dt>
      <dd><a href="{{external_urls.spotify}}" target="_blank">{{external_urls.spotify}}</a></dd>
      <dt>Email</dt>
      <dd>{{email}}</dd>
      <dt>Product</dt>
      <dd>{{product}}</dd>
    </dl>
</script>
</code>```

JavaScript is the same for both

```<code>(function() {

    function login(callback) {
        var CLIENT_ID = '6b284830006843e7ae7b170725715aed';
        var REDIRECT_URI = 'http://jmperezperez.com/spotify-oauth-jsfiddle-proxy/';
        function getLoginURL(scopes) {
            return 'https://accounts.spotify.com/authorize?client_id=' + CLIENT_ID +
              '&redirect_uri=' + encodeURIComponent(REDIRECT_URI) +
              '&scope=' + encodeURIComponent(scopes.join(' ')) +
              '&response_type=token';
        }

        var url = getLoginURL([
            'user-read-email'
        ]);

        var width = 450,
            height = 730,
            left = (screen.width / 2) - (width / 2),
            top = (screen.height / 2) - (height / 2);

        window.addEventListener("message", function(event) {
            var hash = JSON.parse(event.data);
            if (hash.type == 'access_token') {
                callback(hash.access_token);
            }
        }, false);

        var w = window.open(url,
                            'Spotify',
                            'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left
                           );

    }

    function getUserData(accessToken) {
        return $.ajax({
            url: 'https://api.spotify.com/v1/me',
            headers: {
               'Authorization': 'Bearer ' + accessToken
            }
        });
    }

    var templateSource = document.getElementById('result-template').innerHTML,
        template = Handlebars.compile(templateSource),
        resultsPlaceholder = document.getElementById('result'),
        loginButton = document.getElementById('btn-login');

    loginButton.addEventListener('click', function() {
        login(function(accessToken) {
            getUserData(accessToken)
                .then(function(response) {
                    loginButton.style.display = 'none';
                    resultsPlaceholder.innerHTML = template(response);
                });
            });
    });

})();
</code>```

CSS is the same for both

```<code>.container {
    margin: 1em;
}

img {
    margin-bottom: 1em;
}
</code>```

Any clues why this might be happening? Thanks

答:
Just add manually the required scripts in the top of html section:

```<code>  <link rel="stylesheet" type="text/css" href="https://developer.spotify.com/web-api/static/css/cached.css">
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script>
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.min.js"></script>
</code>```

Body:
The following SJFiddle works fine.

http://jsfiddle.net/JMPerez/62wafrm7/

I created a second SJFiddle to test it and copied everything (HTML/CSS/JS) exactly the same from the first one. I also included the same resources but it doesn't work.

https://jsfiddle.net/kennethcode/dz1tubf6/

HTML is the same for both

Displaying User Data

Log in with your Spotify account and this demo will display information about you fetched using the Spotify Web API

    <button class="btn btn-primary" id="btn-login">Login</button>

JavaScript is the same for both

(function() {

    function login(callback) {
        var CLIENT_ID = '6b284830006843e7ae7b170725715aed';
        var REDIRECT_URI = 'http://jmperezperez.com/spotify-oauth-jsfiddle-proxy/';
        function getLoginURL(scopes) {
            return 'https://accounts.spotify.com/authorize?client_id=' + CLIENT_ID +
              '&redirect_uri=' + encodeURIComponent(REDIRECT_URI) +
              '&scope=' + encodeURIComponent(scopes.join(' ')) +
              '&response_type=token';
        }

        var url = getLoginURL([
            'user-read-email'
        ]);

        var width = 450,
            height = 730,
            left = (screen.width / 2) - (width / 2),
            top = (screen.height / 2) - (height / 2);

        window.addEventListener("message", function(event) {
            var hash = JSON.parse(event.data);
            if (hash.type == 'access_token') {
                callback(hash.access_token);
            }
        }, false);

        var w = window.open(url,
                            'Spotify',
                            'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left
                           );

    }

    function getUserData(accessToken) {
        return $.ajax({
            url: 'https://api.spotify.com/v1/me',
            headers: {
               'Authorization': 'Bearer ' + accessToken
            }
        });
    }

    var templateSource = document.getElementById('result-template').innerHTML,
        template = Handlebars.compile(templateSource),
        resultsPlaceholder = document.getElementById('result'),
        loginButton = document.getElementById('btn-login');

    loginButton.addEventListener('click', function() {
        login(function(accessToken) {
            getUserData(accessToken)
                .then(function(response) {
                    loginButton.style.display = 'none';
                    resultsPlaceholder.innerHTML = template(response);
                });
            });
    });

})();

CSS is the same for both

.container {
    margin: 1em;
}

img {
    margin-bottom: 1em;
}

Any clues why this might be happening? Thanks

Body:
Just add manually the required scripts in the top of html section:

  <link rel="stylesheet" type="text/css" href="https://developer.spotify.com/web-api/static/css/cached.css">
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script>
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.min.js"></script>


问:
Find the closest point on a cylinder surface to a given line in c++
I need a function that will find the closest point on a cylinder surface to a given line. Let's say the cylinder is centered along the z-axis({0, 0, 0}) and defined by its Radius R and half-length Z and the (infinite) line is defined by two 3D points A(x1,x2) and B(y1,y2). What is the best way to compute the point on the cylinder surface which is closest to this line? </p>

答:
explanation figure

See the figure above. The idea is:

1- Because the cylinder is on the Z axis, we can project everything on
  the (X,Y) plane, so we can work in 2D. So for example: A (-2,1,10)
  becomes A(-2,1). Also the cylinder is treated as a circle.

Let's call (D) the infinite line passing by A and B. And (C) the
  circle (representing the cylinder in 2D)

2- We draw a triangle formed of 3 points: A, B, and the center of the
  circle (C) (being the origin (0,0)),
  like shown in the figure.

3- Let (L) be the line passing by the center of (C) and perpendicular
  to (D) like shown in the figure.

4- The closest point will be the intersection of (C) and (L)

Now all the above can be done by simple mathematical equations.

First some definitions:

ax + by + c = 0 : is equation of a 2D line in the (X,Y) plane

Having 2 points A and B on a line (D) we can calculate the direction vector Vd of (D)

Vd ( B.x-A.x, B.y-A.y)

With that direction vector we can calculate the equation (ax+by+c) of (D).

a = Vd.y

  b = -Vd.x

  c = Vd.xA.y - A.xVd.y

With that equation we can calculate the normal vector Vn of (D)

Vn (a, b)

Applying these formulas on your question:

1- We calculate the direction vector Vd of the infinite line (D) passing by A and B.

2- From Vd we get the equation of (D)

3- From the equation we get Vn

4- Because Vn is "pointing" from (D) to the (C), we must flip It by multiplying each coordinate with (-1). So we create a new direction Vector: Vd2 ( -Vn.x, -Vn.y)

5- Now Vd2 is the direction vector of (L) which isthe red line in the figure.

6- Now we just have to get the point on the circle (C) (cylinder) following Vd2 which will be the closest point on the circle surface which is closest to the line (D).

To do that we normalize Vd2 and we multiply It by the circle (C) radius. We will get the closest point's X and Y coordinates: X = Vd.normalized * (C).radius and Y = Vd.normalized * (C).radius.

7- Now you got the closest point put only in 2d, let's call It point J. So you have J's x and y coordinates.
To get the z coordinate you replace x and y in the line 3D equation with J's x and y, you solve it and get the z coordinate of J.

The code below is written in C# and tested visually in Unity 3D. It should be simple to write in C++ after understanding what is written above.

Note: here Vector2 is also used to hold the coordinates of 2d points not only 2d vectors. It is just a class that has 2 properties: int x, and int y. And droite means line but in french

```<code>    public Transform A, B ;
    public Transform cylinder ;
    public Transform closest ;

    Vector3 pointA ;
    Vector3 pointB ;

    Vector2 a, b ;
    Vector2 vd, vn ;

    Droite d ;
    Cylinder c ;

    Vector2 inter;

    public void Start () {
        c = new Cylinder (0.5f, 10);
    }

    public void Update () {
        pointA = A.transform.localPosition;
        pointB = B.transform.localPosition;

        a = (Vector2) pointA;
        b = (Vector2) pointB;
        vd = b-a;

        d = new Droite (pointA, vd);
        d.cal_euqation ();

        Vector3 result = closest_point_on_cylinder (d,c);

        closest.transform.localPosition = result;

    }

    public Vector2 closest_point_on_cylinder (Droite d, Cylinder c){
        Droite d2= new Droite (Vector2.zero, d.vn);
        return Vector2.one * (-d2.vd.normalized) * c.r;
    }

}

public class Droite {

    public float a,b,c;
    public Vector2 pointA, vd, vn;

    public Droite (Vector2 _pointA, Vector2 _vd){
        pointA = _pointA;
        vd = _vd ;
    }

    public void cal_euqation () {
        a = vd.y;
        b = -vd.x;
        c = (vd.x*pointA.y - pointA.x*vd.y);

        vn = new Vector2 (a,b);
    }

    public float getX (float y){
        return -(b*y + c) / a ;
    }

}

public class Cylinder {

    public float x,y,h,r; // s  y  height  radius

    public Cylinder (float _r, float _h){
        r = _r ;
        h = _h;
    }

}
</code>```

Body:
explanation figure

See the figure above. The idea is:

1- Because the cylinder is on the Z axis, we can project everything on
  the (X,Y) plane, so we can work in 2D. So for example: A (-2,1,10)
  becomes A(-2,1). Also the cylinder is treated as a circle.

Let's call (D) the infinite line passing by A and B. And (C) the
  circle (representing the cylinder in 2D)

2- We draw a triangle formed of 3 points: A, B, and the center of the
  circle (C) (being the origin (0,0)),
  like shown in the figure.

3- Let (L) be the line passing by the center of (C) and perpendicular
  to (D) like shown in the figure.

4- The closest point will be the intersection of (C) and (L)

Now all the above can be done by simple mathematical equations.

First some definitions:

ax + by + c = 0 : is equation of a 2D line in the (X,Y) plane

Having 2 points A and B on a line (D) we can calculate the direction vector Vd of (D)

Vd ( B.x-A.x, B.y-A.y)

With that direction vector we can calculate the equation (ax+by+c) of (D).

a = Vd.y

  b = -Vd.x

  c = Vd.xA.y - A.xVd.y

With that equation we can calculate the normal vector Vn of (D)

Vn (a, b)

Applying these formulas on your question:

1- We calculate the direction vector Vd of the infinite line (D) passing by A and B.

2- From Vd we get the equation of (D)

3- From the equation we get Vn

4- Because Vn is "pointing" from (D) to the (C), we must flip It by multiplying each coordinate with (-1). So we create a new direction Vector: Vd2 ( -Vn.x, -Vn.y)

5- Now Vd2 is the direction vector of (L) which isthe red line in the figure.

6- Now we just have to get the point on the circle (C) (cylinder) following Vd2 which will be the closest point on the circle surface which is closest to the line (D).

To do that we normalize Vd2 and we multiply It by the circle (C) radius. We will get the closest point's X and Y coordinates: X = Vd.normalized * (C).radius and Y = Vd.normalized * (C).radius.

7- Now you got the closest point put only in 2d, let's call It point J. So you have J's x and y coordinates.
To get the z coordinate you replace x and y in the line 3D equation with J's x and y, you solve it and get the z coordinate of J.

The code below is written in C# and tested visually in Unity 3D. It should be simple to write in C++ after understanding what is written above.

Note: here Vector2 is also used to hold the coordinates of 2d points not only 2d vectors. It is just a class that has 2 properties: int x, and int y. And droite means line but in french

    public Transform A, B ;
    public Transform cylinder ;
    public Transform closest ;

    Vector3 pointA ;
    Vector3 pointB ;

    Vector2 a, b ;
    Vector2 vd, vn ;

    Droite d ;
    Cylinder c ;

    Vector2 inter;

    public void Start () {
        c = new Cylinder (0.5f, 10);
    }

    public void Update () {
        pointA = A.transform.localPosition;
        pointB = B.transform.localPosition;

        a = (Vector2) pointA;
        b = (Vector2) pointB;
        vd = b-a;

        d = new Droite (pointA, vd);
        d.cal_euqation ();

        Vector3 result = closest_point_on_cylinder (d,c);

        closest.transform.localPosition = result;

    }

    public Vector2 closest_point_on_cylinder (Droite d, Cylinder c){
        Droite d2= new Droite (Vector2.zero, d.vn);
        return Vector2.one * (-d2.vd.normalized) * c.r;
    }

}

public class Droite {

    public float a,b,c;
    public Vector2 pointA, vd, vn;

    public Droite (Vector2 _pointA, Vector2 _vd){
        pointA = _pointA;
        vd = _vd ;
    }

    public void cal_euqation () {
        a = vd.y;
        b = -vd.x;
        c = (vd.x*pointA.y - pointA.x*vd.y);

        vn = new Vector2 (a,b);
    }

    public float getX (float y){
        return -(b*y + c) / a ;
    }

}

public class Cylinder {

    public float x,y,h,r; // s  y  height  radius

    public Cylinder (float _r, float _h){
        r = _r ;
        h = _h;
    }

}


问:
LinkedList inside shared memory
I'm trying to share a linked list inside shared memory but I'm having some issues when using fork(), without fork() it works perfectly but I must have at least a child process.

If there aren't children it works but when I create a child process and use addValue function the result is segmentation fault.

The code is not so good because of a lot of changes.
I've tried to use malloc but with processes it cannot be done.

Searching in some forums there are different ideas about share linkedlist but none of them works.

Another doubt that I have is about shmget(), I have to pass sizeof(struct Request) but sometimes they passsizeof(struct Request)*n if there is a max pool of nodes that the linkedlist can handle but sometimes they use shmget with different keys like this code that I wrote. So the other question is: sizeof()*n or size() with multiple shmget keys?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <unistd.h>
#include <sys/ipc.h>

struct Request{
  int value;
  struct Request *next;
}Request;

void errorHandler(char *msg){
  perror(msg);
  exit(EXIT_FAILURE);
}

struct Request *getNode(key_t key){
  int shmid = shmget(key, sizeof(struct Request), IPC_CREAT | 0660);
  if(shmid==-1){
    errorHandler("SHMGET7");
  }

  struct Request *req = shmat(shmid, NULL, 0);
  if(req==(void *)-1){
    errorHandler("SHMAT9");
  }

  return req;
}

void addValue(key_t headKey, key_t newKey, int value){
  struct Request *head = getNode(headKey);
  while(head->next!=NULL){
    head = head->next;
  }
  struct Request *node = getNode(newKey);
  node->value = value;
  node->next = NULL;

  head->next = node;
}

void printNodes(key_t key){
  struct Request *head = getNode(key);
  while(head!=NULL){
    printf("%d\n", head->value);
    head = head->next;
  }
}

int main(int argc, char *argv[]){
  key_t key = 1234;
  struct Request *req = getNode(key);
  req->value = -1;
  req->next = NULL;

  key_t newKey = 250;
  addValue(key, newKey, 100);
  newKey = 251;
  addValue(key, newKey, 101);

  for(int i=0;i<2;i++){
    pid_t pid = fork();
    if(pid==-1){
      errorHandler("FORK");
    }else if(pid==0){
      newKey = 252+i;
      addValue(key, newKey, 101);

      exit(0);
    }

    sleep(1);
  }

  for(int i=0;i<2;i++){
    wait(NULL);
  }

  printNodes(key);
  printf("end\n");

  return 0;
}
</code>```

For shmdt I've got to loop linkedlist and shmdt every node?

答:
If there aren't children it works but when I create a child process and use addValue function the result is segmentation fault.

An address returned by shmat(<id>, NULL, <flg>) is only valid for the current process, to use it in an other process has an undefined behavior.

For the first fork the list contains valid addresses coming from the parent because the  child inherits the attached shared memory segments. But at the second turn (i valuing 1) the second fork try to use an address which is not valid for it nor the main process later in printNodes because coming from the first fork and only valid for it. For the same reason supposing the main process is able to get the address return by shmap for the second fork, that address cannot be dereferenced too.

I have to pass sizeof(struct Request) but sometimes ...

this is the right size because you want to allocate one cell, using malloc the needed size is the same.

One way to solve your problem is to use for next the key rather than an address not valid out of the current process and its children.

Doing the minimal changes from your code, using the key 0 for the NULL pointer, the modified definitions are :

```<code>struct Request{
  int value;
  key_t next;
} Request;
</code>```

and

```<code>void addValue(key_t headKey, key_t newKey, int value){
  struct Request *head = getNode(headKey);

  while(head->next!=0){
    headKey = head->next;
    head = getNode(headKey);
  }

  struct Request *node = getNode(newKey);

  node->value = value;
  node->next = 0;

  head->next = newKey;
}

void printNodes(key_t key) {
  while (key != 0) {
    struct Request *head = getNode(key);

    printf("%d\n", head->value);
    key = head->next;
  }
}
</code>```

and at the beginning or main :

```<code>req->next = 0;
</code>```

After that, compilation and execution (I added #include <sys/wait.h>) :

```<code>pi@raspberrypi:/tmp $ gcc -g -Wall l.c
pi@raspberrypi:/tmp $ ./a.out
i=0
i=1
-1
100
101
101
101
end
pi@raspberrypi:/tmp $
</code>```

Title: LinkedList inside shared memory

Body:
I'm trying to share a linked list inside shared memory but I'm having some issues when using fork(), without fork() it works perfectly but I must have at least a child process.

If there aren't children it works but when I create a child process and use addValue function the result is segmentation fault.

The code is not so good because of a lot of changes.
I've tried to use malloc but with processes it cannot be done.

Searching in some forums there are different ideas about share linkedlist but none of them works.

Another doubt that I have is about shmget(), I have to pass sizeof(struct Request) but sometimes they passsizeof(struct Request)*n if there is a max pool of nodes that the linkedlist can handle but sometimes they use shmget with different keys like this code that I wrote. So the other question is: sizeof()*n or size() with multiple shmget keys?

#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <unistd.h>
#include <sys/ipc.h>

struct Request{
  int value;
  struct Request *next;
}Request;

void errorHandler(char *msg){
  perror(msg);
  exit(EXIT_FAILURE);
}

struct Request *getNode(key_t key){
  int shmid = shmget(key, sizeof(struct Request), IPC_CREAT | 0660);
  if(shmid==-1){
    errorHandler("SHMGET7");
  }

  struct Request *req = shmat(shmid, NULL, 0);
  if(req==(void *)-1){
    errorHandler("SHMAT9");
  }

  return req;
}

void addValue(key_t headKey, key_t newKey, int value){
  struct Request *head = getNode(headKey);
  while(head->next!=NULL){
    head = head->next;
  }
  struct Request *node = getNode(newKey);
  node->value = value;
  node->next = NULL;

  head->next = node;
}

void printNodes(key_t key){
  struct Request *head = getNode(key);
  while(head!=NULL){
    printf("%d\n", head->value);
    head = head->next;
  }
}

int main(int argc, char *argv[]){
  key_t key = 1234;
  struct Request *req = getNode(key);
  req->value = -1;
  req->next = NULL;

  key_t newKey = 250;
  addValue(key, newKey, 100);
  newKey = 251;
  addValue(key, newKey, 101);

  for(int i=0;i<2;i++){
    pid_t pid = fork();
    if(pid==-1){
      errorHandler("FORK");
    }else if(pid==0){
      newKey = 252+i;
      addValue(key, newKey, 101);

      exit(0);
    }

    sleep(1);
  }

  for(int i=0;i<2;i++){
    wait(NULL);
  }

  printNodes(key);
  printf("end\n");

  return 0;
}

For shmdt I've got to loop linkedlist and shmdt every node?

Body:
If there aren't children it works but when I create a child process and use addValue function the result is segmentation fault.

An address returned by shmat(<id>, NULL, <flg>) is only valid for the current process, to use it in an other process has an undefined behavior.

For the first fork the list contains valid addresses coming from the parent because the  child inherits the attached shared memory segments. But at the second turn (i valuing 1) the second fork try to use an address which is not valid for it nor the main process later in printNodes because coming from the first fork and only valid for it. For the same reason supposing the main process is able to get the address return by shmap for the second fork, that address cannot be dereferenced too.

I have to pass sizeof(struct Request) but sometimes ...

this is the right size because you want to allocate one cell, using malloc the needed size is the same.

One way to solve your problem is to use for next the key rather than an address not valid out of the current process and its children.

Doing the minimal changes from your code, using the key 0 for the NULL pointer, the modified definitions are :

struct Request{
  int value;
  key_t next;
} Request;

and

void addValue(key_t headKey, key_t newKey, int value){
  struct Request *head = getNode(headKey);

  while(head->next!=0){
    headKey = head->next;
    head = getNode(headKey);
  }

  struct Request *node = getNode(newKey);

  node->value = value;
  node->next = 0;

  head->next = newKey;
}

void printNodes(key_t key) {
  while (key != 0) {
    struct Request *head = getNode(key);

    printf("%d\n", head->value);
    key = head->next;
  }
}

and at the beginning or main :

req->next = 0;

After that, compilation and execution (I added #include <sys/wait.h>) :

pi@raspberrypi:/tmp $ gcc -g -Wall l.c
pi@raspberrypi:/tmp $ ./a.out
i=0
i=1
-1
100
101
101
101
end
pi@raspberrypi:/tmp $


问:
How to get x-axis value in chart as string?
I am trying to plot a graph using chart.js where y-axis values are numbers and x-axis values are strings. I have given the code that i have written, but it does not plot the string values.
Appreciate your help.

window.onload = function() {
  var dataPoints7 = [];

  var chart7 = new CanvasJS.Chart("chartContainer7", {
    animationEnabled: true,
    theme: "light2",
    title: {
      text: "Cases in States"
    },
    axisY: {
      title: "Cases",
      titleFontSize: 24
    },
    data: [{
      type: "line",
      yValueFormatString: "#,### Cases",
      dataPoints: dataPoints7
    }]
  });
  fetch("https://api.covid19india.org/data.json", {
      "method": "GET"
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      for (var i = 1; i < data.statewise.length; i++) {
        dataPoints7.push({
          x: data.statewise[i].state,
          y: parseInt(data.statewise[i].confirmed)
        });
      }
      chart7.render();
    });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<div id="chartContainer7" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

</html></code>```

答:
For your case you should supply label property not x value and also i believe you should use column charts for this purpose.

You might see some labels not showing up.You can either set the angle or increase the width of chart to make it visible.

Try running this snippet

window.onload = function() {
  var dataPoints7 = [];

  var chart7 = new CanvasJS.Chart("chartContainer7", {
    animationEnabled: true,
    theme: "light2",
    title: {
      text: "Cases in States"
    },
    axisY: {
      title: "Cases",
      titleFontSize: 24
    },
    axisX: {
      labelAngle: 180
    },
    data: [{
      type: "line",
      yValueFormatString: "#,### Cases",
      dataPoints: dataPoints7
    }]
  });
  fetch("https://api.covid19india.org/data.json", {
      "method": "GET"
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      for (var i = 1; i < data.statewise.length; i++) {
        dataPoints7.push({
          label: data.statewise[i].state,
          y: parseInt(data.statewise[i].confirmed)
        });
      }
      chart7.render();
    });

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<div id="chartContainer7" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

</html></code>```

Body:
I am trying to plot a graph using chart.js where y-axis values are numbers and x-axis values are strings. I have given the code that i have written, but it does not plot the string values.
Appreciate your help.

window.onload = function() {
  var dataPoints7 = [];

  var chart7 = new CanvasJS.Chart("chartContainer7", {
    animationEnabled: true,
    theme: "light2",
    title: {
      text: "Cases in States"
    },
    axisY: {
      title: "Cases",
      titleFontSize: 24
    },
    data: [{
      type: "line",
      yValueFormatString: "#,### Cases",
      dataPoints: dataPoints7
    }]
  });
  fetch("https://api.covid19india.org/data.json", {
      "method": "GET"
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      for (var i = 1; i < data.statewise.length; i++) {
        dataPoints7.push({
          x: data.statewise[i].state,
          y: parseInt(data.statewise[i].confirmed)
        });
      }
      chart7.render();
    });
}

<!DOCTYPE html>

Body:
For your case you should supply label property not x value and also i believe you should use column charts for this purpose.

You might see some labels not showing up.You can either set the angle or increase the width of chart to make it visible.

Try running this snippet

window.onload = function() {
  var dataPoints7 = [];

  var chart7 = new CanvasJS.Chart("chartContainer7", {
    animationEnabled: true,
    theme: "light2",
    title: {
      text: "Cases in States"
    },
    axisY: {
      title: "Cases",
      titleFontSize: 24
    },
    axisX: {
      labelAngle: 180
    },
    data: [{
      type: "line",
      yValueFormatString: "#,### Cases",
      dataPoints: dataPoints7
    }]
  });
  fetch("https://api.covid19india.org/data.json", {
      "method": "GET"
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      for (var i = 1; i < data.statewise.length; i++) {
        dataPoints7.push({
          label: data.statewise[i].state,
          y: parseInt(data.statewise[i].confirmed)
        });
      }
      chart7.render();
    });

}

<!DOCTYPE html>
<html lang="en">

<div id="chartContainer7" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

</html>


问:
I think my code is clean but I end up with 0 lines
My code in not working as intended and I have no clue

```<code>def fun(line):
    list_three = []
    list_more = []
    index = 0
    for item in line:
        if len(item) == 3:
            list_three.append(item)
            index += 1
            return item
        elif len(item) > 3:
            list_more.append(item)
            index += 1
            return "this string has more than three char"
        else:
            index += 1
            return None
</code>```

verbs = ["eat", "look", "dance"]
fun(verbs)

答:
Your code doesn't have any syntax errors,
but, to begin with, you should call the function with a list-argument.

I have added a few lines, marked #temp,
which illustrate what happens.

Here, the function looks at the first item, "4444",
goes to the elif command, prints the list list_more
and returns the returnvalue.

```<code>    #!/usr/bin/python3
    """
    study.py
    """
    def fun(line):
        list_three = []
        list_more = []
        index = 0
        for item in line:
            if len(item) == 3:
                list_three.append(item)
                print("list_three",list_three)  #temp
                index += 1
                return item
            elif len(item) > 3:
                list_more.append(item)
                print("list_more",list_more)  #temp
                index += 1
                return "this string has more than three char"
            else:
                index += 1
                return None

    print(fun([ "4444", "333", "55555"]))  #temp
</code>```

Body:
My code in not working as intended and I have no clue

def fun(line):
    list_three = []
    list_more = []
    index = 0
    for item in line:
        if len(item) == 3:
            list_three.append(item)
            index += 1
            return item
        elif len(item) > 3:
            list_more.append(item)
            index += 1
            return "this string has more than three char"
        else:
            index += 1
            return None

verbs = ["eat", "look", "dance"]
fun(verbs)

Body:
Your code doesn't have any syntax errors,
but, to begin with, you should call the function with a list-argument.

I have added a few lines, marked #temp,
which illustrate what happens.

Here, the function looks at the first item, "4444",
goes to the elif command, prints the list list_more
and returns the returnvalue.

    #!/usr/bin/python3
    """
    study.py
    """
    def fun(line):
        list_three = []
        list_more = []
        index = 0
        for item in line:
            if len(item) == 3:
                list_three.append(item)
                print("list_three",list_three)  #temp
                index += 1
                return item
            elif len(item) > 3:
                list_more.append(item)
                print("list_more",list_more)  #temp
                index += 1
                return "this string has more than three char"
            else:
                index += 1
                return None

    print(fun([ "4444", "333", "55555"]))  #temp


问:
Linkedin share api not picking up open-graph meta tags
I am sharing an url "https://timesofindia.indiatimes.com/trend-tracking/jaitley-promises-robust-tax-regime-for-investors/articleshow/62741496.cms?utm_source=linkedin.com&utm_medium=social&utm_campaign=TEST-LINKEDIN" via share api, but no image is picked up from the og:image tag (i.e. meta property="og:image" content="https://example.com" ).

But when i am trying to share the same url from linkedin admin page, it is picking up the image. This means that the image follows all the size-standards and other things required by linkedin.

Then why is the share api not picking up image url from the open graph tag.

答:
If you think your share is properly formatted, but it's not working, first thing I would do is head on over to the LinkedIn Post Inspector, which will examine your URL and look for problems.

But, your URL does look right!  Are you sharing like this, with proper URL encoding?

```<code>https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Ftimesofindia.indiatimes.com%2Ftrend-tracking%2Fjaitley-promises-robust-tax-regime-for-investors%2Farticleshow%2F62741496.cms%3Futm_source%3Dlinkedin.com%26utm_medium%3Dsocial%26utm_campaign%3DTEST-LINKEDIN
</code>```

Because this link works for me!  Take a look:

Sometimes you just need another pair of eyes on the same problem!  Hope this helps!

Body:
If you think your share is properly formatted, but it's not working, first thing I would do is head on over to the LinkedIn Post Inspector, which will examine your URL and look for problems.

But, your URL does look right!  Are you sharing like this, with proper URL encoding?

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Ftimesofindia.indiatimes.com%2Ftrend-tracking%2Fjaitley-promises-robust-tax-regime-for-investors%2Farticleshow%2F62741496.cms%3Futm_source%3Dlinkedin.com%26utm_medium%3Dsocial%26utm_campaign%3DTEST-LINKEDIN

Because this link works for me!  Take a look:

Sometimes you just need another pair of eyes on the same problem!  Hope this helps!


问:
how to check a radio button by clicking on a table row?
I am working on a data table which will be filled with Json data and I want to make the entire row clickable and when I click on the line, the radio button associated with it must be checked and return the value of the radio button

var elements= document.getElementsByTagName('tr');
for(var i=0; i<elements.length;i++)
{

  (elements)[i].addEventListener("click", function(){

   const rbs = document.querySelectorAll('input[name="choice"]');
            let selectedValue;
            for (const rb of rbs) {
                if (rb.checked) {
                    selectedValue = rb.value;
                    break;
                }
            }
            alert(selectedValue);

});
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tr:hover{
background-color:gray;
cursor:pointer;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        Firstname
        Lastname
        Email

        <input type="radio" value="Jhon doe" name="name"/>
        John
        Doe
        john@example.com

      <input type="radio" value="mary Moe" name="name" />
        Mary
        Moe
        mary@example.com

      <input type="radio" value="July dooley" name="name" />
        July
        Dooley
        july@example.com

```

答:
You can do this easily by just using the current this context like:

```<code>const rb = this.querySelector('input[name="choice"]');
rb.checked = true;
</code>```

Working Demo:

var elements = document.getElementsByTagName('tr');
for (var i = 0; i < elements.length; i++) {

  (elements)[i].addEventListener("click", function() {
    const rb = this.querySelector('input[name="choice"]');
    rb.checked = true;

    let selectedValue = rb.value;
    alert(selectedValue);
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tr:hover {
  background-color: gray;
  cursor: pointer;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      Firstname
      Lastname
      Email

      <input type="radio" value="Jhon doe" name="choice" />
      John
      Doe
      john@example.com

      <input type="radio" value="mary Moe" name="choice" />
      Mary
      Moe
      mary@example.com

      <input type="radio" value="July dooley" name="choice" />
      July
      Dooley
      july@example.com

```

Body:
I am working on a data table which will be filled with Json data and I want to make the entire row clickable and when I click on the line, the radio button associated with it must be checked and return the value of the radio button

var elements= document.getElementsByTagName('tr');
for(var i=0; i<elements.length;i++)
{

  (elements)[i].addEventListener("click", function(){

   const rbs = document.querySelectorAll('input[name="choice"]');
            let selectedValue;
            for (const rb of rbs) {
                if (rb.checked) {
                    selectedValue = rb.value;
                    break;
                }
            }
            alert(selectedValue);

});
}

tr:hover{
background-color:gray;
cursor:pointer;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        Firstname
        Lastname
        Email

        <input type="radio" value="Jhon doe" name="name"/>
        John
        Doe
        john@example.com

      <input type="radio" value="mary Moe" name="name" />
        Mary
        Moe
        mary@example.com

      <input type="radio" value="July dooley" name="name" />
        July
        Dooley
        july@example.com

Body:
You can do this easily by just using the current this context like:

const rb = this.querySelector('input[name="choice"]');
rb.checked = true;

Working Demo:

var elements = document.getElementsByTagName('tr');
for (var i = 0; i < elements.length; i++) {

  (elements)[i].addEventListener("click", function() {
    const rb = this.querySelector('input[name="choice"]');
    rb.checked = true;

    let selectedValue = rb.value;
    alert(selectedValue);
  });
}

tr:hover {
  background-color: gray;
  cursor: pointer;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-bordered">
  <thead>
    <tr>
      <th></th>
      <th>Firstname</th>
      <th>Lastname</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="radio" value="Jhon doe" name="choice" /></td>
      <td>John</td>
      <td>Doe</td>
      <td>john@example.com</td>
    </tr>
    <tr>
      <td><input type="radio" value="mary Moe" name="choice" /></td>
      <td>Mary</td>
      <td>Moe</td>
      <td>mary@example.com</td>
    </tr>
    <tr>
      <td><input type="radio" value="July dooley" name="choice" /></td>
      <td>July</td>
      <td>Dooley</td>
      <td>july@example.com</td>
    </tr>
  </tbody>
</table>


答:
```<code>legend_labels = ['Global',
                 'Bangkok',
                 'NYC',
                 'Perth',
                 'Quito',
                 'Santiago',
                 'Singapore',
                 'Tianjin'
                 ]

for i in range(8):
    L.get_texts()[i].set_text(legend_labels[i])
</code>```

Title: How can I put this DRY code into a for loop?


问:
Trying to combine Django inline-formset, django-select2 and django-dynamic-formset
I am trying to combine all mentioned in the title with always something missing. I've gone through all possible posts that I could find and still am not sure what to do.

So I basically have two models, which are master-detail. When I use plain django stuff - everything is OK, but in detail model I have more than 10000 elements, and classic select field is impossible to use. So I switched to select2 through django-select2 module. I somehow managed to put everything together, but then had to add django-dynamic-formset to be able to dynamically add new rows if I need more than three that django renders by default. Again, I managed to make everything work, had some issues while I put everything together, but now I have two issues.

If I leave this peace of code in jquery.formset.js:

```<code>insertDeleteLink(row);
</code>```

I will get this message:

```<code>jquery.formset.js:67 Uncaught ReferenceError: deleteButtonHTML is not defined
    at insertDeleteLink (jquery.formset.js:67)
    at HTMLTableRowElement.<anonymous> (jquery.formset.js:146)
    at Function.each (jquery-2.2.4.min.js:2)
    at n.fn.init.each (jquery-2.2.4.min.js:2)
    at n.fn.init.$.fn.formset (jquery.formset.js:124)
    at HTMLDocument.<anonymous> (1:92)
    at i (jquery-2.2.4.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-2.2.4.min.js:2)
    at Function.ready (jquery-2.2.4.min.js:2)
    at HTMLDocument.J (jquery-2.2.4.min.js:2)
</code>```

If I remove it, delete links for rows are not generated, even though I have in my template

```<code><td>{% if form.instance.id %}{{ form.DELETE }}{% endif %}</td>
</code>```

So, I ended with half-solution, I can add rows, i can fill them, select2 finally works as intended, but I cannot delete rows, not when I create new items and not when I delete old ones.

The other issue is that if django creates three rows in detail table (by design) and I fill just first one it saves all three rows. Not sure how to delete rows while saving formset (tried to do form.delete while doing POST, but it doesn't work).

I can of course add more code if it would help.

答:
Assuming most current jquery.formset.js from github, it needs a fix
'deleteButtonHTML' to 'delButtonHTML' that is so far not in the regular repo
https://github.com/Dowsley/django-dynamic-formset/commit/1a781fd6b1a7a5f6348b43097983773f0d2a69de</p>

Body:
I am trying to combine all mentioned in the title with always something missing. I've gone through all possible posts that I could find and still am not sure what to do.

So I basically have two models, which are master-detail. When I use plain django stuff - everything is OK, but in detail model I have more than 10000 elements, and classic select field is impossible to use. So I switched to select2 through django-select2 module. I somehow managed to put everything together, but then had to add django-dynamic-formset to be able to dynamically add new rows if I need more than three that django renders by default. Again, I managed to make everything work, had some issues while I put everything together, but now I have two issues.

If I leave this peace of code in jquery.formset.js:

insertDeleteLink(row);

I will get this message:

jquery.formset.js:67 Uncaught ReferenceError: deleteButtonHTML is not defined
    at insertDeleteLink (jquery.formset.js:67)
    at HTMLTableRowElement.<anonymous> (jquery.formset.js:146)
    at Function.each (jquery-2.2.4.min.js:2)
    at n.fn.init.each (jquery-2.2.4.min.js:2)
    at n.fn.init.$.fn.formset (jquery.formset.js:124)
    at HTMLDocument.<anonymous> (1:92)
    at i (jquery-2.2.4.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-2.2.4.min.js:2)
    at Function.ready (jquery-2.2.4.min.js:2)
    at HTMLDocument.J (jquery-2.2.4.min.js:2)

If I remove it, delete links for rows are not generated, even though I have in my template

{% if form.instance.id %}{{ form.DELETE }}{% endif %}

So, I ended with half-solution, I can add rows, i can fill them, select2 finally works as intended, but I cannot delete rows, not when I create new items and not when I delete old ones.

The other issue is that if django creates three rows in detail table (by design) and I fill just first one it saves all three rows. Not sure how to delete rows while saving formset (tried to do form.delete while doing POST, but it doesn't work).

I can of course add more code if it would help.


问:
How to acces user detail in template in django
I want check whether logged in  user is doctor or patient i tried the following method to check that thing,but did not succeed can any one help me.

model.py

forms.py

index.html

output

or what does this error means:

```<code>Could not parse the remainder: '=='Doctor'' from 'user.user_type=='Doctor''
</code>```

答:
use this , because tab it's %s as Strings </p>

```<code>user.user_type == 'Doctor'

user.user_type == 'Patient'
</code>```

Body:
I want check whether logged in  user is doctor or patient i tried the following method to check that thing,but did not succeed can any one help me.

model.py

forms.py

index.html

output

or what does this error means:

Could not parse the remainder: '=='Doctor'' from 'user.user_type=='Doctor''

Body:
use this , because tab it's %s as Strings

user.user_type == 'Doctor'

user.user_type == 'Patient'


问:
resize images in php with imagemagick on 1&1 hosting
I am running out of memory when allowing users to resize images of modern day 12MP or higher cameras. Even some pictures that are only 900kb in size take up a lot more room in memory because it's based on pixel size (i think) so ...

I have SSH access to a 1&1 shared server and I followed their instructions to upload imagemagick and configure/make/install it into a directory on my server. Now what do I have to do in php to do the same thing as

```<code>$originalImage = imagecreatefromjpeg($src);
$finalImage = imagecreatetruecolor($newWidth,$newHeight);
imagecopyresampled($finalImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
imagejpeg($finalImage,$saveDest,$jpeg_quality);
</code>```

the variables are hopefully self explanitory. I was trying to find my way through installing the imagick extension but i got really lost when i read about PECL and PEAR and I really don't want to screw up the working php installation somehow.

答:
Update php.ini file:

```<code>memory_limit = 2048M
</code>```

Body:
I am running out of memory when allowing users to resize images of modern day 12MP or higher cameras. Even some pictures that are only 900kb in size take up a lot more room in memory because it's based on pixel size (i think) so ...

I have SSH access to a 1&1 shared server and I followed their instructions to upload imagemagick and configure/make/install it into a directory on my server. Now what do I have to do in php to do the same thing as

$originalImage = imagecreatefromjpeg($src);
$finalImage = imagecreatetruecolor($newWidth,$newHeight);
imagecopyresampled($finalImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
imagejpeg($finalImage,$saveDest,$jpeg_quality);

the variables are hopefully self explanitory. I was trying to find my way through installing the imagick extension but i got really lost when i read about PECL and PEAR and I really don't want to screw up the working php installation somehow.

Body:
Update php.ini file:

memory_limit = 2048M


问:
How to resize an image to fit in the browser window?
This seems trivial but after all the research and coding I can't get it to work. Conditions are:

The browser window size is unknown. So please don't propose a solution involving absolute pixel sizes.

The image's original dimensions are unknown, and may or may not already fit the browser window.

The image is vertically and horizontally centered.

The image proportions must be conserved.

The image must be displayed in its entirety in the window (no cropping.)

I do not wish scrollbars to appear (and they shouldn't if the image fits.)

The image automatically resizes when the window dimensions change, to occupy all the available space without being larger than its original size.

Basically what I want is this:

```<code>.fit {
  max-width: 99%;
  max-height: 99%;
}
<img class="fit" src="pic.png">
</code>```

The problem with the code above is that it doesn't work: the pic takes all the vertical space it needs by adding a vertical scroll bar.

At my disposal is PHP, Javascript, JQuery but I'd kill for a CSS-only solution. I don't care if it doesn't work in IE.

答:
Use this code in your style tag</p>

```<code><style>
html {
  background: url(imagename) no-repeat center center fixed;
  background-size: cover;
  height: 100%;
  overflow: hidden;
}
</style>
</code>```

Body:
This seems trivial but after all the research and coding I can't get it to work. Conditions are:

The browser window size is unknown. So please don't propose a solution involving absolute pixel sizes.

The image's original dimensions are unknown, and may or may not already fit the browser window.

The image is vertically and horizontally centered.

The image proportions must be conserved.

The image must be displayed in its entirety in the window (no cropping.)

I do not wish scrollbars to appear (and they shouldn't if the image fits.)

The image automatically resizes when the window dimensions change, to occupy all the available space without being larger than its original size.

Basically what I want is this:

.fit {
  max-width: 99%;
  max-height: 99%;
}

The problem with the code above is that it doesn't work: the pic takes all the vertical space it needs by adding a vertical scroll bar.

At my disposal is PHP, Javascript, JQuery but I'd kill for a CSS-only solution. I don't care if it doesn't work in IE.

Body:
Use this code in your style tag

<style>
html {
  background: url(imagename) no-repeat center center fixed;
  background-size: cover;
  height: 100%;
  overflow: hidden;
}
</style>


问:
automapper multi objects to one object
I have two sub class that I need to copy a List element from into a master object

public Class Foo1 : Anote
{
  public bool Ison { get; set;}
  public List<Anote>Anotes { get; private set;}

  public Foo1()
  {
    this.Anotes = new List<Anote>();
  }
}

public Class Foo2 : Bnote
{
  public bool Ison { get; set;}
  public List<Bnote>Anotes { get; private set;}

  public Foo2()
  {
    this.Anotes = new List<Bnote>();
  }
}

public Class Foo3 : Cnote
{
   public bool Ison { get; set;}
   public List<Cnote>Anotes { get; private set;}
   public List<Cnote>Bnotes { get; private set; }

}
```

<p>I will be retreiving data from a database and putting this data into Foo1 and Foo2. I then need
to Map the List data from Foo1 and Foo2 into the List elements in Foo3. </p>

<p>I have done </p>

<pre class="lang-cs prettyprint-override"><code>Foo1A foo1a = new Foo1A();
Foo2A foo2a = new Foo2A();

Mapper.CreateMap<Foo1, Foo1A>();
Mapper.CreateMap<Foo2, Foo2A>();
Mapper.Map<Foo1, Foo2A>(foo1, foo1a);
Mapper.Map<Foo2, Foo2A>(foo2, foo2a);
</code>```

and this works but what I need to do is

Map the List Anotes in Foo1 to the List Anotes in Foo3
  Map the List Anotes in Foo2 to the List Bnotes in Foo3.

答:
The accepted answer didn't feel like an acceptable solution for my situation. I was falling asleep last night and had this thought:

Lets say you want to map your two classes, Foo1 and Foo2 to Foo3

public Class Foo1 : Anote
{
  public bool Ison { get; set;}
  public List<Anote>Anotes { get; private set;}

  public Foo1()
  {
    this.Anotes = new List<Anote>();
  }
}
```

<p>+</p>

<pre class="lang-cs prettyprint-override"><code>public Class Foo2 : Bnote
{
  public bool Ison { get; set;}
  public List<Bnote>Anotes { get; private set;}

  public Foo2()
  {
    this.Anotes = new List<Bnote>();
  }
}
</code>```

=

public Class Foo3 : Cnote
{
   public bool Ison { get; set;}
   public List<Cnote>Anotes { get; private set;}
   public List<Cnote>Bnotes { get; private set; }

}
```

<p>All you really need is another wrapper class for Automapper purposes.</p>

<pre class="lang-cs prettyprint-override"><code>public class Foo1And2 {
    public Foo1 Foo1 {get;set;}
    public Foo2 Foo2 {get;set;}
}
</code>```

And then define the mapping:

CreateMap<Foo1And2, Foo3>().ConvertUsing(x => ConvertFoo1And2ToFoo3(x));
```

<pre class="lang-cs prettyprint-override"><code>public Foo3 ConvertFoo1And2ToFoo3(Foo1And2 foo1And2)
{
    return new Foo3
    {
        Ison = foo1And2.Foo1.Ison && foo1And2.Foo2.Ison,
        Anotes = foo1And2.Foo1.Anotes,
        Bnotes = foo1And2.Foo2.Bnotes,
    };
}
</code>```

And use it

var foo3 = Map<Foo3>(new Foo1And2
{
    Foo1 = foo1,
    Foo2 = foo2,
});
```

Title: automapper multi objects to one object

Body:
I have two sub class that I need to copy a List element from into a master object

public Class Foo1 : Anote
{
  public bool Ison { get; set;}
  public List<Anote>Anotes { get; private set;}

  public Foo1()
  {
    this.Anotes = new List<Anote>();
  }
}

public Class Foo2 : Bnote
{
  public bool Ison { get; set;}
  public List<Bnote>Anotes { get; private set;}

  public Foo2()
  {
    this.Anotes = new List<Bnote>();
  }
}

public Class Foo3 : Cnote
{
   public bool Ison { get; set;}
   public List<Cnote>Anotes { get; private set;}
   public List<Cnote>Bnotes { get; private set; }

}

I will be retreiving data from a database and putting this data into Foo1 and Foo2. I then need
to Map the List data from Foo1 and Foo2 into the List elements in Foo3.

I have done

Foo1A foo1a = new Foo1A();
Foo2A foo2a = new Foo2A();

Mapper.CreateMap<Foo1, Foo1A>();
Mapper.CreateMap<Foo2, Foo2A>();
Mapper.Map<Foo1, Foo2A>(foo1, foo1a);
Mapper.Map<Foo2, Foo2A>(foo2, foo2a);

and this works but what I need to do is

Map the List Anotes in Foo1 to the List Anotes in Foo3
  Map the List Anotes in Foo2 to the List Bnotes in Foo3.

Body:
The accepted answer didn't feel like an acceptable solution for my situation. I was falling asleep last night and had this thought:

Lets say you want to map your two classes, Foo1 and Foo2 to Foo3

public Class Foo1 : Anote
{
  public bool Ison { get; set;}
  public List<Anote>Anotes { get; private set;}

  public Foo1()
  {
    this.Anotes = new List<Anote>();
  }
}

+

public Class Foo2 : Bnote
{
  public bool Ison { get; set;}
  public List<Bnote>Anotes { get; private set;}

  public Foo2()
  {
    this.Anotes = new List<Bnote>();
  }
}

=

public Class Foo3 : Cnote
{
   public bool Ison { get; set;}
   public List<Cnote>Anotes { get; private set;}
   public List<Cnote>Bnotes { get; private set; }

}

All you really need is another wrapper class for Automapper purposes.

public class Foo1And2 {
    public Foo1 Foo1 {get;set;}
    public Foo2 Foo2 {get;set;}
}

And then define the mapping:

CreateMap<Foo1And2, Foo3>().ConvertUsing(x => ConvertFoo1And2ToFoo3(x));

public Foo3 ConvertFoo1And2ToFoo3(Foo1And2 foo1And2)
{
    return new Foo3
    {
        Ison = foo1And2.Foo1.Ison && foo1And2.Foo2.Ison,
        Anotes = foo1And2.Foo1.Anotes,
        Bnotes = foo1And2.Foo2.Bnotes,
    };
}

And use it

var foo3 = Map<Foo3>(new Foo1And2
{
    Foo1 = foo1,
    Foo2 = foo2,
});


问:
Aggregate number of likes for each day within period
I am building a REST Api on Django RF which represents a very basic social network. I have a model Post that has a value Likes which is related to a User by many to many through a Like model. My models:

```<code>class Post(models.Model):
    content = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(CustomUser, on_delete=models.CASCADE,
                               related_name='posts')
    likes = models.ManyToManyField(CustomUser,
                                   related_name='likes',
                                   through='Like')

class Like(models.Model):
    author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    liked_on = models.DateTimeField(auto_now_add=True)
</code>```

I need to aggregate a likes statistics for each day within a given period. For example, a request looks like this analytics/?date_from=2020-05-15&date_to=2020-05-17

And I need give something like this:

```<code>[{
    'date': 2020-05-15,
    'likes': 5,
}, {
    'date': 2020-05-16,
    'likes': 7,
}, {
    'date': 2020-05-17,
    'likes': 10,
}]
</code>```

How can I do that in Django? Should I query a Post model that has likes as just a list? Or Likes model? And what query should be?

答:
You should use Django-Filter. Then in the filter class, add the following filters:

```<code>date_from = filters.DateTimeFilter(field_name='liked_on', lookup_expr='gte')
date_to = filters.DateTimeFilter(field_name='liked_on', lookup_expr='lte')
</code>```

Then you can make your request as you specified but used a datetime and not date. The filter class can be added to the LikesView.

UPDATE: Aggregation

To add aggregation, do this in the view after calling self.filter_queryset():

```<code>Like.objects.extra(select={'date': "date(<app_name>_like.liked_on)"}).annotate(likes=Count('pk')).order_by('-liked_on')
</code>```

Don't forget to replace <app_name> with the name of your app and import django.db.models.Count.

This was inspired by the answers to this question.

Now you can have a serializer with the fields date and likes:

```<code>class LikeByDaySerializer(serializers.ModelSerializer):
    date = serilaizers.DateTimeField()
    likes = serializers.IntegerField()

    class Meta:
        model = Like
        fields = ('date', 'likes')
</code>```

Body:
I am building a REST Api on Django RF which represents a very basic social network. I have a model Post that has a value Likes which is related to a User by many to many through a Like model. My models:

class Post(models.Model):
    content = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(CustomUser, on_delete=models.CASCADE,
                               related_name='posts')
    likes = models.ManyToManyField(CustomUser,
                                   related_name='likes',
                                   through='Like')

class Like(models.Model):
    author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    liked_on = models.DateTimeField(auto_now_add=True)

I need to aggregate a likes statistics for each day within a given period. For example, a request looks like this analytics/?date_from=2020-05-15&date_to=2020-05-17

And I need give something like this:

[{
    'date': 2020-05-15,
    'likes': 5,
}, {
    'date': 2020-05-16,
    'likes': 7,
}, {
    'date': 2020-05-17,
    'likes': 10,
}]

How can I do that in Django? Should I query a Post model that has likes as just a list? Or Likes model? And what query should be?

Body:
You should use Django-Filter. Then in the filter class, add the following filters:

date_from = filters.DateTimeFilter(field_name='liked_on', lookup_expr='gte')
date_to = filters.DateTimeFilter(field_name='liked_on', lookup_expr='lte')

Then you can make your request as you specified but used a datetime and not date. The filter class can be added to the LikesView.

UPDATE: Aggregation

To add aggregation, do this in the view after calling self.filter_queryset():

Like.objects.extra(select={'date': "date(<app_name>_like.liked_on)"}).annotate(likes=Count('pk')).order_by('-liked_on')

Don't forget to replace <app_name> with the name of your app and import django.db.models.Count.

This was inspired by the answers to this question.

Now you can have a serializer with the fields date and likes:

class LikeByDaySerializer(serializers.ModelSerializer):
    date = serilaizers.DateTimeField()
    likes = serializers.IntegerField()

    class Meta:
        model = Like
        fields = ('date', 'likes')


问:
How do i make Bar Chart of a subset of counts of categorical Column?
I have a Fifa 19 Dataset with data on more than 1000 players hailing from more than 100 countries. I want to make a bar chart showing the distribution of nationalities where number of players is greater than 3. Here is what I have tried:

```<code>nation = fifa_19[fifa_19['Nationality'].value_counts()>=3]
plt.figure(figsize=(30, 15))
sns.set(style="whitegrid")
sns.countplot(nation, order = fifa_19['Nationality'].value_counts().index)
plt.title('Distribution of Nationalities of players')
plt.xlabel('Nationality')
plt.ylabel('Frequency')
</code>```

and I get this error:

```<code>IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).
</code>```

I am making a sample DataFrame and adding it here.

```<code>fifa_19 = pd.DataFrame({'Player':['A','B','C','D','E','F','E','G','H'],'Nationality':['USA','USA','USA','Canada','Pakistan','India', 'Brazil','Brazil','Brazil']})
</code>```

If someone can help me, It will be great.

答:
The problem is that in your code the .value_counts() Series won't work as an index into the fifa_19 dataframe. Instead:

```<code>nation = fifa_19['Nationality'].value_counts()
nation = nation.loc[nation >= 3]

plt.figure(figsize=(30, 15))
sns.set(style="whitegrid")
sns.barplot(data=nation, x="Country", y="Frequency", order = fifa_19['Nationality'].value_counts().index)
plt.title('Distribution of Nationalities of players')
plt.xlabel('Nationality')
plt.ylabel('Frequency')
</code>```

Note: If you don't want the empty values for nationalities that don't meet the 3 player threshold, change this line:

```<code>sns.barplot(data=nation, x="Country", y="Frequency", order = fifa_19['Nationality'].value_counts().index)
</code>```

to

```<code>order = pd.DataFrame(fifa_19['Nationality'].value_counts().index).join(nation["Country"], how="inner")["Country"]
sns.barplot(data=nation, x="Country", y="Frequency", order = order)
</code>```

Body:
I have a Fifa 19 Dataset with data on more than 1000 players hailing from more than 100 countries. I want to make a bar chart showing the distribution of nationalities where number of players is greater than 3. Here is what I have tried:

nation = fifa_19[fifa_19['Nationality'].value_counts()>=3]
plt.figure(figsize=(30, 15))
sns.set(style="whitegrid")
sns.countplot(nation, order = fifa_19['Nationality'].value_counts().index)
plt.title('Distribution of Nationalities of players')
plt.xlabel('Nationality')
plt.ylabel('Frequency')

and I get this error:

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

I am making a sample DataFrame and adding it here.

fifa_19 = pd.DataFrame({'Player':['A','B','C','D','E','F','E','G','H'],'Nationality':['USA','USA','USA','Canada','Pakistan','India', 'Brazil','Brazil','Brazil']})

If someone can help me, It will be great.

Body:
The problem is that in your code the .value_counts() Series won't work as an index into the fifa_19 dataframe. Instead:

nation = fifa_19['Nationality'].value_counts()
nation = nation.loc[nation >= 3]

plt.figure(figsize=(30, 15))
sns.set(style="whitegrid")
sns.barplot(data=nation, x="Country", y="Frequency", order = fifa_19['Nationality'].value_counts().index)
plt.title('Distribution of Nationalities of players')
plt.xlabel('Nationality')
plt.ylabel('Frequency')

Note: If you don't want the empty values for nationalities that don't meet the 3 player threshold, change this line:

sns.barplot(data=nation, x="Country", y="Frequency", order = fifa_19['Nationality'].value_counts().index)

to

order = pd.DataFrame(fifa_19['Nationality'].value_counts().index).join(nation["Country"], how="inner")["Country"]
sns.barplot(data=nation, x="Country", y="Frequency", order = order)


问:
How to control the width and height prportion in matplotlib?
I am preparing a paper to submit to a journal. In the Author's guidelines, they said that the format of the images is (among other things) 3:2 (proportion width and height). I am doing graphics using matplotlib, and I want to get a .eps format images with this proportion (3:2) to put them in a latex file, but ensuring that feature. I just want to know if I am doing it right.

import numpy as np
import matplotlib.pyplot as plt
from random import randint, uniform,random
import random
import math

plt.rcParams['font.family'] = "Times New Roman" #Fount size.
plt.rcParams["figure.figsize"] = (30,20)        #width and height prportion

variables=[1563,6004,26406,52631,95580,183615,480500,1030582]
restricciones=[3538,15459,68886,155116,285660,603255,1709703,3694572]
instancias=['$I_{1}$','$I_{2}$','$I_{3}$','$I_{4}$','$I_{5}$','$I_{6}$','$I_{7}$','$I_{8}$']
plt.plot(instancias,variables,'#828282',marker='o',label="Number of decision variables")
plt.plot(instancias,restricciones,'#1E1E1E',marker='^',label="Number of constraints")
plt.grid()
plt.xlabel("Instances")
plt.ylabel("Units generated")
plt.legend(loc=0)
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
plt.savefig("test.eps",dpi=1200)
plt.show()
```

using plt.rcParams["figure.figsize"] = (30,20) , ensure that this proportion (30:20=3:2=1.5) it will be satisfied when I used the .eps file generated in the latex document? Thanks in advance

答:
changing aspect of figure:

```<code>fig = plt.figure(figsize=(1,2))
plt.scatter(range(5), range(5))
</code>```

```<code>fig = plt.figure(figsize=(2,2))
plt.scatter(range(5), range(5))
</code>```

```<code>fig = plt.figure(figsize=(2,1))
plt.scatter(range(5), range(5))
</code>```

changing aspect of subplots

set_aspect is your friend:

```<code>plt.scatter(range(5), range(5))
plt.gca().set_aspect(.1)
</code>```

```<code>plt.scatter(range(5), range(5))
plt.gca().set_aspect(1)
</code>```

```<code>plt.scatter(range(5), range(5))
plt.gca().set_aspect(10)
</code>```

Body:
I am preparing a paper to submit to a journal. In the Author's guidelines, they said that the format of the images is (among other things) 3:2 (proportion width and height). I am doing graphics using matplotlib, and I want to get a .eps format images with this proportion (3:2) to put them in a latex file, but ensuring that feature. I just want to know if I am doing it right.

import numpy as np
import matplotlib.pyplot as plt
from random import randint, uniform,random
import random
import math

plt.rcParams['font.family'] = "Times New Roman" #Fount size.
plt.rcParams["figure.figsize"] = (30,20)        #width and height prportion

variables=[1563,6004,26406,52631,95580,183615,480500,1030582]
restricciones=[3538,15459,68886,155116,285660,603255,1709703,3694572]
instancias=['$I_{1}$','$I_{2}$','$I_{3}$','$I_{4}$','$I_{5}$','$I_{6}$','$I_{7}$','$I_{8}$']
plt.plot(instancias,variables,'#828282',marker='o',label="Number of decision variables")
plt.plot(instancias,restricciones,'#1E1E1E',marker='^',label="Number of constraints")
plt.grid()
plt.xlabel("Instances")
plt.ylabel("Units generated")
plt.legend(loc=0)
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
plt.savefig("test.eps",dpi=1200)
plt.show()

using plt.rcParams["figure.figsize"] = (30,20) , ensure that this proportion (30:20=3:2=1.5) it will be satisfied when I used the .eps file generated in the latex document? Thanks in advance

Body:
changing aspect of figure:

fig = plt.figure(figsize=(1,2))
plt.scatter(range(5), range(5))

fig = plt.figure(figsize=(2,2))
plt.scatter(range(5), range(5))

fig = plt.figure(figsize=(2,1))
plt.scatter(range(5), range(5))

changing aspect of subplots

set_aspect is your friend:

plt.scatter(range(5), range(5))
plt.gca().set_aspect(.1)

plt.scatter(range(5), range(5))
plt.gca().set_aspect(1)

plt.scatter(range(5), range(5))
plt.gca().set_aspect(10)


问:
Javascript onscroll function not working
I am trying to add a class to a id when the user scrolls past 25 pixels. I am unsure why but the function is not firing after I school. Any help as to why would be greatly appreciated. Here is my code:

window.onscoll = function() {
  showArrow()
};

function showArrow() {
  if (document.body.scrollTop > 25 || document.documentElement.scrollTop > 25) {
    document.getElementById("hide_Arrow").className = "show";
  } else {
    document.getElementById("hide_Arrow").className = "";
  }
}
console.log(arrow);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#arrow {
  position: relative;
  height: 270px;
  display: block;
  margin: -20px auto;
  overflow: hidden;
}

#hide_Arrow {
  height: 0px;
  margin: -200px 00px 0px 0px;
  overflow: hidden;
}

#hide_Arrow.show {
  height: 250px;
}</code>```

```

答:
Hi i have also faced same issue and solved while writing code as per below in the JavaScript file...</p>

```<code>window.addEventListener('scroll', function() {
   showArrow()
});

function showArrow() {
  if (document.body.scrollTop > 25 || document.documentElement.scrollTop > 25) {
    document.getElementById("hide_Arrow").className = "show";
  } else {
    document.getElementById("hide_Arrow").className = "";
  }
}
console.log(arrow);

</code>```

Body:
I am trying to add a class to a id when the user scrolls past 25 pixels. I am unsure why but the function is not firing after I school. Any help as to why would be greatly appreciated. Here is my code:

window.onscoll = function() {
  showArrow()
};

function showArrow() {
  if (document.body.scrollTop > 25 || document.documentElement.scrollTop > 25) {
    document.getElementById("hide_Arrow").className = "show";
  } else {
    document.getElementById("hide_Arrow").className = "";
  }
}
console.log(arrow);

#arrow {
  position: relative;
  height: 270px;
  display: block;
  margin: -20px auto;
  overflow: hidden;
}

#hide_Arrow {
  height: 0px;
  margin: -200px 00px 0px 0px;
  overflow: hidden;
}

#hide_Arrow.show {
  height: 250px;
}

Body:
Hi i have also faced same issue and solved while writing code as per below in the JavaScript file...

window.addEventListener('scroll', function() {
   showArrow()
});

function showArrow() {
  if (document.body.scrollTop > 25 || document.documentElement.scrollTop > 25) {
    document.getElementById("hide_Arrow").className = "show";
  } else {
    document.getElementById("hide_Arrow").className = "";
  }
}
console.log(arrow);