问:
how to convert xml response to class object in c#?
Hi i am going for the xml response to convert as a class object in c#.i have get the xml from the sql side and call the one utility and get the xml and go for the convert in class object but with my code not return null in the class. any one know where is my problem then please let me know.

Here is my xml data :

```<code><Users>
      <User>
            <UserId>1</UserId>
            <Email>abc@gmail.com</Email>
            <UserName>abc</UserName>
            <ProfileImage>20160816105401206.jpeg</ProfileImage>
            <Name>abc</Name>

            <InterestId>8</InterestId>
            <FeedId>4608</FeedId>
            <Description>Test</Description>
            <Interest>Cricekt</Interest>

            <InterestId>12</InterestId>
            <FeedId>4609</FeedId>
            <Description>Test 2</Description>
            <Interest>Read</Interest>
      </User>
       <User>
            <UserId>2</UserId>
            <Email>xyz@gmail.com</Email>
            <UserName>xyz</UserName>
            <ProfileImage>20160816105401207.jpeg</ProfileImage>
            <Name>xyz</Name>

            <InterestId>8</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>swim</Interest>

            <InterestId>12</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>drive</Interest>
      </User>
 </Users>
</code>```

this is my class in c#:

```<code>        [XmlRoot]
    public class Users
    {
        [XmlRoot]
        public class User
        {
            [XmlElement]
            public int UserId { get; set; }

            [XmlElement]
            public string Email { get; set; }

            [XmlElement]
            public string UserName { get; set; }

            [XmlElement]
            public string ProfileImage { get; set; }

            [XmlElement]
            public string Name { get; set; }

            [XmlElement]
            public int FeedId { get; set; }

            [XmlElement]
            public string Description { get; set; }

            [XmlElement]
            public string Interest { get; set; }

            [XmlElement]
            public int InterestId { get; set; }

        }

        [XmlArray("UserList")]
        [XmlArrayItem("User")]
        public User[] ListUsers { get; set; }
    }
</code>```

this is my method in c#:

```<code>    public string xmldata()
    {
        Users obju = new Users();

            string xml = "";
            DataSet ds = DataAccess.ExecuteDataset(Settings.ConnectionString(), "Getxml",1,10);
            if (ds != null && ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    xml += ds.Tables[0].Rows[i]["XML_F52E2B61-18A1-11d1-B105-00805F49916B"].ToString();
                }
            }

            var serializer = new XmlSerializer(typeof(Users));
            Users result;

            using (TextReader reader = new StringReader(xml))
            {
                result = (Users)serializer.Deserialize(reader);// here i am not getting xml to in class
            }
        return null;
    }
</code>```

答:
There seem to be 2 completely different xml structures in play here; one neatly itemized in the question, and one that is not itemized - in the comments. By non-itemized, I mean that individual elements bleed into each-other without a wrapper per object, like so:

```<code><InterestId>8</InterestId>
<FeedId>4608</FeedId>
<Description>Test</Description>
<Interest>Cricekt</Interest>
<InterestId>12</InterestId>
<FeedId>4609</FeedId>
<Description>Test 2</Description>
<Interest>Read</Interest>
</code>```

The first is a good fit for XmlSerializer, which excels are pulling apart itemized xml, but really can't help much for non-itemized. To read such a model tends to be more manual. I would probably:

identify the first element per batch

read until the next of those elements

resolve the other child elements from between the two

Something like:

```<code>using System;
using System.Linq;
using System.Xml.Linq;
static class Program
{
    static void Main()
    {
        var el = XDocument.Parse(xml).Root;

        var interests = from intIdEl in el.Elements("InterestId")
                        let children = intIdEl.ElementsAfterSelf().TakeWhile(
                            x => x.Name != "InterestId")
                        let feedIdEl = children.FirstOrDefault(x => x.Name == "FeedId")
                        let descIdEl = children.FirstOrDefault(x => x.Name == "Description")
                        let intEl = children.FirstOrDefault(x => x.Name == "Interest")
                        select new
                        {
                            InterestId = (int?)intIdEl,
                            FeedId = (int?)feedIdEl,
                            Description = (string)descIdEl,
                            Interest = (string)intEl
                        };

        foreach(var obj in interests)
        {
            Console.WriteLine(
              $"{obj.InterestId}, {obj.FeedId}, {obj.Description}, {obj.Interest}");
        }
    }
    const string xml = @"<Users>
<InterestId>8</InterestId><FeedId>4608</FeedId>
<Description>Test</Description> <Interest>Cricekt</Interest>
<InterestId>12</InterestId> <FeedId>4609</FeedId>
<Description>Test 2</Description> <Interest>Read</Interest>
</Users>";
}
</code>```

Body:
Hi i am going for the xml response to convert as a class object in c#.i have get the xml from the sql side and call the one utility and get the xml and go for the convert in class object but with my code not return null in the class. any one know where is my problem then please let me know.

Here is my xml data :

<Users>
      <User>
            <UserId>1</UserId>
            <Email>abc@gmail.com</Email>
            <UserName>abc</UserName>
            <ProfileImage>20160816105401206.jpeg</ProfileImage>
            <Name>abc</Name>

            <InterestId>8</InterestId>
            <FeedId>4608</FeedId>
            <Description>Test</Description>
            <Interest>Cricekt</Interest>

            <InterestId>12</InterestId>
            <FeedId>4609</FeedId>
            <Description>Test 2</Description>
            <Interest>Read</Interest>
      </User>
       <User>
            <UserId>2</UserId>
            <Email>xyz@gmail.com</Email>
            <UserName>xyz</UserName>
            <ProfileImage>20160816105401207.jpeg</ProfileImage>
            <Name>xyz</Name>

            <InterestId>8</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>swim</Interest>

            <InterestId>12</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>drive</Interest>
      </User>
 </Users>

this is my class in c#:

        [XmlRoot]
    public class Users
    {
        [XmlRoot]
        public class User
        {
            [XmlElement]
            public int UserId { get; set; }

            [XmlElement]
            public string Email { get; set; }

            [XmlElement]
            public string UserName { get; set; }

            [XmlElement]
            public string ProfileImage { get; set; }

            [XmlElement]
            public string Name { get; set; }

            [XmlElement]
            public int FeedId { get; set; }

            [XmlElement]
            public string Description { get; set; }

            [XmlElement]
            public string Interest { get; set; }

            [XmlElement]
            public int InterestId { get; set; }

        }

        [XmlArray("UserList")]
        [XmlArrayItem("User")]
        public User[] ListUsers { get; set; }
    }

this is my method in c#:

    public string xmldata()
    {
        Users obju = new Users();

            string xml = "";
            DataSet ds = DataAccess.ExecuteDataset(Settings.ConnectionString(), "Getxml",1,10);
            if (ds != null && ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    xml += ds.Tables[0].Rows[i]["XML_F52E2B61-18A1-11d1-B105-00805F49916B"].ToString();
                }
            }

            var serializer = new XmlSerializer(typeof(Users));
            Users result;

            using (TextReader reader = new StringReader(xml))
            {
                result = (Users)serializer.Deserialize(reader);// here i am not getting xml to in class
            }
        return null;
    }

Body:
There seem to be 2 completely different xml structures in play here; one neatly itemized in the question, and one that is not itemized - in the comments. By non-itemized, I mean that individual elements bleed into each-other without a wrapper per object, like so:

<InterestId>8</InterestId>
<FeedId>4608</FeedId>
<Description>Test</Description>
<Interest>Cricekt</Interest>
<InterestId>12</InterestId>
<FeedId>4609</FeedId>
<Description>Test 2</Description>
<Interest>Read</Interest>

The first is a good fit for XmlSerializer, which excels are pulling apart itemized xml, but really can't help much for non-itemized. To read such a model tends to be more manual. I would probably:

identify the first element per batch

read until the next of those elements

resolve the other child elements from between the two

Something like:

using System;
using System.Linq;
using System.Xml.Linq;
static class Program
{
    static void Main()
    {
        var el = XDocument.Parse(xml).Root;

        var interests = from intIdEl in el.Elements("InterestId")
                        let children = intIdEl.ElementsAfterSelf().TakeWhile(
                            x => x.Name != "InterestId")
                        let feedIdEl = children.FirstOrDefault(x => x.Name == "FeedId")
                        let descIdEl = children.FirstOrDefault(x => x.Name == "Description")
                        let intEl = children.FirstOrDefault(x => x.Name == "Interest")
                        select new
                        {
                            InterestId = (int?)intIdEl,
                            FeedId = (int?)feedIdEl,
                            Description = (string)descIdEl,
                            Interest = (string)intEl
                        };

        foreach(var obj in interests)
        {
            Console.WriteLine(
              $"{obj.InterestId}, {obj.FeedId}, {obj.Description}, {obj.Interest}");
        }
    }
    const string xml = @"<Users>
<InterestId>8</InterestId><FeedId>4608</FeedId>
<Description>Test</Description> <Interest>Cricekt</Interest>
<InterestId>12</InterestId> <FeedId>4609</FeedId>
<Description>Test 2</Description> <Interest>Read</Interest>
</Users>";
}


来源: stackexchange

问:
WPF Page to Window Navigation
I have a MainWindow with button 1, when i press this button it navigate to  Page1 placed inside a Window1. When i press button 2 inside Page1, i need to close Window1 and display MainWindow. Kindly help me to find a solution.

When i trying to access MainWindow object using :

```<code>Window1 w = Application.Current.MainWindow as Window1;
</code>```

w is giving null.

答:
Try this:</p>

```<code>//display a new MainWindow
MainWindow mainWindow = new MainWindow();
mainWindow.Show();

//close Window1
Window1 w = Application.Current.Windows.OfType<Window1>().FirstOrDefault();
w.Close();
</code>```

ContentLicense: CC BY-SA 3.0

Title: WPF Page to Window Navigation

Body:
I have a MainWindow with button 1, when i press this button it navigate to  Page1 placed inside a Window1. When i press button 2 inside Page1, i need to close Window1 and display MainWindow. Kindly help me to find a solution.

When i trying to access MainWindow object using :

Window1 w = Application.Current.MainWindow as Window1;

w is giving null.

Body:
Try this:

//display a new MainWindow
MainWindow mainWindow = new MainWindow();
mainWindow.Show();

//close Window1
Window1 w = Application.Current.Windows.OfType<Window1>().FirstOrDefault();
w.Close();


问:
CSS Star outline
Is there any way to make a css star shape outline?

I know you can make a filled in one, with the following css

```<code>    .star-five {
       margin: 50px 0;
       position: relative;
       display: block;
       color: red;
       width: 0px;
       height: 0px;
       border-right:  100px solid transparent;
       border-bottom: 70px  solid red;
       border-left:   100px solid transparent;
       -moz-transform:    rotate(35deg);
       -webkit-transform: rotate(35deg);
       -ms-transform:     rotate(35deg);
       -o-transform:      rotate(35deg);
    }
.star-five:before{
...
}
.star-five:after {
...
}
</code>```

Working example here: jsfiddle

But what about a transparent fill with a red outline?

答:
Here is a pure CSS solution using the same Fiddle you provided. I just scaled a star in and made it white.

body {
  margin: 0px;
}

.star-five {
  margin: 50px 0;
  position: relative;
  display: block;
  color: red;
  width: 0px;
  height: 0px;
  border-right: 100px solid transparent;
  border-bottom: 70px solid red;
  border-left: 100px solid transparent;
  -moz-transform: rotate(35deg);
  -webkit-transform: rotate(35deg);
  -ms-transform: rotate(35deg);
  -o-transform: rotate(35deg);
}

.star-five:before {
  border-bottom: 80px solid red;
  border-left: 30px solid transparent;
  border-right: 30px solid transparent;
  position: absolute;
  height: 10px;
  width: 0;
  top: -45px;
  left: -65px;
  display: block;
  content: '';
  -webkit-transform: rotate(-35deg);
  -moz-transform: rotate(-35deg);
  -ms-transform: rotate(-35deg);
  -o-transform: rotate(-35deg);
}

.star-five:after {
  position: absolute;
  display: block;
  color: red;
  top: 3px;
  left: -105px;
  width: 0px;
  height: 0px;
  border-right: 100px solid transparent;
  border-bottom: 70px solid red;
  border-left: 100px solid transparent;
  -webkit-transform: rotate(-70deg);
  -moz-transform: rotate(-70deg);
  -ms-transform: rotate(-70deg);
  -o-transform: rotate(-70deg);
  content: '';
}

.star-outline>.star-five,
.star-outline>.star-five:before,
.star-outline>.star-five:after {
  border-bottom-color: white;
}

.star-outline {
  position: absolute;
  top: 0px;
  left: 0px;
  transform: scale(0.9);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="star">
  <span class="star-five" width="10" height="10">
</span>

  <div class="star-outline">
    <span class="star-five">
</span>
  </div>
</div></code>```

Title: CSS Star outline

Body:
Is there any way to make a css star shape outline?

I know you can make a filled in one, with the following css

    .star-five {
       margin: 50px 0;
       position: relative;
       display: block;
       color: red;
       width: 0px;
       height: 0px;
       border-right:  100px solid transparent;
       border-bottom: 70px  solid red;
       border-left:   100px solid transparent;
       -moz-transform:    rotate(35deg);
       -webkit-transform: rotate(35deg);
       -ms-transform:     rotate(35deg);
       -o-transform:      rotate(35deg);
    }
.star-five:before{
...
}
.star-five:after {
...
}

Working example here: jsfiddle

But what about a transparent fill with a red outline?

Body:
Here is a pure CSS solution using the same Fiddle you provided. I just scaled a star in and made it white.

body {
  margin: 0px;
}

.star-five {
  margin: 50px 0;
  position: relative;
  display: block;
  color: red;
  width: 0px;
  height: 0px;
  border-right: 100px solid transparent;
  border-bottom: 70px solid red;
  border-left: 100px solid transparent;
  -moz-transform: rotate(35deg);
  -webkit-transform: rotate(35deg);
  -ms-transform: rotate(35deg);
  -o-transform: rotate(35deg);
}

.star-five:before {
  border-bottom: 80px solid red;
  border-left: 30px solid transparent;
  border-right: 30px solid transparent;
  position: absolute;
  height: 10px;
  width: 0;
  top: -45px;
  left: -65px;
  display: block;
  content: '';
  -webkit-transform: rotate(-35deg);
  -moz-transform: rotate(-35deg);
  -ms-transform: rotate(-35deg);
  -o-transform: rotate(-35deg);
}

.star-five:after {
  position: absolute;
  display: block;
  color: red;
  top: 3px;
  left: -105px;
  width: 0px;
  height: 0px;
  border-right: 100px solid transparent;
  border-bottom: 70px solid red;
  border-left: 100px solid transparent;
  -webkit-transform: rotate(-70deg);
  -moz-transform: rotate(-70deg);
  -ms-transform: rotate(-70deg);
  -o-transform: rotate(-70deg);
  content: '';
}

.star-outline>.star-five,
.star-outline>.star-five:before,
.star-outline>.star-five:after {
  border-bottom-color: white;
}

.star-outline {
  position: absolute;
  top: 0px;
  left: 0px;
  transform: scale(0.9);
}

<div class="star">
  <span class="star-five" width="10" height="10">
</span>

  <div class="star-outline">
    <span class="star-five">
</span>
  </div>
</div>


问:
PHP output showing little black diamonds with a question mark
I'm writing a php program that pulls from a database source. Some of the varchars have quotes that are displaying as black diamonds with a question mark in them (�, REPLACEMENT CHARACTER, I assume from Microsoft Word text).

How can I use php to strip these characters out?

答:
When you extract data from anywhere you should use functions with the prefix md_FUNC_NAME.

Had the same problem it helped me out.

Or you can find the code of this symbol and use regexp to delete these symbols.

OwnerDisplayName: Steve Zajaczkowski

LastEditorDisplayName: hop


问:
How to test whether Siren(https://github.com/ArtSabintsev/Siren) moves properly on my app
i have an app on App Store but it still doesn't have a new version.

I added this library called "Siren" so that i could push a notification to the user that the user could update their app's version.

Because there are no any new version, i can't test whether succeeded in adding "Siren" to my app.

I think this problem may occur in other libraries like iVersion or Harpy too.

Does anyone has a good idea to test this push notification?

答:
The project readme now has some guidance on how to Test Siren

Temporarily change the version string in Xcode (within the .xcodeproj)
      to an older version than the one that's currently available in the App
      Store. Afterwards, build and run your app, and you should see the alert.

  If you currently don't have an app in the store, change your bundleID
      to one that is already in the store. In the sample app packaged with
      this library, we use the iTunes Connect Mobile app's bundleID:
      com.apple.itunesconnect.mobile.

  For your convenience, you may turn on debugging statements by setting
      self.debugEnabled = true before calling the checkVersion() method.


问:
How to design a method that contains lots of IF's or Switch statements
How can i make the design of this class more dynamic so i can add new extensions and types as required.

```<code>public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}
</code>```

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

```<code>else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}
</code>```

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers

答:
for this particular case I'd build something like

```<code>List<string> excelExtensions = new List<string>(){ "xls", "xlsx" };
List<string> wordExtensions = new List<string>(){ "doc", "docx" };

if(excelExtensions.Contains(extension))
{
}

if(wordExtensions.Contains(extension))
{
}
</code>```

etc?

ContentLicense: CC BY-SA 2.5

Body:
How can i make the design of this class more dynamic so i can add new extensions and types as required.

public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers

Body:
for this particular case I'd build something like

List<string> excelExtensions = new List<string>(){ "xls", "xlsx" };
List<string> wordExtensions = new List<string>(){ "doc", "docx" };

if(excelExtensions.Contains(extension))
{
}

if(wordExtensions.Contains(extension))
{
}

etc?


问:
How to resolve a generated string in an R loop
I am trying to populate a column in an R dataframe with a value from regression results. There are 27 unique ID's in the dataframe, each with 64 row entries.
I am looping through my 27 regression results and would like to populate each of the 64 rows (per ID) with a value from a generated string. I can do all of the above fine with:

```<code>for (i in 1:27) {
  coef1<-paste("Gamble_results.",i,sep="")
  coef1<-paste(coef1,"$coefficients[2]",sep="")
  print (coef1)
  Gamble_results$Lambda[Gamble_results$X1==i] <- coef1

   }
</code>```

But the code will not resolve my coef1..I get
Error in get(coef1) : object 'Gamble_results.2$coefficients[2]' not found
When of course, this coefficient can be printed directly.
Any help would be greatly appreciated
thanks

答:
You can use eval(parse()) to evaluate the object given by a string. In your case it would be:

```<code>Gamble_results$Lambda[Gamble_results$X1==i] <- eval(parse(text = coef1))
</code>```

Disclaimer: I know about fortunes::fortune(106), I still think eval(parse()) has its use :)

Body:
I am trying to populate a column in an R dataframe with a value from regression results. There are 27 unique ID's in the dataframe, each with 64 row entries.
I am looping through my 27 regression results and would like to populate each of the 64 rows (per ID) with a value from a generated string. I can do all of the above fine with:

for (i in 1:27) {
  coef1<-paste("Gamble_results.",i,sep="")
  coef1<-paste(coef1,"$coefficients[2]",sep="")
  print (coef1)
  Gamble_results$Lambda[Gamble_results$X1==i] <- coef1

   }

But the code will not resolve my coef1..I get
Error in get(coef1) : object 'Gamble_results.2$coefficients[2]' not found
When of course, this coefficient can be printed directly.
Any help would be greatly appreciated
thanks

Body:
You can use eval(parse()) to evaluate the object given by a string. In your case it would be:

Gamble_results$Lambda[Gamble_results$X1==i] <- eval(parse(text = coef1))

Disclaimer: I know about fortunes::fortune(106), I still think eval(parse()) has its use :)


问:
C# Entity Framework - Multiple Foreign Keys
I have a problem with Entity Framework 6 code first creating multiple foreign keys from my classes when it should only create one. Consider I have 2 classes -

```<code>public class Work
{
    public Work()
    {
        Document1 = new Collection<Document>();
        Document2 = new Collection<Document>();
        Document3 = new Collection<Document>();
    }
    [Key]
    public int WorkId { get; set; }
    public virtual ICollection<Document> Document1 { get; set; }
    public virtual ICollection<Document> Document2 { get; set; }
    public virtual ICollection<Document> Document3 { get; set; }
}

public class Document
{
    public int? WorkId { get; set; }
    [ForeignKey("WorkId")]
    public Work Work { get; set; }
}
</code>```

Now when I run the code first update-database command, in my documents table it creates 3 different foreign keys for the Work table WorkId, Work_Id1, Work_Id2, this should just be one foreign key instead of 3. I know there should be a simple annotation to fix this or a fluent mapping I need to add?

答:
Apparently a Work may have zero or more Document1, zero or more Document2 and zero or more Document3. All these documents are of type Document.

Each Document belongs to exactly one Work, in which it is either a Document1, a Document2 or a Document3. The problem is when using your classes it does not know which Document type it is.

The most database friendly and flexible solution is to give each document a property, telling which type of Document it is, and put all Documents into one table:

```<code>public enum DocumentType
{
    Document1,
    Document2,
    Document3,
};

public class Work
{
    public int WorkId { get; set; }
    public virtual ICollection<Document> Document { get; set; }
}

public class Document
{
    public int DocumentId {get; set;} // primary key
    public DocumentType DocumentType {get; set;}

    public int WorkId { get; set; }
    public Work Work { get; set; }
}
public MyDbContext : DbContext
{
    public DbSet<Work> Works {get; set;}
    public DbSet<Document> Documents {get; set;}
}
</code>```

The result is one Table with Documents. column WorkId will tell you to which Work the document belongs. Column DocumentType will tell you whether it is a Document1, a Document2 or a Document3.

This way it will be easy to add new DocumentTypes without having to change the database. If you want fast searches for all documents of a certain type consider creating an extra index with keys (Id, DocumentType)

If you really want three different tables, for instance because it could be that in future a Document1 is not similar to a Document2 anymore, you'll have to create three classes derived from Document, and three DbSet for these classes

```<code>public class Document1 : Document
{
   public int WorkId {get; set;}
   public virtual Work Work {get; set;}
}
public MyDbContext : DbContext
{
    public DbSet<Work> Works {get; set;}
    public DbSet<Document1> Document1s {get; set;}
    public DbSet<Document2> Document2s {get; set;}
    public DbSet<Document3> Document3s {get; set;}
}
</code>```

Consider using Table-per-concrete-class for this. This way you'll get a table with Document1, a table with Document2 and one for Document3

Body:
I have a problem with Entity Framework 6 code first creating multiple foreign keys from my classes when it should only create one. Consider I have 2 classes -

public class Work
{
    public Work()
    {
        Document1 = new Collection<Document>();
        Document2 = new Collection<Document>();
        Document3 = new Collection<Document>();
    }
    [Key]
    public int WorkId { get; set; }
    public virtual ICollection<Document> Document1 { get; set; }
    public virtual ICollection<Document> Document2 { get; set; }
    public virtual ICollection<Document> Document3 { get; set; }
}

public class Document
{
    public int? WorkId { get; set; }
    [ForeignKey("WorkId")]
    public Work Work { get; set; }
}

Now when I run the code first update-database command, in my documents table it creates 3 different foreign keys for the Work table WorkId, Work_Id1, Work_Id2, this should just be one foreign key instead of 3. I know there should be a simple annotation to fix this or a fluent mapping I need to add?

Body:
Apparently a Work may have zero or more Document1, zero or more Document2 and zero or more Document3. All these documents are of type Document.

Each Document belongs to exactly one Work, in which it is either a Document1, a Document2 or a Document3. The problem is when using your classes it does not know which Document type it is.

The most database friendly and flexible solution is to give each document a property, telling which type of Document it is, and put all Documents into one table:

public enum DocumentType
{
    Document1,
    Document2,
    Document3,
};

public class Work
{
    public int WorkId { get; set; }
    public virtual ICollection<Document> Document { get; set; }
}

public class Document
{
    public int DocumentId {get; set;} // primary key
    public DocumentType DocumentType {get; set;}

    public int WorkId { get; set; }
    public Work Work { get; set; }
}
public MyDbContext : DbContext
{
    public DbSet<Work> Works {get; set;}
    public DbSet<Document> Documents {get; set;}
}

The result is one Table with Documents. column WorkId will tell you to which Work the document belongs. Column DocumentType will tell you whether it is a Document1, a Document2 or a Document3.

This way it will be easy to add new DocumentTypes without having to change the database. If you want fast searches for all documents of a certain type consider creating an extra index with keys (Id, DocumentType)

If you really want three different tables, for instance because it could be that in future a Document1 is not similar to a Document2 anymore, you'll have to create three classes derived from Document, and three DbSet for these classes

public class Document1 : Document
{
   public int WorkId {get; set;}
   public virtual Work Work {get; set;}
}
public MyDbContext : DbContext
{
    public DbSet<Work> Works {get; set;}
    public DbSet<Document1> Document1s {get; set;}
    public DbSet<Document2> Document2s {get; set;}
    public DbSet<Document3> Document3s {get; set;}
}

Consider using Table-per-concrete-class for this. This way you'll get a table with Document1, a table with Document2 and one for Document3


问:
Mock an object which is part of mocked object
when I run the test case I get AnObj mocked. this is used from inside the target classes method. when that method gets invoked the 'anOtherObj' is accessed and that is found to be null. Can some one please point out how to make sure 'anOtherObj' is not null so that I dont get nullpointer there?</p>

```<code>    @Test
    public class TestTargetTest {

    @Mock
    private AnObj anObj;

    @InjectMocks
    private TestTarget testTarget;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testTarget() {

        when(anObj.someMethod()).thenCallRealMethod();

        testTarget.testTarget();

    }

}

@Component
public class TestTarget {

    @Autowired
    private AnObj anObj;

    public void testTarget(){

        anObj.someMethod();
    }
}

@Component
public class AnObj {

    @Autowired
    private AnOtherObj anOtherObj;

    public void someMethod(){
        syso(anOtherObj.toString());
    }
}
</code>```

答:
You need to initialize annotated mocks in your test class.</p>

```<code>@BeforeMethod
public void beforeClass() {
    MockitoAnnotations.initMocks(this);
}
</code>```

Body:
when I run the test case I get AnObj mocked. this is used from inside the target classes method. when that method gets invoked the 'anOtherObj' is accessed and that is found to be null. Can some one please point out how to make sure 'anOtherObj' is not null so that I dont get nullpointer there?

    @Test
    public class TestTargetTest {

    @Mock
    private AnObj anObj;

    @InjectMocks
    private TestTarget testTarget;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testTarget() {

        when(anObj.someMethod()).thenCallRealMethod();

        testTarget.testTarget();

    }

}

@Component
public class TestTarget {

    @Autowired
    private AnObj anObj;

    public void testTarget(){

        anObj.someMethod();
    }
}

@Component
public class AnObj {

    @Autowired
    private AnOtherObj anOtherObj;

    public void someMethod(){
        syso(anOtherObj.toString());
    }
}

Body:
You need to initialize annotated mocks in your test class.

@BeforeMethod
public void beforeClass() {
    MockitoAnnotations.initMocks(this);
}


问:
Openvswitch (ovsdb) database migration
We have an Openstack infrastructure consisting of one controller node, eight compute nodes and a network node. This last node is having hardware problems (disk write failures). Unfortunately it has only one disk without replication. And there's no option now to modify it for HA support.

We already tried to "dd" that disk to another but it didn't bring up. So, we agreed that the better choice was to build a new network node (using the same hardware specs)

Failing network node is running the following:

CentOS 7.1.1503

Openstack-neutron-openvswitch-2014.2.2-1 (Juno release)

Openvswitch-2.1.2-2

New network node:

CentOS 7.3.1611

Openstack-neutron-openvswitch-2014.2.3-1 (Juno release)

Openvswitch-2.3.1-2

We managed to export the database, just copying the conf.db file located in /etc/openvswitch into the new node. We had to convert the db to a newer schema since the nodes have different ovs versions. But we can't make it work like the old one, since it adds new interfaces to the database record and doesn't use the ones imported from the old hardware, even having the same exact names.

Is there a way to replicate the ovs configuration in the new node and make it work? That considering that both hardware are the same. Any of you had any experience trying to move/import/export an ovs database? I can attach the database dump if necessary.

答:
I think you must config manually from the beginning, because that database is hashed and encrypted,
when you install openstack throught different machine, the openstack generate keystone randomly,
if you use packstack it the keystone stone can be same with you generate the answer-file

```<code>packstack --gen-answer-file=openstack.conf
</code>```

and adit the option you want in openstack.conf

Title: Openvswitch (ovsdb) database migration

Body:
I think you must config manually from the beginning, because that database is hashed and encrypted,
when you install openstack throught different machine, the openstack generate keystone randomly,
if you use packstack it the keystone stone can be same with you generate the answer-file

packstack --gen-answer-file=openstack.conf

and adit the option you want in openstack.conf


问:
How to Create REST Application using Google App Engine?
I am trying to develop REST application using Google App Engine.
I've tried so many things but nothing is working for me so please if you have any sample code please share it with me.</p>

答:
1) you have to configure your eclipse for google app engine.
   so you can learn it form here : https://www.youtube.com/watch?v=tVIIgcIqoPw&t=1426s

2) Configuring the REST support in the application

To be able to create and run REST services in your application you need to:

Add the JAX-RS, JAXB,  jersey-core, jersey-server, jersey-servlet Jars in your project and application.

Configure the web application (web.xml) to handle REST requests.

Add JAX-RS, JAXB to your project

Right click on the project and select menu entry Build Path > Configure Build Path...

Click on the Add External JARs button

Select all the JARs located in $JERSEY_HOME/lib  and $JAXB_HOME/lib folders. You can for better visibility and reuse create a user library with all these JARs.

You also need to copy the JARs in the web-inf/lib directory of your application, this step is mandatory to be sure that the JARs are included in the application when deployed to App Engine.
Note: I do not like this step. I would prefer to do that by configuration of the build path, to automatically add the JARs to the WEB-INF/lib directory when executing/deploying the application. Unfortunately I did not find the way to do it, so if you know it, feel free to post a comment and I will update the article.

Configure the web application

1) WEB.xml

```<code><servlet>

    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.demo.employee.service.rest.impl</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/resources/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</code>```

Creating a simple REST Service to test the environment

2). EmployeeResource.java

```<code>package com.demo.employee.service.rest.impl;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;

@Path("/hr/")
public class EmployeeResource {
 @GET
 @Produces("text/plain")
 @Path("/employee")
 public String getEmployee() {
    return "Hello World!";
 }
}
</code>```

You should be able to test it, stop the server and run it again, enter the following URL in your browser:
http://localhost:8888/resources/hr/employee
or
http://localhost:8888/rest/hr/employee

if Run successfully it means your configuration is working fine and you are good to go to develop further.

Now We will create one demo application which returns employee email,First Name,and Last Name using REST.

To do that you have to perform some changes in EmployeeResouce.java
and you need to add some classes which are as follows:

1)  Employee Model class : Employee.java

```<code>package com.demo.employee.service.model;

import java.util.Date;

public class Employee {

private String firstName;
private String lastName;
private Date hireDate;

public Employee() {}

public Employee(String firstName, String lastName, Date hireDate, String email) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
    this.hireDate = hireDate;
    this.email = email;
}

<generated setter and getter >

public String toString() {
    StringBuffer sb = new StringBuffer();
    sb.append("First: ").append(getFirstName());
    sb.append(" - Last: ").append(getLastName());
    sb.append(" - Date: ").append(getHireDate());
    sb.append(" - Email: ").append(getEmail());
    return sb.toString();
}
}
</code>```

Converter class for your entity

I usually encapsulate all the transformation in some converter class, like that I do not directly couple my business class to the serialisation mechanism. (So I do that for classes and lists of classes). So instead of adding the JAXB annotations to the Employee class itself, let's create an EmployeeConverter class that will be responsible of the transformation and used by your REST service.

2)  EmployeeConverter.java

```<code>package com.demo.employee.service.converter;

import java.util.Date;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.grallandco.employee.service.model.Employee;

@XmlRootElement(name = "employee")
public class EmployeeConverter {
private Employee entity = null;

public EmployeeConverter() {
     entity = new Employee();
     }

     public EmployeeConverter(Employee entity) {
     this.entity = entity;
     }

     @XmlElement
     public String getFirstName() {
     return entity.getFirstName();
     }

     @XmlElement
     public String getLastName() {
     return entity.getLastName();
     }

     @XmlElement
     public Date getHireDate() {
     return entity.getHireDate();
     }

     @XmlElement
     public String getEmail() {
     return entity.getEmail();
     }

     public Employee getEmployee() {
     return entity;
     }

     public void setFirstName(String firstName) {
     entity.setFirstName(firstName);
     }

     public void setHireDate(Date hireDate) {
     entity.setHireDate(hireDate);
     }

     public void setLastName(String email) {
     entity.setEmail(email);
     }

     public void setEmail(String lastName) {
     entity.setLastName(lastName);
     }

   }
</code>```

Add support to JSON and XML to your REST service

You need to change the EmployeeRessource class, to change the signature and add new annotations of the getEmployee() method.
The annotation you are adding:

@Produces({"application/xml", "application/json"}) : indicates which type of content will be produced by the service. Based on the type of the request.

@Path("/employee/{employeeEmail}/") :    change the Path to indicate a Path parameter, here for example the URL can accept an email in the URI - not the best example, but you get the point...

public EmployeeConverter getEmployee( @PathParam ("employeeEmail") String email)  : change the type returned by the method and take a parameter as String that match the Path param defined in the @Path annotation.

3). EmployeeResource.java

```<code>package com.demo.employee.service.rest.impl;

      import javax.ws.rs.GET;
      import javax.ws.rs.Path;
      import javax.ws.rs.PathParam;
      import javax.ws.rs.Produces;
      import com.demo.employee.service.converter.EmployeeConverter;
      import com.demo.employee.service.model.Employee;

      @Path("/hr/")
      public class EmployeeResource {
           @GET
           @Produces({"application/xml", "application/json"})
           @Path("/employee/{employeeEmail}/")
           public EmployeeConverter getEmployee( @PathParam ("employeeEmail")
           String email) {
               //dummy code
               Employee emp = new Employee();
               emp.setEmail(email);
               emp.setFirstName("Dhruv");
               emp.setLastName("Gurjar");
               EmployeeConverter converter = new EmployeeConverter(emp);
               return converter;
           }

      }
</code>```

Test the service
You can now run the server locally and test the service

http://localhost:8888/rest/hr/employee/test@test.com

This will return an XML document.

Body:
1) you have to configure your eclipse for google app engine.
   so you can learn it form here : https://www.youtube.com/watch?v=tVIIgcIqoPw&t=1426s

2) Configuring the REST support in the application

To be able to create and run REST services in your application you need to:

Add the JAX-RS, JAXB,  jersey-core, jersey-server, jersey-servlet Jars in your project and application.

Configure the web application (web.xml) to handle REST requests.

Add JAX-RS, JAXB to your project

Right click on the project and select menu entry Build Path > Configure Build Path...

Click on the Add External JARs button

Select all the JARs located in $JERSEY_HOME/lib  and $JAXB_HOME/lib folders. You can for better visibility and reuse create a user library with all these JARs.

You also need to copy the JARs in the web-inf/lib directory of your application, this step is mandatory to be sure that the JARs are included in the application when deployed to App Engine.
Note: I do not like this step. I would prefer to do that by configuration of the build path, to automatically add the JARs to the WEB-INF/lib directory when executing/deploying the application. Unfortunately I did not find the way to do it, so if you know it, feel free to post a comment and I will update the article.

Configure the web application

1) WEB.xml

<servlet>

    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.demo.employee.service.rest.impl</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/resources/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Creating a simple REST Service to test the environment

2). EmployeeResource.java

package com.demo.employee.service.rest.impl;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;

@Path("/hr/")
public class EmployeeResource {
 @GET
 @Produces("text/plain")
 @Path("/employee")
 public String getEmployee() {
    return "Hello World!";
 }
}

You should be able to test it, stop the server and run it again, enter the following URL in your browser:
http://localhost:8888/resources/hr/employee
or
http://localhost:8888/rest/hr/employee

if Run successfully it means your configuration is working fine and you are good to go to develop further.

Now We will create one demo application which returns employee email,First Name,and Last Name using REST.

To do that you have to perform some changes in EmployeeResouce.java
and you need to add some classes which are as follows:

1)  Employee Model class : Employee.java

package com.demo.employee.service.model;

import java.util.Date;

public class Employee {

private String firstName;
private String lastName;
private Date hireDate;

public Employee() {}

public Employee(String firstName, String lastName, Date hireDate, String email) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
    this.hireDate = hireDate;
    this.email = email;
}

<generated setter and getter >

public String toString() {
    StringBuffer sb = new StringBuffer();
    sb.append("First: ").append(getFirstName());
    sb.append(" - Last: ").append(getLastName());
    sb.append(" - Date: ").append(getHireDate());
    sb.append(" - Email: ").append(getEmail());
    return sb.toString();
}
}

Converter class for your entity

I usually encapsulate all the transformation in some converter class, like that I do not directly couple my business class to the serialisation mechanism. (So I do that for classes and lists of classes). So instead of adding the JAXB annotations to the Employee class itself, let's create an EmployeeConverter class that will be responsible of the transformation and used by your REST service.

2)  EmployeeConverter.java

package com.demo.employee.service.converter;

import java.util.Date;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.grallandco.employee.service.model.Employee;

@XmlRootElement(name = "employee")
public class EmployeeConverter {
private Employee entity = null;

public EmployeeConverter() {
     entity = new Employee();
     }

     public EmployeeConverter(Employee entity) {
     this.entity = entity;
     }

     @XmlElement
     public String getFirstName() {
     return entity.getFirstName();
     }

     @XmlElement
     public String getLastName() {
     return entity.getLastName();
     }

     @XmlElement
     public Date getHireDate() {
     return entity.getHireDate();
     }

     @XmlElement
     public String getEmail() {
     return entity.getEmail();
     }

     public Employee getEmployee() {
     return entity;
     }

     public void setFirstName(String firstName) {
     entity.setFirstName(firstName);
     }

     public void setHireDate(Date hireDate) {
     entity.setHireDate(hireDate);
     }

     public void setLastName(String email) {
     entity.setEmail(email);
     }

     public void setEmail(String lastName) {
     entity.setLastName(lastName);
     }

   }

Add support to JSON and XML to your REST service

You need to change the EmployeeRessource class, to change the signature and add new annotations of the getEmployee() method.
The annotation you are adding:

@Produces({"application/xml", "application/json"}) : indicates which type of content will be produced by the service. Based on the type of the request.

@Path("/employee/{employeeEmail}/") :    change the Path to indicate a Path parameter, here for example the URL can accept an email in the URI - not the best example, but you get the point...

public EmployeeConverter getEmployee( @PathParam ("employeeEmail") String email)  : change the type returned by the method and take a parameter as String that match the Path param defined in the @Path annotation.

3). EmployeeResource.java

package com.demo.employee.service.rest.impl;

      import javax.ws.rs.GET;
      import javax.ws.rs.Path;
      import javax.ws.rs.PathParam;
      import javax.ws.rs.Produces;
      import com.demo.employee.service.converter.EmployeeConverter;
      import com.demo.employee.service.model.Employee;

      @Path("/hr/")
      public class EmployeeResource {
           @GET
           @Produces({"application/xml", "application/json"})
           @Path("/employee/{employeeEmail}/")
           public EmployeeConverter getEmployee( @PathParam ("employeeEmail")
           String email) {
               //dummy code
               Employee emp = new Employee();
               emp.setEmail(email);
               emp.setFirstName("Dhruv");
               emp.setLastName("Gurjar");
               EmployeeConverter converter = new EmployeeConverter(emp);
               return converter;
           }

      }

Test the service
You can now run the server locally and test the service

http://localhost:8888/rest/hr/employee/test@test.com

This will return an XML document.


问:
Rectifying browser scaling
When designing a website, the website looks proper on all displays and browsers. However, when moving towards HDPI displays (above the resolution of 1920x1080), chrome and Firefox scale the content by default. This makes text, that looks correct on Microsoft Edge, very big. I could change my browser settings but the not everyone would.

I would like to know how to have the text scale properly and look the right size on HDPI displays.

答:
Use Media Queries

```<code>@media screen and (max-device-width : 1080px)
    {
      body or yourdiv element
      {
        font:<size>px/em/cm;
      }
    }
</code>```

This Link might help as well. Optimize for Displays

Title: Rectifying browser scaling

Body:
Use Media Queries

@media screen and (max-device-width : 1080px)
    {
      body or yourdiv element
      {
        font:<size>px/em/cm;
      }
    }

This Link might help as well. Optimize for Displays


问:
PasteSpecial is pasting multiple times
My goal is : to filter some rows, copy those filtered rows and paste it on another sheet.
I'm doing it twice : the first time, it's working well but the second time, not at all.
Before my sample of code, you need to know : wsData ---filter--> wsDataUpdated --- filter ---> wsDataUpdated2 .

The problem is : the second filter is quite ok, but the paste is like awkward : it's pasting all over the range, I mean : if I have only 2 rows after the filter, and i'm pasting it on the wsDataUpdated2 with the range : ("A1:A100") it'll paste it 50 times !! The awkward part is that it's exactly the same code of my first filter, and on my first filter, even if I have less rows than my range, it's not pasting twice or more... By the way, with some breakpoints, I've seen that the filtered part and the copy part is perfect. The paste part is not okay at all.

Here's a sample of my code :

```<code>    wsDataUpdated.Range("B4").CurrentRegion.AdvancedFilter xlFilterInPlace, wsCriteria2.Range("A1").CurrentRegion
    wsDataUpdated.Range("A1:AG10150").SpecialCells(xlCellTypeVisible).Copy
    wsDataUpdated2.Range("A1:AG10150").PasteSpecial Paste:=xlPasteValues
    wsDataUpdated2.Range("A1:AG10150").PasteSpecial Paste:=xlPasteFormats
</code>```

答:
This is normal behaviour. Try manual copy-paste of 3 cells into a selection of 9 cells: You'll get three copies. Replace

```<code>wsDataUpdated2.Range("A1:AG10150")
</code>```

with

```<code>wsDataUpdated2.Range("A1")
</code>```

That should do the trick.

Title: PasteSpecial is pasting multiple times

Body:
My goal is : to filter some rows, copy those filtered rows and paste it on another sheet.
I'm doing it twice : the first time, it's working well but the second time, not at all.
Before my sample of code, you need to know : wsData ---filter--> wsDataUpdated --- filter ---> wsDataUpdated2 .

The problem is : the second filter is quite ok, but the paste is like awkward : it's pasting all over the range, I mean : if I have only 2 rows after the filter, and i'm pasting it on the wsDataUpdated2 with the range : ("A1:A100") it'll paste it 50 times !! The awkward part is that it's exactly the same code of my first filter, and on my first filter, even if I have less rows than my range, it's not pasting twice or more... By the way, with some breakpoints, I've seen that the filtered part and the copy part is perfect. The paste part is not okay at all.

Here's a sample of my code :

    wsDataUpdated.Range("B4").CurrentRegion.AdvancedFilter xlFilterInPlace, wsCriteria2.Range("A1").CurrentRegion
    wsDataUpdated.Range("A1:AG10150").SpecialCells(xlCellTypeVisible).Copy
    wsDataUpdated2.Range("A1:AG10150").PasteSpecial Paste:=xlPasteValues
    wsDataUpdated2.Range("A1:AG10150").PasteSpecial Paste:=xlPasteFormats

Body:
This is normal behaviour. Try manual copy-paste of 3 cells into a selection of 9 cells: You'll get three copies. Replace

wsDataUpdated2.Range("A1:AG10150")

with

wsDataUpdated2.Range("A1")

That should do the trick.


问:
Simplifying or improving a method
The following code is executed before the model is saved. It checks a has_many association for change before looping through and setting a value on each. It checks through each answer option whether the correct_answer is changed on any of the answers. If so, it looks for which was changed and was true.

```<code>if self.answer_options.select{|a| a.correct_answer_changed?}.any?
  self.answer_options.each do |answer_option|
    if answer_option.correct_answer_changed? && !answer_option.correct_answer_was
      answer_option.correct_answer = true
    else
      answer_option.correct_answer = false
    end
  end
end
</code>```

How could I simplify or improve this method?

答:
```<code>answer_options.each do |answer_option|
  answer_option.correct_answer =
    answer_option.correct_answer_changed? && !answer_option.correct_answer_was
end
if answer_options.all?{|answer_option| answer_option.correct_answer == false}
  answer_options.each{|answer_option| answer_option.correct_answer == nil}
end
</code>```

Title: Simplifying or improving a method

Body:
The following code is executed before the model is saved. It checks a has_many association for change before looping through and setting a value on each. It checks through each answer option whether the correct_answer is changed on any of the answers. If so, it looks for which was changed and was true.

if self.answer_options.select{|a| a.correct_answer_changed?}.any?
  self.answer_options.each do |answer_option|
    if answer_option.correct_answer_changed? && !answer_option.correct_answer_was
      answer_option.correct_answer = true
    else
      answer_option.correct_answer = false
    end
  end
end

How could I simplify or improve this method?


问:
ViewCompat.setNestedScrollingEnabled() not working on KitKat
ViewCompat.setNestedScrollingEnabled() is not working on KitKat. It does work fine on Lollipop.

What maybe the issue and how to resolve it?

答:
I lots of search and found my self solution !!!
I am happy for this code and working fine </p>

```<code><android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:fillViewport="true">
</code>```

Body:
I lots of search and found my self solution !!!
I am happy for this code and working fine

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:fillViewport="true">


问:
How to find product of arithmetic progression?
I need to write a function to find a product of arithmetic progression elements (using recursion). I have only vague idea how to do it – something like this:

```<code>public static int product(int n)
{
   if (n == 0)
      return 0;
   else
      return <some code> * product(n-1);
}
</code>```

Could you at least give me a hint?

答:
The following code should do the trick:

```<code>public static int Product(int arithInitial, int arithDifference, int n)
{
   if (n == 1)
      return GetArithmeticSeriesTerm(arithInitial,arithDifference,1);
   else
      return GetArithmeticSeriesTerm(arithInitial,arithDifference,n) * Product(arithInitial, arithDifference, n-1);
}

public static int GetArithmeticSeriesTerm(int initial, int difference, int position)
{
    return initial+difference*(position-1);
}
</code>```

I have created a new method to get the elements of the arithmetic progression. I've also changed the base case of the recursion to be n==1 and then put the call to the arithmetic series term.

It should hopefully be pretty self explanatory as to what it does.

For the first four terms of the series 1,3,5,7,... you would call it as

```<code>int result = Product(1,2,4)`
</code>```

Note: You don't need two methods for this but I feel that introducing the second method makes it clearer what the code is doing. You could of course just inline the expression and of course your base case can in fact be simplified to just initial if you wanted to make it a bit cleaner. Using the full method though makes it very intuitive of why we are doing that.

Body:
I need to write a function to find a product of arithmetic progression elements (using recursion). I have only vague idea how to do it – something like this:

public static int product(int n)
{
   if (n == 0)
      return 0;
   else
      return <some code> * product(n-1);
}

Could you at least give me a hint?

Body:
The following code should do the trick:

public static int Product(int arithInitial, int arithDifference, int n)
{
   if (n == 1)
      return GetArithmeticSeriesTerm(arithInitial,arithDifference,1);
   else
      return GetArithmeticSeriesTerm(arithInitial,arithDifference,n) * Product(arithInitial, arithDifference, n-1);
}

public static int GetArithmeticSeriesTerm(int initial, int difference, int position)
{
    return initial+difference*(position-1);
}

I have created a new method to get the elements of the arithmetic progression. I've also changed the base case of the recursion to be n==1 and then put the call to the arithmetic series term.

It should hopefully be pretty self explanatory as to what it does.

For the first four terms of the series 1,3,5,7,... you would call it as

int result = Product(1,2,4)`

Note: You don't need two methods for this but I feel that introducing the second method makes it clearer what the code is doing. You could of course just inline the expression and of course your base case can in fact be simplified to just initial if you wanted to make it a bit cleaner. Using the full method though makes it very intuitive of why we are doing that.


问:
PDF file when opening in Android Nougat is showing blank screen
I am creating a PDF file and saving it in local storage. When trying to open it, it is working perfect in all devices except in Android N. I am able to open PDF file in Android N using FileProvider, but it is displaying as blank.

This is my URI

```<code>content://com.products.provider/external_storage_root/Android/data/com.products/in_17052017_170502_1_1001.pdf
</code>```

This is my code

```<code>Uri path;

File pdfFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
                + "Android" + "/" + "data" + "/" + "com.products" + "/" + file);

if (Build.VERSION.SDK_INT >= 24) {
            path = FileProvider.getUriForFile(getActivity(), "com.products.provider", pdfFile);
        } else {
            path = Uri.fromFile(pdfFile);
        }

        // Setting the intent for pdf reader
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

        try {
            startActivity(pdfIntent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(getActivity(), "Can't read pdf file", Toast.LENGTH_SHORT).show();
        }
</code>```

答:
The problem is with how you are setting the flags on the intent

```<code>pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
</code>```

Instead, try this:

```<code>pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
</code>```

Body:
I am creating a PDF file and saving it in local storage. When trying to open it, it is working perfect in all devices except in Android N. I am able to open PDF file in Android N using FileProvider, but it is displaying as blank.

This is my URI

content://com.products.provider/external_storage_root/Android/data/com.products/in_17052017_170502_1_1001.pdf

This is my code

Uri path;

File pdfFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
                + "Android" + "/" + "data" + "/" + "com.products" + "/" + file);

if (Build.VERSION.SDK_INT >= 24) {
            path = FileProvider.getUriForFile(getActivity(), "com.products.provider", pdfFile);
        } else {
            path = Uri.fromFile(pdfFile);
        }

        // Setting the intent for pdf reader
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

        try {
            startActivity(pdfIntent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(getActivity(), "Can't read pdf file", Toast.LENGTH_SHORT).show();
        }

Body:
The problem is with how you are setting the flags on the intent

pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Instead, try this:

pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);


问:
Symfony - Manage a big amount of data uploads to server
I'm currently working on a management system for a 50 people agency.
Those people needs to upload a huge amount of data to the server (thousands of files, light and heavy ones, can be several gigabytes)

I can upload file to the mail server, but I want to manage those files on a storage server.
How could I transfer my files to my storage server and give back storage informations to the web server ?
What would be the better solution to manage this kind of storage with a Symfony app ?

Thanks a lot

答:
You can use KnpGaufretteBundle as a filesystem abstraction layer and implement your own custom adapter service to provide methods to communicate with your remote storage. </p>

```<code># app/config/config.yml
knp_gaufrette:
    adapters:
        foo:
            service:
                id:     my.adapter.service
</code>```

Body:
You can use KnpGaufretteBundle as a filesystem abstraction layer and implement your own custom adapter service to provide methods to communicate with your remote storage.

# app/config/config.yml
knp_gaufrette:
    adapters:
        foo:
            service:
                id:     my.adapter.service


问:
New Array's key should be another Array's value
I want to create new array.

Value of element in array should be blank.

Key of array should another array's value.

```<code>$Oldarr =  Array
(
    [0] => Webseite,
    [1] => Bestellung,
    [2] => Verkäufer,
    [3] => Käufer,
    [4] => Warenwert,
    [5] => Lieferkosten,
    [6] => Produktname,
    [7] => Article Nr,
    [8] => Anzahl
);
</code>```

And New array shoud be

```<code>$Newarr =  Array
(
    ['Bestellung'] => '',
    ['Verkäufer'] => '',
    ['Käufer'] => '',
    ['Warenwert'] => '',
    ['Lieferkosten'] => '',
    ['Produktname'] => '',
    ['Article Nr'] => '',
    ['Anzahl'] => ''
);
</code>```

答:
use array_flip to make key as values and values as keys.

```<code>$newarr = array_flip($Oldarr);
</code>```

If you need to set blank values as well then you can use array_fill_keys like:

```<code>$newarr = array_flip($Oldarr);
$newarr = array_fill_keys($newarr, null);//for null values
$newarr = array_fill_keys($newarr, '');//for empty string values
</code>```

Edited:

only array_fill_keys will work in your scenario (credit goes to @Sougata Bose who commented here)

```<code>$newarr = array_fill_keys($Oldarr, '');//for empty string values
</code>```

Body:
I want to create new array.

Value of element in array should be blank.

Key of array should another array's value.

$Oldarr =  Array
(
    [0] => Webseite,
    [1] => Bestellung,
    [2] => Verkäufer,
    [3] => Käufer,
    [4] => Warenwert,
    [5] => Lieferkosten,
    [6] => Produktname,
    [7] => Article Nr,
    [8] => Anzahl
);

And New array shoud be

$Newarr =  Array
(
    ['Bestellung'] => '',
    ['Verkäufer'] => '',
    ['Käufer'] => '',
    ['Warenwert'] => '',
    ['Lieferkosten'] => '',
    ['Produktname'] => '',
    ['Article Nr'] => '',
    ['Anzahl'] => ''
);

Body:
use array_flip to make key as values and values as keys.

$newarr = array_flip($Oldarr);

If you need to set blank values as well then you can use array_fill_keys like:

$newarr = array_flip($Oldarr);
$newarr = array_fill_keys($newarr, null);//for null values
$newarr = array_fill_keys($newarr, '');//for empty string values

Edited:

only array_fill_keys will work in your scenario (credit goes to @Sougata Bose who commented here)

$newarr = array_fill_keys($Oldarr, '');//for empty string values


问:
Autolayout using anchors not laying out my views the way I intended?
So I have a fairly simple cell view that I am trying to customize. I have a bunch of fields and label that I would like to layout as shown in the below image

However what I end up with using the constraints I have setup looks something like this...

indexLabelBackground (circle)

indexLabel (number)

repsField (0 the left of REPS)

repsLabel (REPS string)

dividerLabel ("/" string)

weightField (0 to the left of POUNDS)

weightLabel (POUNDS string)

I have looked at my constraints over and over again and I can't find anything that would lead me to think my constraints are wrong so Im hoping a fresh pair of eyes can help me identify this puzzling problem...

P.S. I even created a new project and attempted to recreate this layout using storyboards using the same constraints which seemed to look good.

```<code>private func setupViews() {
    addSubview(indexLabelBackground)
    indexLabelBackground.addSubview(indexLabel)
    addSubview(repsField)
    addSubview(repsLabel)
    addSubview(dividerLabel)
    addSubview(weightField)
    addSubview(weightLabel)

    indexLabelBackground.leftAnchor.constraint(equalTo: leftAnchor, constant: 24).isActive = true
    indexLabelBackground.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    indexLabelBackground.heightAnchor.constraint(equalToConstant: 24).isActive = true
    indexLabelBackground.widthAnchor.constraint(equalToConstant: 24).isActive = true

    indexLabel.centerXAnchor.constraint(equalTo: indexLabelBackground.centerXAnchor).isActive = true
    indexLabel.centerYAnchor.constraint(equalTo: indexLabelBackground.centerYAnchor).isActive = true

    repsField.leftAnchor.constraint(equalTo: indexLabelBackground.rightAnchor, constant: 8).isActive = true
    repsField.rightAnchor.constraint(equalTo: repsLabel.leftAnchor, constant: -8).isActive = true
    repsField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    repsLabel.rightAnchor.constraint(equalTo: dividerLabel.leftAnchor, constant: -16).isActive = true
    repsLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    dividerLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    dividerLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    weightField.leftAnchor.constraint(equalTo: dividerLabel.rightAnchor, constant: 16).isActive = true
    weightField.rightAnchor.constraint(equalTo: weightLabel.leftAnchor, constant: -8).isActive = true
    weightField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    weightLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -16).isActive = true
    weightLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
//  weightLabel.widthAnchor.constraint(equalToConstant: 60).isActive = true //note this fixes the problem but forces my label to be a fixed width
    }
</code>```

So something to note is that if you look at the last line, this can be "fixed" in a hacky way such as adding a width constraint to the weightLabel. However I'd like to avoid this as it seems hacky and unnecessary with the right constraints.

答:
The problem is that you have multiple elements (fields and labels) in your cell that can be stretched to make the layout work, and you haven't told Auto Layout which ones not to stretch.

You want your labels to stick to their intrinsic content size (be as big as they need to be to show the text, but no bigger).  You specify this by setting a high content hugging priority.  By default, when you programmatically create UITextFields and UILabels, their content hugging priority is low (250).  Since they are all low, Auto Layout will stretch them in some unknown order to make the layout work.

I suggest adding these 3 lines to set the content hugging priority to high (750) for your 3 labels:

```<code>repsLabel.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal)
dividerLabel.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal)
weightLabel.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal)
</code>```

That way, your labels will always be the size needed to hold their text, and they can then anchor your layout (pun intended).

I even created a new project and attempted to recreate this layout
  using storyboards using the same constraints which seemed to look
  good.

In the Storyboard, UILabels have a higher default content hugging priority (251) than UITextFields (250), so it just works.  It beats me why they chose to give them all low (250) when created programmatically.

Body:
So I have a fairly simple cell view that I am trying to customize. I have a bunch of fields and label that I would like to layout as shown in the below image

However what I end up with using the constraints I have setup looks something like this...

indexLabelBackground (circle)

indexLabel (number)

repsField (0 the left of REPS)

repsLabel (REPS string)

dividerLabel ("/" string)

weightField (0 to the left of POUNDS)

weightLabel (POUNDS string)

I have looked at my constraints over and over again and I can't find anything that would lead me to think my constraints are wrong so Im hoping a fresh pair of eyes can help me identify this puzzling problem...

P.S. I even created a new project and attempted to recreate this layout using storyboards using the same constraints which seemed to look good.

private func setupViews() {
    addSubview(indexLabelBackground)
    indexLabelBackground.addSubview(indexLabel)
    addSubview(repsField)
    addSubview(repsLabel)
    addSubview(dividerLabel)
    addSubview(weightField)
    addSubview(weightLabel)

    indexLabelBackground.leftAnchor.constraint(equalTo: leftAnchor, constant: 24).isActive = true
    indexLabelBackground.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    indexLabelBackground.heightAnchor.constraint(equalToConstant: 24).isActive = true
    indexLabelBackground.widthAnchor.constraint(equalToConstant: 24).isActive = true

    indexLabel.centerXAnchor.constraint(equalTo: indexLabelBackground.centerXAnchor).isActive = true
    indexLabel.centerYAnchor.constraint(equalTo: indexLabelBackground.centerYAnchor).isActive = true

    repsField.leftAnchor.constraint(equalTo: indexLabelBackground.rightAnchor, constant: 8).isActive = true
    repsField.rightAnchor.constraint(equalTo: repsLabel.leftAnchor, constant: -8).isActive = true
    repsField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    repsLabel.rightAnchor.constraint(equalTo: dividerLabel.leftAnchor, constant: -16).isActive = true
    repsLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    dividerLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    dividerLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    weightField.leftAnchor.constraint(equalTo: dividerLabel.rightAnchor, constant: 16).isActive = true
    weightField.rightAnchor.constraint(equalTo: weightLabel.leftAnchor, constant: -8).isActive = true
    weightField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    weightLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -16).isActive = true
    weightLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
//  weightLabel.widthAnchor.constraint(equalToConstant: 60).isActive = true //note this fixes the problem but forces my label to be a fixed width
    }

So something to note is that if you look at the last line, this can be "fixed" in a hacky way such as adding a width constraint to the weightLabel. However I'd like to avoid this as it seems hacky and unnecessary with the right constraints.

Body:
The problem is that you have multiple elements (fields and labels) in your cell that can be stretched to make the layout work, and you haven't told Auto Layout which ones not to stretch.

You want your labels to stick to their intrinsic content size (be as big as they need to be to show the text, but no bigger).  You specify this by setting a high content hugging priority.  By default, when you programmatically create UITextFields and UILabels, their content hugging priority is low (250).  Since they are all low, Auto Layout will stretch them in some unknown order to make the layout work.

I suggest adding these 3 lines to set the content hugging priority to high (750) for your 3 labels:

repsLabel.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal)
dividerLabel.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal)
weightLabel.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal)

That way, your labels will always be the size needed to hold their text, and they can then anchor your layout (pun intended).

I even created a new project and attempted to recreate this layout
  using storyboards using the same constraints which seemed to look
  good.

In the Storyboard, UILabels have a higher default content hugging priority (251) than UITextFields (250), so it just works.  It beats me why they chose to give them all low (250) when created programmatically.


问:
Django - How to add data to a ManyToMany field model?
I have the following models, view and template:

models.py:

```<code>class Batch(models.Model):
    material_id = models.ManyToManyField(AssetMetadata)
    user = models.ForeignKey(User)

    def __str__(self):
        return 'Batch_' + str(self.pk) + '_' + self.user.username

class AssetMetadata(models.Model):

    material_id = models.CharField(max_length=256, blank=True)
    series_title = models.CharField(max_length=256, blank=True)
    season_title = models.CharField(max_length=256, blank=True)
    season_number = models.IntegerField(default=0)
    episode_title = models.CharField(max_length=256, blank=True)
    episode_number = models.IntegerField(default=0)
    synopsis = models.TextField(max_length=1024, blank=True)
    ratings = models.CharField(max_length=256, blank=True)

    def __str__(self):
        return self.material_id
</code>```

views.py:

```<code>def assets_in_repo(request):

    asset_list = AssetMetadata.objects.order_by('id').all()
    page = request.GET.get('page', 1)
    paginator = Paginator(asset_list, 50)

    try:
        assets = paginator.page(page)
    except PageNotAnInteger:
        assets = paginator.page(1)
    except EmptyPage:
        assets = paginator.page(paginator.num_pages)

    if request.method == 'POST':

        batch_list = request.POST.getlist('batch')
        print(batch_list)

    return render(request, 'assets_db/assets.html', {'assets': assets})
</code>```

snippet from template:

```<code><form method="post">{% csrf_token %}
    <input type="submit" value="Create Batch" align="right">
    <table class="table table-striped" id="myTable">
        <tr>
            <th>ID</th>
            <th>Material ID</th>
            <th>Series Title</th>
            <th>Season Tile</th>
            <th>Season Number</th>
            <th>Episode Title</th>
            <th>Episode Number</th>
            <th>Create Batch</th>
        </tr>
        {%  for i in assets %}<tr>
            <td>{{i.pk}}</td>
            <td><a href="/repo/{{ i.id}}">{{i.material_id}}</a></td>
            <td>{{i.series_title}}</td>
            <td>{{i.season_title}}</td>
            <td>{{i.season_number}}</td>
            <td>{{i.episode_title}}</td>
            <td>{{i.episode_number}}</td>
            <td>
                <input type="checkbox" name="batch" value="{{i.pk}}">
            </td>
        </tr>{% endfor %}
    </table>
    </form>
</code>```

I am trying to get the data provided from the checkbox and save it in the Batch model.

The user selects assets to create a batch, the form returns the pk for these assetss in AssetMetadata and the selections are stored in a list create via batch_list = request.POST.getlist('batch'). I want to use the data stored in this list to create a new entry in Batch which then links to the asset pk in AssetMetadata.

I have been able to do this successfully in the Django admin page but i would ideally do this in teh view.

I have read https://docs.djangoproject.com/en/1.10/ref/models/relations/ and search stackoverflow but i am stumped as how to do this.

答:
I think you need </p>

```<code>obj = AssetMetadata.objects.get(id=pk)
obj.batch_set.add(* batch_list)
</code>```

Body:
I have the following models, view and template:

models.py:

class Batch(models.Model):
    material_id = models.ManyToManyField(AssetMetadata)
    user = models.ForeignKey(User)

    def __str__(self):
        return 'Batch_' + str(self.pk) + '_' + self.user.username

class AssetMetadata(models.Model):

    material_id = models.CharField(max_length=256, blank=True)
    series_title = models.CharField(max_length=256, blank=True)
    season_title = models.CharField(max_length=256, blank=True)
    season_number = models.IntegerField(default=0)
    episode_title = models.CharField(max_length=256, blank=True)
    episode_number = models.IntegerField(default=0)
    synopsis = models.TextField(max_length=1024, blank=True)
    ratings = models.CharField(max_length=256, blank=True)

    def __str__(self):
        return self.material_id

views.py:

def assets_in_repo(request):

    asset_list = AssetMetadata.objects.order_by('id').all()
    page = request.GET.get('page', 1)
    paginator = Paginator(asset_list, 50)

    try:
        assets = paginator.page(page)
    except PageNotAnInteger:
        assets = paginator.page(1)
    except EmptyPage:
        assets = paginator.page(paginator.num_pages)

    if request.method == 'POST':

        batch_list = request.POST.getlist('batch')
        print(batch_list)

    return render(request, 'assets_db/assets.html', {'assets': assets})

snippet from template:

<form method="post">{% csrf_token %}
    <input type="submit" value="Create Batch" align="right">

            ID
            Material ID
            Series Title
            Season Tile
            Season Number
            Episode Title
            Episode Number
            Create Batch

        {%  for i in assets %}

            {{i.pk}}
            {{i.material_id}}
            {{i.series_title}}
            {{i.season_title}}
            {{i.season_number}}
            {{i.episode_title}}
            {{i.episode_number}}

                <input type="checkbox" name="batch" value="{{i.pk}}">

{% endfor %}

    </form>

I am trying to get the data provided from the checkbox and save it in the Batch model.

The user selects assets to create a batch, the form returns the pk for these assetss in AssetMetadata and the selections are stored in a list create via batch_list = request.POST.getlist('batch'). I want to use the data stored in this list to create a new entry in Batch which then links to the asset pk in AssetMetadata.

I have been able to do this successfully in the Django admin page but i would ideally do this in teh view.

I have read https://docs.djangoproject.com/en/1.10/ref/models/relations/ and search stackoverflow but i am stumped as how to do this.

Body:
I think you need

obj = AssetMetadata.objects.get(id=pk)
obj.batch_set.add(* batch_list)


问:
Copying string content to char array
I want to copy the content in the string to char array.

Can I use this code StrLCopy(C, pChar(@S[1]), high(C));

I am currently using Delphi 2006. Will there be any problems if I upgrade my Delphi version because of Unicode support provided in newer versions?

If not, what can be the code for this conversion?

答:
When you're copying a string into an array, prefer StrPLCopy.

```<code>StrPLCopy(C, S, High(C));
</code>```

That will work in all versions of Delphi, even when Unicode is in effect. The character types of C and S should be the same; don't try to use that function to convert between Ansi and Unicode characters.

But StrLCopy is fine, too. You don't need to have so much pointer code, though. Delphi already knows how to convert a string into a PChar:

```<code>StrLCopy(C, PChar(S), High(C));
</code>```

Title: Copying string content to char array

Body:
When you're copying a string into an array, prefer StrPLCopy.

StrPLCopy(C, S, High(C));

That will work in all versions of Delphi, even when Unicode is in effect. The character types of C and S should be the same; don't try to use that function to convert between Ansi and Unicode characters.

But StrLCopy is fine, too. You don't need to have so much pointer code, though. Delphi already knows how to convert a string into a PChar:

StrLCopy(C, PChar(S), High(C));