问:
Intermittent file lock exception when calling File.AppendAllLines many times and file is open in Visual Studio
I have a number of methods on a class which I am calling via reflection:

```<code>var instances = new TestsBase[] {
    new CompilerGeneratedTestData(),
    new ConstructedTestData(),
    new VBCompilerGeneratedTestData()
};

var methods = instances
    .SelectMany(x =>
        x.GetType()
            .GetMethods()
            .Select(m => (instance: x, method: m))
    )
    .OrderBy(x => x.method.ReflectedType.Name)
    .ThenBy(x => x.method.Name)
    .ToList();
</code>```

Each of these methods ultimately calls the following code:

```<code>string[] toWrite = ...
var outfileName = @"c:\path\to\text.txt";
File.AppendAllLines(outfileName, toWrite);
</code>```

When I run the code, at some point I get the following exception at the call to File.AppendAllLines:

System.IO.IOException: 'The process cannot access the file 'c:\path\to\text.txt' because it is being used by another process.'

The original method call appears to be different each time; it's not failing on a particular method.

The application is a simple console project, with no multithreading in my code.

How can I avoid this error?

I have a set of abstract classes with XUnit test methods:

```<code>public class ConstructedBase {
    protected abstract void RunTest(object o, string csharp, string vb, string factoryMethods);

    [Fact]
    public void ConstructAdd() => RunTest(Expression.Add(x, y), "x + y", "x + y", "Add(x, y)");

    ...
}
</code>```

and a class which defines the implementation of RunTest:

```<code>class ConstructedTestData : ConstructedBase {
    protected override void RunTest(object o, string csharp, string vb, string factoryMethods) => Runner.WriteData(o, factoryMethods);
}
</code>```

as forwarding to a static method:

```<code>public static class Runner {
    public static readonly string outfileName = @"c:\path\to\text.txt";
    public static void WriteData(object o, string testData) {
        string[] toWrite = ...
        File.AppendAllLines(outfileName, toWrite);
    }
}
</code>```

Update

This error only appears to happen if the text file is simultaneously open in Visual Studio.

答:
The issue is likely that Visual Studio (or anti virus) is holding a lock on the file.

You should close it in Visual Studio.

Body:
I have a number of methods on a class which I am calling via reflection:

var instances = new TestsBase[] {
    new CompilerGeneratedTestData(),
    new ConstructedTestData(),
    new VBCompilerGeneratedTestData()
};

var methods = instances
    .SelectMany(x =>
        x.GetType()
            .GetMethods()
            .Select(m => (instance: x, method: m))
    )
    .OrderBy(x => x.method.ReflectedType.Name)
    .ThenBy(x => x.method.Name)
    .ToList();

Each of these methods ultimately calls the following code:

string[] toWrite = ...
var outfileName = @"c:\path\to\text.txt";
File.AppendAllLines(outfileName, toWrite);

When I run the code, at some point I get the following exception at the call to File.AppendAllLines:

System.IO.IOException: 'The process cannot access the file 'c:\path\to\text.txt' because it is being used by another process.'

The original method call appears to be different each time; it's not failing on a particular method.

The application is a simple console project, with no multithreading in my code.

How can I avoid this error?

I have a set of abstract classes with XUnit test methods:

public class ConstructedBase {
    protected abstract void RunTest(object o, string csharp, string vb, string factoryMethods);

    [Fact]
    public void ConstructAdd() => RunTest(Expression.Add(x, y), "x + y", "x + y", "Add(x, y)");

    ...
}

and a class which defines the implementation of RunTest:

class ConstructedTestData : ConstructedBase {
    protected override void RunTest(object o, string csharp, string vb, string factoryMethods) => Runner.WriteData(o, factoryMethods);
}

as forwarding to a static method:

public static class Runner {
    public static readonly string outfileName = @"c:\path\to\text.txt";
    public static void WriteData(object o, string testData) {
        string[] toWrite = ...
        File.AppendAllLines(outfileName, toWrite);
    }
}

Update

This error only appears to happen if the text file is simultaneously open in Visual Studio.


来源: stackexchange

问:
How to convert/change date format from MM/DD/YYYY to Month Date, Year?
I'm trying to convert/change my blog date from MM/DD/YYYY to Month Date, Year. For example, this date 11/12/2018 convert to November 12, 2018. Is there a way to do this correctly?

I've tried a code that suppose to work. However, the code converted/changed every blog posts' date to recent published posts' (date).

I tried this code:

```<code>var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var data = $('.date-text').text();
var arr = data.split('/');
$(".date-text").html(months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2]);
</code>```

and code converted all dates to recent published posts' date, which is now displayed as November 12, 2018 11.

Working editor: https://jsfiddle.net/s1b2fenk/

Website's image after date changed:

答:
Your problem is that in jQuery:

```<code>$(".date-text").html(...);
</code>```

changes the HTML of all elements selected by .date-text to the same value, so they all end up showing the same date.

You can use jQuery's .each method something like:

$(".date-text").each(function (){
  var months = ["January", "February", "March", "April",
                "May", "June", "July", "August",
                "September", "October", "November", "December"];
  var arr = this.textContent.split('/');
  this.textContent = months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-text">11/12/2018</div>
<div class="date-text">10/1/2018</div></code>```

You might find it simpler to use POJS:

window.addEventListener('DOMContentLoaded', function () {
  document.querySelectorAll('.date-text').forEach(el => el.textContent = formatDateString(el.textContent))
}, false);

function formatDateString(s) {
  var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var arr = s.split('/');
  return months[arr[0] - 1] + " " + arr[1] + ", " + arr[2];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="date-text">11/12/2018</div>
<div class="date-text">10/1/2018</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to convert/change my blog date from MM/DD/YYYY to Month Date, Year. For example, this date 11/12/2018 convert to November 12, 2018. Is there a way to do this correctly?

I've tried a code that suppose to work. However, the code converted/changed every blog posts' date to recent published posts' (date).

I tried this code:

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var data = $('.date-text').text();
var arr = data.split('/');
$(".date-text").html(months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2]);

and code converted all dates to recent published posts' date, which is now displayed as November 12, 2018 11.

Working editor: https://jsfiddle.net/s1b2fenk/

Website's image after date changed:

Body:
Your problem is that in jQuery:

$(".date-text").html(...);

changes the HTML of all elements selected by .date-text to the same value, so they all end up showing the same date.

You can use jQuery's .each method something like:

$(".date-text").each(function (){
  var months = ["January", "February", "March", "April",
                "May", "June", "July", "August",
                "September", "October", "November", "December"];
  var arr = this.textContent.split('/');
  this.textContent = months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2];
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-text">11/12/2018</div>
<div class="date-text">10/1/2018</div>

You might find it simpler to use POJS:

window.addEventListener('DOMContentLoaded', function () {
  document.querySelectorAll('.date-text').forEach(el => el.textContent = formatDateString(el.textContent))
}, false);

function formatDateString(s) {
  var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var arr = s.split('/');
  return months[arr[0] - 1] + " " + arr[1] + ", " + arr[2];
}

<div class="date-text">11/12/2018</div>
<div class="date-text">10/1/2018</div>


问:
dhtmlx grid.render_table in java not working
I'm setting up a dhtmlx grid for loading data using grid.render_table method in java, no rendering is done, I'm new in this

I've tried to implement the PHP 'contact_manager' demo that comes with dhtmlx in java, but grid.render_table does not populate the grid

```<code>try (PrintWriter out = response.getWriter())
        {
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup("jdbc/PsFlowWeb");
            conn = ds.getConnection(username, password);

            GridConnector gc = new GridConnector(conn);
            gc.enable_log("temp.log", false);
            LogManager.getInstance().log("any text here");
                        gc.render_table("TCiudades","csCodigoCiudad","csCodigoCiudad,csDescripcionCiudad,csTipoRiesgo");

        }
        catch (Throwable e) { e.printStackTrace(); }
</code>```

I expect the grid be populated with data from server obtained by using grid.render_table method

答: Could you please, check your log file and the response coming from your data request.</p>

Body:
I'm setting up a dhtmlx grid for loading data using grid.render_table method in java, no rendering is done, I'm new in this

I've tried to implement the PHP 'contact_manager' demo that comes with dhtmlx in java, but grid.render_table does not populate the grid

try (PrintWriter out = response.getWriter())
        {
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup("jdbc/PsFlowWeb");
            conn = ds.getConnection(username, password);

            GridConnector gc = new GridConnector(conn);
            gc.enable_log("temp.log", false);
            LogManager.getInstance().log("any text here");
                        gc.render_table("TCiudades","csCodigoCiudad","csCodigoCiudad,csDescripcionCiudad,csTipoRiesgo");

        }
        catch (Throwable e) { e.printStackTrace(); }

I expect the grid be populated with data from server obtained by using grid.render_table method


问:
Difference between missing and empty fields on JSON unmarshalling
So I have this struct in Go:

```<code>type Car struct {
    Name  string `json:"name"`
    Speed int    `json:"speed"`
}
</code>```

And I have two JSON samples that I unmarshal:

```<code>str := `{"name": "", "speed": 0}`
strTwo := `{}`
</code>```

I do the unmarshaling in this way:

```<code>car := Car{}
_ = json.Unmarshal([]byte(str), &car)

carTwo := Car{}
_ = json.Unmarshal([]byte(strTwo), &carTwo)
</code>```

Now because of the way Go deals with default value types, when I try to print the structure, I get the same result:

```<code>car - { 0}
carTwo - { 0}
</code>```

So I can't see the difference between a missing value in JSON and when a default value is passed. How can I solve this problem?

One way is to use pointers in struct:

```<code>type Car struct {
    Name  *string `json:"name"`
    Speed *int    `json:"speed"`
}
</code>```

But I get a very ugly code when using this values, I have to do pointer dereferencing everywhere

答:
Go's primitive data types are not suitable to handle the "all valid values" and an additional "is present" information.

If you do need this, one way is to use pointers, where the nil pointer value corresponds to the "missing" state.

If it is uncomfortable to work with pointers afterwards, do a "post processing": convert your structs with pointer fields to a struct value with non-pointer fields, so you can work with that later on.

You may do this "manually", or write a custom unmarshaler to make this happen automatically.

Here's an example how to do it:

```<code>type PCar struct {
    Name  *string `json:"name"`
    Speed *int    `json:"speed"`
}

type Car struct {
    Name  string `json:"-"`
    Speed int    `json:"-"`
    PCar
}

func (c *Car) UnmarshalJSON(data []byte) error {
    if err := json.Unmarshal(data, &c.PCar); err != nil {
        return err
    }

    if c.PCar.Name != nil {
        c.Name = *c.PCar.Name
    }
    if c.PCar.Speed != nil {
        c.Speed = *c.PCar.Speed
    }
    return nil
}
</code>```

Example using it:

```<code>sources := []string{
    `{"name": "", "speed": 0}`,
    `{}`,
    `{"name": "Bob", "speed": 21}`,
}

for i, src := range sources {
    var c Car
    if err := json.Unmarshal([]byte(src), &c); err != nil {
        panic(err)
    }
    fmt.Println("car", i, c)
}
</code>```

Output (try it on the Go Playground):

```<code>car 0 { 0 {0x40c200 0x4140ac}}
car 1 { 0 {<nil> <nil>}}
car 2 {Bob 21 {0x40c218 0x41410c}}
</code>```

As you can see, car 1 contains 2 non-nil pointers, because the respective fields were present in the input JSON, while car 2 contains 2 nil pointers, because those fields were missing in its input. You may use Car.Name and Car.Speed fields as non-pointers (because they are not pointers). To tell if they were present in the input, you may check the corresponding pointers Car.PCar.Name and Car.PCar.Speed if they are nil.

Body:
So I have this struct in Go:

type Car struct {
    Name  string `json:"name"`
    Speed int    `json:"speed"`
}

And I have two JSON samples that I unmarshal:

str := `{"name": "", "speed": 0}`
strTwo := `{}`

I do the unmarshaling in this way:

car := Car{}
_ = json.Unmarshal([]byte(str), &car)

carTwo := Car{}
_ = json.Unmarshal([]byte(strTwo), &carTwo)

Now because of the way Go deals with default value types, when I try to print the structure, I get the same result:

car - { 0}
carTwo - { 0}

So I can't see the difference between a missing value in JSON and when a default value is passed. How can I solve this problem?

One way is to use pointers in struct:

type Car struct {
    Name  *string `json:"name"`
    Speed *int    `json:"speed"`
}

But I get a very ugly code when using this values, I have to do pointer dereferencing everywhere

Body:
Go's primitive data types are not suitable to handle the "all valid values" and an additional "is present" information.

If you do need this, one way is to use pointers, where the nil pointer value corresponds to the "missing" state.

If it is uncomfortable to work with pointers afterwards, do a "post processing": convert your structs with pointer fields to a struct value with non-pointer fields, so you can work with that later on.

You may do this "manually", or write a custom unmarshaler to make this happen automatically.

Here's an example how to do it:

type PCar struct {
    Name  *string `json:"name"`
    Speed *int    `json:"speed"`
}

type Car struct {
    Name  string `json:"-"`
    Speed int    `json:"-"`
    PCar
}

func (c *Car) UnmarshalJSON(data []byte) error {
    if err := json.Unmarshal(data, &c.PCar); err != nil {
        return err
    }

    if c.PCar.Name != nil {
        c.Name = *c.PCar.Name
    }
    if c.PCar.Speed != nil {
        c.Speed = *c.PCar.Speed
    }
    return nil
}

Example using it:

sources := []string{
    `{"name": "", "speed": 0}`,
    `{}`,
    `{"name": "Bob", "speed": 21}`,
}

for i, src := range sources {
    var c Car
    if err := json.Unmarshal([]byte(src), &c); err != nil {
        panic(err)
    }
    fmt.Println("car", i, c)
}

Output (try it on the Go Playground):

car 0 { 0 {0x40c200 0x4140ac}}
car 1 { 0 {<nil> <nil>}}
car 2 {Bob 21 {0x40c218 0x41410c}}

As you can see, car 1 contains 2 non-nil pointers, because the respective fields were present in the input JSON, while car 2 contains 2 nil pointers, because those fields were missing in its input. You may use Car.Name and Car.Speed fields as non-pointers (because they are not pointers). To tell if they were present in the input, you may check the corresponding pointers Car.PCar.Name and Car.PCar.Speed if they are nil.


问:
HighCharts Orgcharts make scroll able container
I had a problem with highcharts organization chart. The problem is, that chart will be a big one, and I need horizontal scrollbar for container of chart, or make chart horizontally scrollable.

I have tried to enable scrollbar of chart or make container of chart scrollable using css, but no luck, highcharts trying to fit chart within window size, which is unacceptable for this case.

Tried enable scrollbar by using js code below

```<code>scrollbar: {
    enabled:true,
    barBackgroundColor: 'gray',
    barBorderRadius: 7,
    barBorderWidth: 0,
    buttonBackgroundColor: 'gray',
    buttonBorderWidth: 0,
    buttonArrowColor: 'yellow',
    buttonBorderRadius: 7,
    rifleColor: 'yellow',
    trackBackgroundColor: 'white',
    trackBorderWidth: 1,
    trackBorderColor: 'silver',
    trackBorderRadius: 7
},
</code>```

and with css using style for container like

```<code><style>
#container {
    min-width: 300px;
    margin: 1em auto;
    border: 1px solid silver;
    overflow: scroll !important;
}

#container h4 {
    text-transform: none;
    font-size: 14px;
    font-weight: normal;
}
#container p {
    font-size: 13px;
    line-height: 16px;
}
</style>
</code>```

Results can be viewed in fiddle provided below

https://jsfiddle.net/72v36msx/

So the question is - are there any way to make chart horizontally scrollable and get nice view, without making nodes so small, as it is in the fiddle, that I provided.

Any help will be appreciated !

答:
The scrollbar feature is available only for Highstock. To create a custom scrollbar set chart.width to a higher value than container width.

CSS:

```<code>#container {
    min-width: 300px;
    overflow: scroll !important;
}
</code>```

JS:

```<code>chart: {
    width: 1200,
    ...
}
</code>```

Live demo: https://jsfiddle.net/BlackLabel/5hpk3e9d/

API Reference: https://api.highcharts.com/highcharts/chart.width

Body:
I had a problem with highcharts organization chart. The problem is, that chart will be a big one, and I need horizontal scrollbar for container of chart, or make chart horizontally scrollable.

I have tried to enable scrollbar of chart or make container of chart scrollable using css, but no luck, highcharts trying to fit chart within window size, which is unacceptable for this case.

Tried enable scrollbar by using js code below

scrollbar: {
    enabled:true,
    barBackgroundColor: 'gray',
    barBorderRadius: 7,
    barBorderWidth: 0,
    buttonBackgroundColor: 'gray',
    buttonBorderWidth: 0,
    buttonArrowColor: 'yellow',
    buttonBorderRadius: 7,
    rifleColor: 'yellow',
    trackBackgroundColor: 'white',
    trackBorderWidth: 1,
    trackBorderColor: 'silver',
    trackBorderRadius: 7
},

and with css using style for container like

Results can be viewed in fiddle provided below

https://jsfiddle.net/72v36msx/

So the question is - are there any way to make chart horizontally scrollable and get nice view, without making nodes so small, as it is in the fiddle, that I provided.

Any help will be appreciated !

Body:
The scrollbar feature is available only for Highstock. To create a custom scrollbar set chart.width to a higher value than container width.

CSS:

#container {
    min-width: 300px;
    overflow: scroll !important;
}

JS:

chart: {
    width: 1200,
    ...
}

Live demo: https://jsfiddle.net/BlackLabel/5hpk3e9d/

API Reference: https://api.highcharts.com/highcharts/chart.width


问:
Play video playlist and individual video clip from playlist in Loop, AVQueuePlayer iOS Swift
I am trying to play video playlist in loop and also play individual video clip from playlist in loop in AVQueuePlayer using AVPlayerItem, but i am unable to find the solution for same below is the code that i have tried so far

General

```<code>var player : AVQueuePlayer?
var playerLayer: AVPlayerLayer?
var playerItem: [AVPlayerItem] = []

func playAtIndex(index:Int){
        for i in index ..< playerItem.count {
            let obj = playerItem[i]
            if (self.player?.canInsert(obj, after: nil))! {
                obj.seek(to: .zero, completionHandler: nil)
                self.player?.insert(obj, after: nil)
                }
        }
    }
</code>```

Initialise video player

```<code>self.player = AVQueuePlayer.init(items: self.playerItem)
self.playerLayer = AVPlayerLayer(player: self.player)
self.playerLayer?.frame = self.view!.bounds
self.playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspect
self.view!.layer.addSublayer(self.playerLayer!)
self.player?.play()
</code>```

code done so far for looping playlist, this works but some of the video from the loop does not play sometimes.

```<code>self.playAtIndex(index: 0)
</code>```

code done for looping individual video clip in playlist, but does not work

```<code>let playerItem: AVPlayerItem = note.object as! AVPlayerItem // here we get current item
playerItem.seek(to: CMTime.zero, completionHandler: nil)
self.player?.play()
</code>```

Any help will be great.!!

答:
To loop the playerItems in AVQueuePlayer, you need to add a an observer to the notification - AVPlayerItemDidPlayToEndTimeNotification

A notification that's posted when the item has played to its end time.

```<code>NotificationCenter.default.addObserver(self, selector: #selector(playerEndedPlaying), name: Notification.Name("AVPlayerItemDidPlayToEndTimeNotification"), object: nil)
</code>```

The method playerEndedPlaying(_:) will be called whenever the notification is fired.

```<code>@objc func playerEndedPlaying(_ notification: Notification) {
    DispatchQueue.main.async {[weak self] in
        if let playerItem = notification.object as? AVPlayerItem {
            self?.player?.remove(playerItem)
            playerItem.seek(to: .zero, completionHandler: nil)
            self?.player?.insert(playerItem, after: nil)
            if playerItem == self?.playerItems?.last {
                self?.pauseVideo()
            }
        }
    }
}
</code>```

The above method will be called every time a playerItem in the AVQueuePlayer ends playing.

AVQueuePlayer's insert(_:after:) is called where each playerItem is appended to the queue.

afterItem

The player item that the newly inserted player item should
  follow in the queue. Pass nil to append the item to the queue.

Loop is identified using playerItem == self?.playerItems?.last. You can add your custom handling here. I've paused the player once all the videos end playing.

Body:
I am trying to play video playlist in loop and also play individual video clip from playlist in loop in AVQueuePlayer using AVPlayerItem, but i am unable to find the solution for same below is the code that i have tried so far

General

var player : AVQueuePlayer?
var playerLayer: AVPlayerLayer?
var playerItem: [AVPlayerItem] = []

func playAtIndex(index:Int){
        for i in index ..< playerItem.count {
            let obj = playerItem[i]
            if (self.player?.canInsert(obj, after: nil))! {
                obj.seek(to: .zero, completionHandler: nil)
                self.player?.insert(obj, after: nil)
                }
        }
    }

Initialise video player

self.player = AVQueuePlayer.init(items: self.playerItem)
self.playerLayer = AVPlayerLayer(player: self.player)
self.playerLayer?.frame = self.view!.bounds
self.playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspect
self.view!.layer.addSublayer(self.playerLayer!)
self.player?.play()

code done so far for looping playlist, this works but some of the video from the loop does not play sometimes.

self.playAtIndex(index: 0)

code done for looping individual video clip in playlist, but does not work

let playerItem: AVPlayerItem = note.object as! AVPlayerItem // here we get current item
playerItem.seek(to: CMTime.zero, completionHandler: nil)
self.player?.play()

Any help will be great.!!

Body:
To loop the playerItems in AVQueuePlayer, you need to add a an observer to the notification - AVPlayerItemDidPlayToEndTimeNotification

A notification that's posted when the item has played to its end time.

NotificationCenter.default.addObserver(self, selector: #selector(playerEndedPlaying), name: Notification.Name("AVPlayerItemDidPlayToEndTimeNotification"), object: nil)

The method playerEndedPlaying(_:) will be called whenever the notification is fired.

@objc func playerEndedPlaying(_ notification: Notification) {
    DispatchQueue.main.async {[weak self] in
        if let playerItem = notification.object as? AVPlayerItem {
            self?.player?.remove(playerItem)
            playerItem.seek(to: .zero, completionHandler: nil)
            self?.player?.insert(playerItem, after: nil)
            if playerItem == self?.playerItems?.last {
                self?.pauseVideo()
            }
        }
    }
}

The above method will be called every time a playerItem in the AVQueuePlayer ends playing.

AVQueuePlayer's insert(_:after:) is called where each playerItem is appended to the queue.

afterItem

The player item that the newly inserted player item should
  follow in the queue. Pass nil to append the item to the queue.

Loop is identified using playerItem == self?.playerItems?.last. You can add your custom handling here. I've paused the player once all the videos end playing.


问:
API 'variantOutput.getProcessManifest()' is obsolete
I am trying to change version code, version name and app icon. Below is my code

```<code>    variant.outputs.all { output ->
        def newApkName
        if (output.zipAlign) {
            newApkName = "Application.apk"
        }

        output.processManifest.doLast{
            // Stores the path to the maifest.
            String manifestPath = "$manifestOutputDirectory/AndroidManifest.xml"
            // Stores the contents of the manifest.
            def manifestContent = file(manifestPath).getText()
            // Changes the version code in the stored text.
            manifestContent = manifestContent.replace('android:versionName="dev_build"',
                    String.format('android:versionName="%s"', variant.versionName))
            // Overwrites the manifest with the new text.
            file(manifestPath).write(manifestContent)
        }

        output.processManifest.doLast{
            // Stores the path to the maifest.
            String manifestPath = "$manifestOutputDirectory/AndroidManifest.xml"
            // Stores the contents of the manifest.
            def manifestContent = file(manifestPath).getText()
            // Changes the version code in the stored text.
            manifestContent = manifestContent.replace('android:icon="@drawable/app_icon_main"',
                    String.format('android:icon="@drawable/%s"', getVersionIconName()))
            // Overwrites the manifest with the new text.
            file(manifestPath).write(manifestContent)
        }

        outputFileName = "Application.apk"
    }
</code>```

Getting bellow warning:
WARNING: API 'variantOutput.getProcessManifest()' is obsolete and has been replaced with 'variantOutput.getProcessManifestProvider()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance.
To determine what is calling variantOutput.getProcessManifest(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.
Affected Modules: Application

Environment Details:
Android Studio : 3.3.1
Gradle Version: 4.10.0
Build Tool Version  28.0.2

答:
Change the following

```<code>output.processManifest.doLast {
    //your code
}
</code>```

with

```<code>output.getProcessManifestProvider().get().doLast {
    //your code
}
</code>```

Body:
I am trying to change version code, version name and app icon. Below is my code

    variant.outputs.all { output ->
        def newApkName
        if (output.zipAlign) {
            newApkName = "Application.apk"
        }

        output.processManifest.doLast{
            // Stores the path to the maifest.
            String manifestPath = "$manifestOutputDirectory/AndroidManifest.xml"
            // Stores the contents of the manifest.
            def manifestContent = file(manifestPath).getText()
            // Changes the version code in the stored text.
            manifestContent = manifestContent.replace('android:versionName="dev_build"',
                    String.format('android:versionName="%s"', variant.versionName))
            // Overwrites the manifest with the new text.
            file(manifestPath).write(manifestContent)
        }

        output.processManifest.doLast{
            // Stores the path to the maifest.
            String manifestPath = "$manifestOutputDirectory/AndroidManifest.xml"
            // Stores the contents of the manifest.
            def manifestContent = file(manifestPath).getText()
            // Changes the version code in the stored text.
            manifestContent = manifestContent.replace('android:icon="@drawable/app_icon_main"',
                    String.format('android:icon="@drawable/%s"', getVersionIconName()))
            // Overwrites the manifest with the new text.
            file(manifestPath).write(manifestContent)
        }

        outputFileName = "Application.apk"
    }

Getting bellow warning:
WARNING: API 'variantOutput.getProcessManifest()' is obsolete and has been replaced with 'variantOutput.getProcessManifestProvider()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance.
To determine what is calling variantOutput.getProcessManifest(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.
Affected Modules: Application

Environment Details:
Android Studio : 3.3.1
Gradle Version: 4.10.0
Build Tool Version  28.0.2

Body:
Change the following

output.processManifest.doLast {
    //your code
}

with

output.getProcessManifestProvider().get().doLast {
    //your code
}


问:
The total discount per month, year and currency, excluding data from 2017
I need to know the total discount per month, year and currency, excluding data from 2017 for this database:

```<code>Sales table:
PK sale_id : text
FK1 client_id : text
tax_code : text
currency : text
amount : integer
notes : text
created_at : timestamp

Sales_entries table:
PK sale_entry_id : text
FK1 sale_id : text
price : integer
discount : integer
FK2 journey_id : text
</code>```

I have created this query but I don't know if it's correct:

```<code>Select
Datetrunc(‘month’, a.created_at) as month,
Datetrunc(‘year’, a.created_at) as year,
a.Currency as currency,
Sum(b.discount) as discount
From sales as a
Left join sales_entries as b
On a.sales_id = b.sale_id
Where year <> 2017
Group by
Month,
Year,
currency
</code>```

答:
Your date arithmetic is a bit off.  I think this is what you want:

```<code>select year(s.created_at) as yyyy,
       month(s.created_at) as mm,
       s.Currency as currency,
       sum(se.discount) as discount
from sales s left join
     sales_entries se
     on s.sales_id = se.sale_id
where s.created_at < '2017-01-01' or
      s.created_at >= '2018-01-01'
group by year(s.created_at), month(s.created_at),
         s.currency
order by year(s.created_at), month(s.created_at), s.currency;
</code>```

Notice that I also replaced the table aliases with meaningful abbreviations rather than arbitrary letters.

Body:
I need to know the total discount per month, year and currency, excluding data from 2017 for this database:

Sales table:
PK sale_id : text
FK1 client_id : text
tax_code : text
currency : text
amount : integer
notes : text
created_at : timestamp

Sales_entries table:
PK sale_entry_id : text
FK1 sale_id : text
price : integer
discount : integer
FK2 journey_id : text

I have created this query but I don't know if it's correct:

Select
Datetrunc(‘month’, a.created_at) as month,
Datetrunc(‘year’, a.created_at) as year,
a.Currency as currency,
Sum(b.discount) as discount
From sales as a
Left join sales_entries as b
On a.sales_id = b.sale_id
Where year <> 2017
Group by
Month,
Year,
currency

Body:
Your date arithmetic is a bit off.  I think this is what you want:

select year(s.created_at) as yyyy,
       month(s.created_at) as mm,
       s.Currency as currency,
       sum(se.discount) as discount
from sales s left join
     sales_entries se
     on s.sales_id = se.sale_id
where s.created_at < '2017-01-01' or
      s.created_at >= '2018-01-01'
group by year(s.created_at), month(s.created_at),
         s.currency
order by year(s.created_at), month(s.created_at), s.currency;

Notice that I also replaced the table aliases with meaningful abbreviations rather than arbitrary letters.


问:
How to bind a form in SAPUI5?
I was trying to figure out how to bind a simple form in UI5 (not a list) so I can submit to my oData backend . How do I do that with a simple form?

Here is my controller code (if I were to do in a List) - But I have no clue how to deal with a Form:

```<code>var oList = this.byId("addapp"),
                oBinding = oList.getBinding("items"),
                // Create a new entry through the table's list binding
                oContext = oBinding.create({
                    "application_id": 0,
                    "product_name_short": 'Test',
                });
</code>```

This is what I have tried so far, but I got undefined value:

```<code>var x =this.getView().byId("addapp").getBinding("items");
</code>```

答:
If you have set a model to your view, you can bind an existing object to a view using Element.bindElement:

```<code>this.getView().byId("addapp").bindElement("/path/to/your/object");
</code>```

If you want to use a temporary model (to use the data once you click "add" or something similar):

```<code>onInit: function () {
    // Initial values of the form
    this.getView().setModel(new sap.ui.model.json.JSONModel({
        property1: "",
        property2: "",
        property3: ""
    }), "newEntry");

    // Bind the form to the json model
    this.getView().byId("addapp").bindElement("newEntry>/");
},

onAddButtonClick: function() {
    // Get the form values
    var newEntry = this.getView().getModel("newEntry").getData();

    // Use the OData model to create a new entity
    var oDataModel = ...;
    oDataModel.create("/path/to/your/entityset", newEntry, {
        success: function() {
            // entity was created
        }
    });
}
</code>```

Title: How to bind a form in SAPUI5?

Body:
I was trying to figure out how to bind a simple form in UI5 (not a list) so I can submit to my oData backend . How do I do that with a simple form?

Here is my controller code (if I were to do in a List) - But I have no clue how to deal with a Form:

var oList = this.byId("addapp"),
                oBinding = oList.getBinding("items"),
                // Create a new entry through the table's list binding
                oContext = oBinding.create({
                    "application_id": 0,
                    "product_name_short": 'Test',
                });

This is what I have tried so far, but I got undefined value:

var x =this.getView().byId("addapp").getBinding("items");

Body:
If you have set a model to your view, you can bind an existing object to a view using Element.bindElement:

this.getView().byId("addapp").bindElement("/path/to/your/object");

If you want to use a temporary model (to use the data once you click "add" or something similar):

onInit: function () {
    // Initial values of the form
    this.getView().setModel(new sap.ui.model.json.JSONModel({
        property1: "",
        property2: "",
        property3: ""
    }), "newEntry");

    // Bind the form to the json model
    this.getView().byId("addapp").bindElement("newEntry>/");
},

onAddButtonClick: function() {
    // Get the form values
    var newEntry = this.getView().getModel("newEntry").getData();

    // Use the OData model to create a new entity
    var oDataModel = ...;
    oDataModel.create("/path/to/your/entityset", newEntry, {
        success: function() {
            // entity was created
        }
    });
}


问:
Node Sass does not yet support your current environment: Linux 64-bit with false
Getting this error on Arch Linux with node-sass. I'm using it with gulp-sass.

```<code>Node Sass does not yet support your current environment: Linux 64-bit with false
</code>```

Versions

```<code>$ gulp -v
[19:43:15] CLI version 3.9.1
[19:43:15] Local version 3.9.1

$ npm -v
3.9.0
</code>```

Node

```<code>$ node -v
v6.2.0
</code>```

Even using this command npm rebuild node-sass is not changing anything.

答:
Go the path where node-sass is present and run this command </p>

```<code>npm rebuild node-sass --force
</code>```

<p>This solved my issue </p>

ContentLicense: CC BY-SA 3.0

Body:
Getting this error on Arch Linux with node-sass. I'm using it with gulp-sass.

Node Sass does not yet support your current environment: Linux 64-bit with false

Versions

$ gulp -v
[19:43:15] CLI version 3.9.1
[19:43:15] Local version 3.9.1

$ npm -v
3.9.0

Node

$ node -v
v6.2.0

Even using this command npm rebuild node-sass is not changing anything.

Body:
Go the path where node-sass is present and run this command

npm rebuild node-sass --force

This solved my issue


问:
Java hashCode doubt
I have this program:

```<code>import java.util.*;
public class test {
    private String s;
    public test(String s) { this.s = s; }
    public static void main(String[] args) {
        HashSet<Object> hs = new HashSet<Object>();
        test ws1 = new test("foo");
        test ws2 = new test("foo");
        String s1 = new String("foo");
        String s2 = new String("foo");
        hs.add(ws1);
        hs.add(ws2);
        hs.add(s1);
        hs.add(s2); // removing this line also gives same output.
        System.out.println(hs.size());
    }
}
</code>```

Note that this is not a homework. We were asked this question on our quiz earlier today. I know the answers but trying to understand why it is so.

The above program gives 3 as output.

Can anyone please explain why that is?

I think (not sure):

The java.lang.String class overrides the hashCode method from java.lang.Object. So the String objects with value "foo" will be treated as duplicates. The test class does not override the hashCode method and ends up using the java.lang.Object version and this version always returns a different hashcode for every object, so the two test objects being added are treated as different.

答:
Below are few (well quite many) bullets refarding the equals and hashcode from my preparations to SCJP.
Hope it helps:

equals(), hashCode(), and toString() are public.

Override toString() so that System.out.println() or other methods can see something useful, like your object's state.

Use == to determine if two reference variables refer to the same object.

Use equals() to determine if two objects are meaningfully equivalent.

If you don't override equals(), your objects won't be useful hashing keys.

If you don't override equals(), different objects can't be considered equal.

Strings and wrappers override equals() and make good hashing keys.

When overriding equals(), use the instanceof operator to be sure you're evaluating an appropriate class.

When overriding equals(), compare the objects' significant attributes.

Highlights of the equals() contract:

      a. Reflexive: x.equals(x) is true.

   b. Symmetric: If x.equals(y) is true, then y.equals(x) must be true.

   c.  Transitive: If x.equals(y) is true, and y.equals(z) is true, then z.equals(x) is true.

   d. Consistent: Multiple calls to x.equals(y) will return the same result.

    e. Null: If x is not null, then x.equals(null) is false.

   f. If x.equals(y) is true, then x.hashCode() == y.hashCode() is true.

If you override equals(), override hashCode().

HashMap, HashSet, Hashtable, LinkedHashMap, & LinkedHashSet use hashing.

An appropriate hashCode() override sticks to the hashCode() contract.

An efficient hashCode() override distributes keys evenly across its buckets.

An overridden equals() must be at least as precise as its hashCode() mate.

To reiterate: if two objects are equal, their hashcodes must be equal.

It's legal for a hashCode() method to return the same value for all instances (although in practice it's very inefficient).

In addition if you implement equals and hashcode the transient fields (if any) must be treated properly.

The Commons have nice implementation for EqualsBuilder and HashcodeBuilder. They are available in Coomons Lang
http://commons.apache.org/lang/

I use them whenevr I need to implement the equals and the hashcode.

Title: Java hashCode doubt

Body:
I have this program:

import java.util.*;
public class test {
    private String s;
    public test(String s) { this.s = s; }
    public static void main(String[] args) {
        HashSet<Object> hs = new HashSet<Object>();
        test ws1 = new test("foo");
        test ws2 = new test("foo");
        String s1 = new String("foo");
        String s2 = new String("foo");
        hs.add(ws1);
        hs.add(ws2);
        hs.add(s1);
        hs.add(s2); // removing this line also gives same output.
        System.out.println(hs.size());
    }
}

Note that this is not a homework. We were asked this question on our quiz earlier today. I know the answers but trying to understand why it is so.

The above program gives 3 as output.

Can anyone please explain why that is?

I think (not sure):

The java.lang.String class overrides the hashCode method from java.lang.Object. So the String objects with value "foo" will be treated as duplicates. The test class does not override the hashCode method and ends up using the java.lang.Object version and this version always returns a different hashcode for every object, so the two test objects being added are treated as different.


问:
Reload View with new model using AJAX call
I'm having problem with reloading View using AJAX call.

There is a controller called Syzyf and two Index actions (one without parameters and one with string parameter).

In Index view, there are checkboxes from which I create action parameter.
The action is called by button which calls function below.

The problem is that I can't get View reloaded. When I've debugged script in console I got code 200 response with new model.
How to refresh Index view with script below ?

```<code>$('#refreshTasks').click(function () {

    var checkboxesChecked = $('#checkBoxes input:checked');

    var priorities = [];

    checkboxesChecked.each(function () {
        var input = $(this);
        var id = input.attr('id');
        priorities.push(id);
    });

    var filter = JSON.stringify(priorities);

    $.ajax({
        type: "POST",
        url: "/Syzyf/Index",
        data: { filters: filter },
        success: function (result) {
        }
    });
});
</code>```

And finally actions:

```<code>public ActionResult Index()
    {
        if (CheckIfSyzyfConfigured(CustomMethods.GetUserId(User.Identity.Name)))
        {
            using (var ctx = new SyzyfContext())
            {
                ctx.Database.Connection.Open();
                using (var cmd = ctx.Database.Connection.CreateCommand())
                {
                    cmd.CommandText = "GetListTaskWeb";
                    cmd.CommandType = CommandType.StoredProcedure;
                    var param = cmd.CreateParameter();
                    param.ParameterName = "userId";
                    param.Value = CustomMethods.GetUserId(User.Identity.Name);
                    cmd.Parameters.Add(param);

                    using (var reader = cmd.ExecuteReader())
                    {
                        var model = Read(reader).ToList();
                        ctx.Database.Connection.Close();
                        return View(model);
                    }
                }
            }
        }
        else
        {
            return View("NotConfigured");
        }
    }

    [HttpPost]
    public ActionResult Index(string filters)
    {
        if (CheckIfSyzyfConfigured(CustomMethods.GetUserId(User.Identity.Name)))
        {
            using (var ctx = new SyzyfContext())
            {
                ctx.Database.Connection.Open();
                using (var cmd = ctx.Database.Connection.CreateCommand())
                {

                    cmd.CommandText = "GetListTaskWeb";
                    cmd.CommandType = CommandType.StoredProcedure;
                    var param = cmd.CreateParameter();
                    param.ParameterName = "userId";
                    param.Value = CustomMethods.GetUserId(User.Identity.Name);
                    cmd.Parameters.Add(param);

                    if (filters != null)
                    {

                        var test = JsonConvert.DeserializeObject<List<string>>(filters);
                        var priorsXml = test.Select(p => new XElement("prior", p));
                        var mainXml = new XElement("Priorities", priorsXml);
                        var xmlString = mainXml.ToString();

                        var param2 = cmd.CreateParameter();
                        param2.ParameterName = "statusFilter";
                        param2.Value = xmlString;
                    }

                    using (var reader = cmd.ExecuteReader())
                    {
                        var model = Read(reader).ToList();
                        ctx.Database.Connection.Close();
                        var json = JsonConvert.SerializeObject(model);
                        return View(model);
                    }
                }
            }
        }
        else
        {
            return View("NotConfigured");
        }
    }
</code>```

答:
You need to replace your view based on HTML Element.

```<code>var filter = JSON.stringify(priorities);

    $.ajax({
        type: "POST",
        url: "/Syzyf/Index",
        data: { filters: filter },
        success: function (result) {
             $('[HTML_element]').empty().html(result);
        }
    });
</code>```

Note: Return only html what you want to refresh (Not entire page/partial view) or get specific content from result returned by controller.

Update: It is always a good practice to return PartialView from controller in this type of scenario.

Body:
I'm having problem with reloading View using AJAX call.

There is a controller called Syzyf and two Index actions (one without parameters and one with string parameter).

In Index view, there are checkboxes from which I create action parameter.
The action is called by button which calls function below.

The problem is that I can't get View reloaded. When I've debugged script in console I got code 200 response with new model.
How to refresh Index view with script below ?

$('#refreshTasks').click(function () {

    var checkboxesChecked = $('#checkBoxes input:checked');

    var priorities = [];

    checkboxesChecked.each(function () {
        var input = $(this);
        var id = input.attr('id');
        priorities.push(id);
    });

    var filter = JSON.stringify(priorities);

    $.ajax({
        type: "POST",
        url: "/Syzyf/Index",
        data: { filters: filter },
        success: function (result) {
        }
    });
});

And finally actions:

public ActionResult Index()
    {
        if (CheckIfSyzyfConfigured(CustomMethods.GetUserId(User.Identity.Name)))
        {
            using (var ctx = new SyzyfContext())
            {
                ctx.Database.Connection.Open();
                using (var cmd = ctx.Database.Connection.CreateCommand())
                {
                    cmd.CommandText = "GetListTaskWeb";
                    cmd.CommandType = CommandType.StoredProcedure;
                    var param = cmd.CreateParameter();
                    param.ParameterName = "userId";
                    param.Value = CustomMethods.GetUserId(User.Identity.Name);
                    cmd.Parameters.Add(param);

                    using (var reader = cmd.ExecuteReader())
                    {
                        var model = Read(reader).ToList();
                        ctx.Database.Connection.Close();
                        return View(model);
                    }
                }
            }
        }
        else
        {
            return View("NotConfigured");
        }
    }

    [HttpPost]
    public ActionResult Index(string filters)
    {
        if (CheckIfSyzyfConfigured(CustomMethods.GetUserId(User.Identity.Name)))
        {
            using (var ctx = new SyzyfContext())
            {
                ctx.Database.Connection.Open();
                using (var cmd = ctx.Database.Connection.CreateCommand())
                {

                    cmd.CommandText = "GetListTaskWeb";
                    cmd.CommandType = CommandType.StoredProcedure;
                    var param = cmd.CreateParameter();
                    param.ParameterName = "userId";
                    param.Value = CustomMethods.GetUserId(User.Identity.Name);
                    cmd.Parameters.Add(param);

                    if (filters != null)
                    {

                        var test = JsonConvert.DeserializeObject<List<string>>(filters);
                        var priorsXml = test.Select(p => new XElement("prior", p));
                        var mainXml = new XElement("Priorities", priorsXml);
                        var xmlString = mainXml.ToString();

                        var param2 = cmd.CreateParameter();
                        param2.ParameterName = "statusFilter";
                        param2.Value = xmlString;
                    }

                    using (var reader = cmd.ExecuteReader())
                    {
                        var model = Read(reader).ToList();
                        ctx.Database.Connection.Close();
                        var json = JsonConvert.SerializeObject(model);
                        return View(model);
                    }
                }
            }
        }
        else
        {
            return View("NotConfigured");
        }
    }

Body:
You need to replace your view based on HTML Element.

var filter = JSON.stringify(priorities);

    $.ajax({
        type: "POST",
        url: "/Syzyf/Index",
        data: { filters: filter },
        success: function (result) {
             $('[HTML_element]').empty().html(result);
        }
    });

Note: Return only html what you want to refresh (Not entire page/partial view) or get specific content from result returned by controller.

Update: It is always a good practice to return PartialView from controller in this type of scenario.


问:
Custom allocators as alternatives to vector of smart pointers?
This question is about owning pointers, consuming pointers, smart pointers, vectors, and allocators.

I am a little bit lost on my thoughts about code architecture. Furthermore, if this  question has already an answer somewhere, 1. sorry, but I haven't found a satisfying answer so far and 2. please point me to it.

My problem is the following:

I have several "things" stored in a vector and several "consumers" of those "things". So, my first try was like follows:

```<code>std::vector<thing> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return &i_am_the_owner_of_things[5]; // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};
</code>```

In my application, this would be safe because the "things" outlive the "consumers" in any case. However, more "things" can be added during runtime and that can become a problem because if the std::vector<thing> i_am_the_owner_of_things; gets reallocated, all the thing* m_thing pointers become invalid.

A fix to this scenario would be to store unique pointers to "things" instead of "things" directly, i.e. like follows:

```<code>std::vector<std::unique_ptr<thing>> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return i_am_the_owner_of_things[5].get(); // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};
</code>```

The downside here is that memory coherency between "things" is lost. Can this memory coherency be re-established by using custom allocators somehow? I am thinking of something like an allocator which would always allocate memory for, e.g., 10 elements at a time and whenever required, adds more 10-elements-sized chunks of memory.

Example:

initially:

v = ☐☐☐☐☐☐☐☐☐☐

more elements:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

and again:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

Using such an allocator, I wouldn't even have to use std::unique_ptrs of "things" because at std::vector's reallocation time, the memory addresses of the already existing elements would not change.

As alternative, I can only think of referencing the "thing" in "consumer" via a std::shared_ptr<thing> m_thing, as opposed to the current thing* m_thing but that seems like the worst approach to me, because a "thing" shall not own a "consumer" and with shared pointers I would create shared ownership.

So, is the allocator-approach a good one? And if so, how can it be done? Do I have to implement the allocator by myself or is there an existing one?

答:
If you are able to treat thing as a value type, do so. It simplifies things, you don't need a smart pointer for circumventing the pointer/reference invalidation issue. The latter can be tackled differently:

If new thing instances are inserted via push_front and push_back during the program, use std::deque instead of std::vector. Then, no pointers or references to elements in this container are invalidated (iterators are invalidated, though - thanks to @odyss-jii for pointing that out). If you fear that you heavily rely on the performance benefit of the completely contiguous memory layout of std::vector: create a benchmark and profile.

If new thing instances are inserted in the middle of the container during the program, consider using std::list. No pointers/iterators/references are invalidated when inserting or removing container elements. Iteration over a std::list is much slower than a std::vector, but make sure this is an actual issue in your scenario before worrying too much about that.

Body:
This question is about owning pointers, consuming pointers, smart pointers, vectors, and allocators.

I am a little bit lost on my thoughts about code architecture. Furthermore, if this  question has already an answer somewhere, 1. sorry, but I haven't found a satisfying answer so far and 2. please point me to it.

My problem is the following:

I have several "things" stored in a vector and several "consumers" of those "things". So, my first try was like follows:

std::vector<thing> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return &i_am_the_owner_of_things[5]; // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};

In my application, this would be safe because the "things" outlive the "consumers" in any case. However, more "things" can be added during runtime and that can become a problem because if the std::vector<thing> i_am_the_owner_of_things; gets reallocated, all the thing* m_thing pointers become invalid.

A fix to this scenario would be to store unique pointers to "things" instead of "things" directly, i.e. like follows:

std::vector<std::unique_ptr<thing>> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return i_am_the_owner_of_things[5].get(); // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};

The downside here is that memory coherency between "things" is lost. Can this memory coherency be re-established by using custom allocators somehow? I am thinking of something like an allocator which would always allocate memory for, e.g., 10 elements at a time and whenever required, adds more 10-elements-sized chunks of memory.

Example:

initially:

v = ☐☐☐☐☐☐☐☐☐☐

more elements:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

and again:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

Using such an allocator, I wouldn't even have to use std::unique_ptrs of "things" because at std::vector's reallocation time, the memory addresses of the already existing elements would not change.

As alternative, I can only think of referencing the "thing" in "consumer" via a std::shared_ptr<thing> m_thing, as opposed to the current thing* m_thing but that seems like the worst approach to me, because a "thing" shall not own a "consumer" and with shared pointers I would create shared ownership.

So, is the allocator-approach a good one? And if so, how can it be done? Do I have to implement the allocator by myself or is there an existing one?


问:
Order by several columns
I want to regularly update the rows in a database but also want more popular rows (rows that are requested more) to be updated more often. I thought I could base this on two parameters: popularity and time since the last update.

```<code>id | title | popularity | last_updated
---+-------+------------+-------------
1  | A     | 148        | 20190501
2  | B     | 3874       | 20190201
3  | C     | 29         | 20190104
4  | D     | 242        | 20190314
5  | E     | 398        | 20190325
6  | F     | 3          | 20190128
</code>```

The last_updated column is formated as YYYYMMDD.

I first thought I could simply use ORDER BY:

SELECT * FROM results ORDER BY last_updated, popularity;
```

However, this query will only care about the last_updated column if the value of two or more rows' popularity is the same.

Would it be possible to e.g. turn popularity and last_updated into another value that can be used for this kind of sorting?

答:
Difficulty will be to define the level of importance between the popularity and last update.

How is the popularity value calculated ? Will it ever decrease ? Most subjects are popular for while (hipes) and become quick old news. To know the current popularity of a record, I suggest to keep an extra column popularityOnUpdate which holds the popularity value at the moment of the last update. When the popularity decreases the increment of the popularity value will fade out and so the difference between the popularityOnUpdate value and the popularity value.

The query can become:

```<code>order by POP_WEIGHT*(popularity - popularityOnUpdate)
       + UPD_WEIGHT*(current date - lastUpdate) DESCENDING
</code>```

POP_WEIGHT and UPD_WEIGHT are constants you have to define which express the importance of the 2 criteria (popularity and last update). Once the popularity slows down, the last update value will push the record up in the ranking.

Title: Order by several columns

Body:
I want to regularly update the rows in a database but also want more popular rows (rows that are requested more) to be updated more often. I thought I could base this on two parameters: popularity and time since the last update.

id | title | popularity | last_updated
---+-------+------------+-------------
1  | A     | 148        | 20190501
2  | B     | 3874       | 20190201
3  | C     | 29         | 20190104
4  | D     | 242        | 20190314
5  | E     | 398        | 20190325
6  | F     | 3          | 20190128

The last_updated column is formated as YYYYMMDD.

I first thought I could simply use ORDER BY:

SELECT * FROM results ORDER BY last_updated, popularity;

However, this query will only care about the last_updated column if the value of two or more rows' popularity is the same.

Would it be possible to e.g. turn popularity and last_updated into another value that can be used for this kind of sorting?

Body:
Difficulty will be to define the level of importance between the popularity and last update.

How is the popularity value calculated ? Will it ever decrease ? Most subjects are popular for while (hipes) and become quick old news. To know the current popularity of a record, I suggest to keep an extra column popularityOnUpdate which holds the popularity value at the moment of the last update. When the popularity decreases the increment of the popularity value will fade out and so the difference between the popularityOnUpdate value and the popularity value.

The query can become:

order by POP_WEIGHT*(popularity - popularityOnUpdate)
       + UPD_WEIGHT*(current date - lastUpdate) DESCENDING

POP_WEIGHT and UPD_WEIGHT are constants you have to define which express the importance of the 2 criteria (popularity and last update). Once the popularity slows down, the last update value will push the record up in the ranking.


问:
What's the value of variable when setTimeout assigned to it?
I am trying to know what is the value of the variable when setTimeout get called and assigned to it. Unexpected value get logged, so being curious how this happening.

I tried to look some related question on stack and also look out on web but didn't get the exact answer.

Update - I am seeking help to understand how the unique id which assigne d to variable get calculated ?

let a = setTimeout( () => {
  console.log('something will happen')
}, 2000)

let b = setTimeout( () => {
  console.log('something will happen')
}, 3000)

let c = setTimeout( () => {
  console.log('something will happen')
}, 4000)

console.log(a, b, c)```

答:
When you call setTimeout or setInterval the uniq id of particular timer is returned.

Usually it is just a number, incremented with every new timer and it is guaranteed that this number will never be reused.

You can use it only for cancelling timeouts or intervals with corresponding function clearInterval or clearTimeout.

More about returned value here.


问:
Is it possible to create a button using nothing but CSS that changes the appearance of a page?
I'm using a website that allows members to alter the appearance of their own page with CSS. No HTML permitted, only CSS. I've deliberately made my page as bright and clashing and "graphic design is my passion" as possible. This is not a serious site and I'm not taking it seriously.

However, I would like to implement a button that removes the most visually offensive elements of the design and makes it possible to actually read my page, should anyone want to.

I'm fairly confident this isn't possible with only CSS, but I thought I'd ask just to be certain.

答:
This is an extension of my comment to the OP's question:

.content{
  width: 500px;
  background: #e1e1e1;
  margin-top: 30px;
}
.remove-el{
  width: 30px;
  height: 30px;
  background: red;
}
input[type="checkbox"]{
  -webkit-appearance: none;
}
input[type="checkbox"] ~ label{
  background: teal;
  color: #fff;
  padding: 5px;
}
input[type="checkbox"]:checked ~ label{
  background: #e1e1e1;
  color: #aaa;
}
input[type="checkbox"]:checked ~ .content .remove-el{
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="more-readable">
<label for="more-readable">Make it more readable</label>

<div class="content">
  <div class="remove-el"></div>
  <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Sunt nostrum quasi labore, neque incidunt enim soluta velit in possimus, amet cupiditate optio sequi ipsum natus aperiam quibusdam eos molestiae. Excepturi.</p>
  <p>Rerum consequuntur provident, vel tempora dolore deleniti impedit quia ab exercitationem laboriosam quaerat perspiciatis doloremque accusamus, nesciunt sed veniam libero soluta quasi recusandae unde nostrum sapiente nam. Culpa, fugiat omnis!</p>
    <div class="remove-el"></div>
  <p>Quibusdam, voluptatibus ipsa reprehenderit reiciendis suscipit maxime vero praesentium nobis ex perspiciatis quo laudantium? Alias aliquam voluptatum, exercitationem ea modi corrupti aspernatur a. Illo sint distinctio quos quod quas quasi!</p>
  <p>Autem praesentium inventore soluta atque ut, consectetur minima itaque perspiciatis sint nobis assumenda eum vitae culpa nemo fugiat facere in sapiente eaque a voluptatibus aut recusandae commodi ipsam? Iste, quae.</p>
    <div class="remove-el"></div>
  <p>Unde sequi nihil, molestias laudantium ex dolorem corporis dolore at minima perferendis consequuntur, nisi repellendus quibusdam sit reiciendis fugit officiis optio dicta veniam asperiores ab enim. Dolorem commodi illum saepe!</p>
  <p>Eos labore quo, deserunt nobis hic molestias excepturi accusantium quidem aperiam quisquam sapiente delectus. Nulla enim delectus illum, sunt cupiditate et incidunt ducimus alias eligendi labore iste! Iste, sapiente ad.</p>
    <div class="remove-el"></div>
  <p>Sint, nisi sunt. Neque, libero est rerum adipisci cum commodi aliquid architecto eveniet natus culpa eligendi earum ratione? Excepturi sed hic impedit esse inventore fugit? Ut minus quia odio quis!</p>
  <p>Corrupti nesciunt dolor amet sunt autem dicta minima expedita ducimus illum! Mollitia molestiae nihil veniam cupiditate! Veritatis explicabo voluptatem soluta, nemo libero illum. A magni molestiae provident possimus laudantium dolorum.</p>
    <div class="remove-el"></div>
    <div class="remove-el"></div>
  <p>Itaque numquam, provident molestias odit eum deleniti ab temporibus iure earum non pariatur a aliquid minus? Eius adipisci quis delectus praesentium ab minus quaerat debitis inventore quo! Hic, facilis vel.</p>
    <div class="remove-el"></div>
  <p>Atque esse pariatur porro non quo minus nesciunt cumque perspiciatis vel ad deserunt culpa eius facere aut adipisci, fuga, mollitia nam enim dolore veritatis vitae, dolorem obcaecati? Eos, quidem in.</p>
</div></code>```

Body:
This is an extension of my comment to the OP's question:

.content{
  width: 500px;
  background: #e1e1e1;
  margin-top: 30px;
}
.remove-el{
  width: 30px;
  height: 30px;
  background: red;
}
input[type="checkbox"]{
  -webkit-appearance: none;
}
input[type="checkbox"] ~ label{
  background: teal;
  color: #fff;
  padding: 5px;
}
input[type="checkbox"]:checked ~ label{
  background: #e1e1e1;
  color: #aaa;
}
input[type="checkbox"]:checked ~ .content .remove-el{
  display: none;
}

<input type="checkbox" id="more-readable">
<label for="more-readable">Make it more readable</label>

<div class="content">
  <div class="remove-el"></div>
  <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Sunt nostrum quasi labore, neque incidunt enim soluta velit in possimus, amet cupiditate optio sequi ipsum natus aperiam quibusdam eos molestiae. Excepturi.</p>
  <p>Rerum consequuntur provident, vel tempora dolore deleniti impedit quia ab exercitationem laboriosam quaerat perspiciatis doloremque accusamus, nesciunt sed veniam libero soluta quasi recusandae unde nostrum sapiente nam. Culpa, fugiat omnis!</p>
    <div class="remove-el"></div>
  <p>Quibusdam, voluptatibus ipsa reprehenderit reiciendis suscipit maxime vero praesentium nobis ex perspiciatis quo laudantium? Alias aliquam voluptatum, exercitationem ea modi corrupti aspernatur a. Illo sint distinctio quos quod quas quasi!</p>
  <p>Autem praesentium inventore soluta atque ut, consectetur minima itaque perspiciatis sint nobis assumenda eum vitae culpa nemo fugiat facere in sapiente eaque a voluptatibus aut recusandae commodi ipsam? Iste, quae.</p>
    <div class="remove-el"></div>
  <p>Unde sequi nihil, molestias laudantium ex dolorem corporis dolore at minima perferendis consequuntur, nisi repellendus quibusdam sit reiciendis fugit officiis optio dicta veniam asperiores ab enim. Dolorem commodi illum saepe!</p>
  <p>Eos labore quo, deserunt nobis hic molestias excepturi accusantium quidem aperiam quisquam sapiente delectus. Nulla enim delectus illum, sunt cupiditate et incidunt ducimus alias eligendi labore iste! Iste, sapiente ad.</p>
    <div class="remove-el"></div>
  <p>Sint, nisi sunt. Neque, libero est rerum adipisci cum commodi aliquid architecto eveniet natus culpa eligendi earum ratione? Excepturi sed hic impedit esse inventore fugit? Ut minus quia odio quis!</p>
  <p>Corrupti nesciunt dolor amet sunt autem dicta minima expedita ducimus illum! Mollitia molestiae nihil veniam cupiditate! Veritatis explicabo voluptatem soluta, nemo libero illum. A magni molestiae provident possimus laudantium dolorum.</p>
    <div class="remove-el"></div>
    <div class="remove-el"></div>
  <p>Itaque numquam, provident molestias odit eum deleniti ab temporibus iure earum non pariatur a aliquid minus? Eius adipisci quis delectus praesentium ab minus quaerat debitis inventore quo! Hic, facilis vel.</p>
    <div class="remove-el"></div>
  <p>Atque esse pariatur porro non quo minus nesciunt cumque perspiciatis vel ad deserunt culpa eius facere aut adipisci, fuga, mollitia nam enim dolore veritatis vitae, dolorem obcaecati? Eos, quidem in.</p>
</div>


问:
How to get form data into angular controller and how to pass it to serlvet?
I have a form which contains two <select> tags.
One is a list of the year the other is a list of dosages.

When I select the options am able to get the selectedYear in my controller using ng-model but am not able to get selectedDosage.
And when am trying to send this data to my servlet it is returning null as a value.

Any suggestions I appreciate
JSON

```<code>Dosages:[
    {"name":"Tablet"},
    {"name":"Syrups and Suspension"},
    {"name":"Non-Antibiotic Capsules"},
    {"name":"Antibiotic Capsules"},
    {"name":"Dry Powder for Suspension"},
    {"name":"ORS"},
    {"name":"Antiseptics"}
]
Years:{"json1":"[
    {\"years\":2018},
    {\"years\":2017},
    {\"years\":2016},
    {\"years\":2015}]"
</code>```

HTML

```<code><form  ng-submit="Display()">

    <select class="form-control" ng-model="selectedYear">
        <option value="" selected disabled>Select Year</option>
        <option   ng-repeat="option in years" ng-value="{{option.years}}" >
          {{option.years}}
        </option>
    </select>
    <br>
    <select class="form-control" ng-model="selectedDo">
        <option value="" selected disabled>Select Dosage</option>
        <option  ng-repeat="option in section" ng-value="{{option.name}}"  >
          {{option.name}}
        </option>
    </select>

    <input type="submit" value="Submit"/>
</form>
</code>```

Controller

```<code>$scope.selectedDo;
$scope.selectedYear;
$scope.Display=function(){

    $window.alert($scope.selectedDo+"..."+ $scope.selectedYear);
    $http({
        method:"post",
        url:"/com.az.BusinessRatioAnalysis/SectionServlet",
        data:{
           year:$scope.selectedYear,
           dosage:$scope.selectedDo,
        }
    }).then(function(result){
        $window.alert("Ajex call failed" + result);
    });
};

</code>```

Servlet

```<code>public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String year=request.getParameter("year");
        String dosage=request.getParameter("dosage");
                System.out.println(year+".."+dosage);
    }

</code>```

答:
Please try the below.

Payload Bean class:

```<code>class Bean {
    Year year;
    Dosage dosage;
    //getters and setters
}
</code>```

Servlet Class:

```<code>public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    StringBuilder json = new StringBuilder();
    String str;
    while ((str = request.getReader().readLine()) != null) {
        json.append(str);
    }

    // Using Jackson
    ObjectMapper objectMapper = new ObjectMapper();
    Bean bean = objectMapper.readValue(json.toString(), Bean.class);

    System.out.println("Year ::" + bean.getYear());
    System.out.println("Dosage ::" + bean.getDosage());
}
</code>```

pom.xml file in case of a maven project, else add jars accordingly:

```<code><dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
</code>```

PS: Ignored Exception Handling in above code

Body:
I have a form which contains two <select> tags.
One is a list of the year the other is a list of dosages.

When I select the options am able to get the selectedYear in my controller using ng-model but am not able to get selectedDosage.
And when am trying to send this data to my servlet it is returning null as a value.

Any suggestions I appreciate
JSON

Dosages:[
    {"name":"Tablet"},
    {"name":"Syrups and Suspension"},
    {"name":"Non-Antibiotic Capsules"},
    {"name":"Antibiotic Capsules"},
    {"name":"Dry Powder for Suspension"},
    {"name":"ORS"},
    {"name":"Antiseptics"}
]
Years:{"json1":"[
    {\"years\":2018},
    {\"years\":2017},
    {\"years\":2016},
    {\"years\":2015}]"

HTML

<form  ng-submit="Display()">

    <select class="form-control" ng-model="selectedYear">
        <option value="" selected disabled>Select Year</option>
        <option   ng-repeat="option in years" ng-value="{{option.years}}" >
          {{option.years}}
        </option>
    </select>

    <select class="form-control" ng-model="selectedDo">
        <option value="" selected disabled>Select Dosage</option>
        <option  ng-repeat="option in section" ng-value="{{option.name}}"  >
          {{option.name}}
        </option>
    </select>

    <input type="submit" value="Submit"/>
</form>

Controller

$scope.selectedDo;
$scope.selectedYear;
$scope.Display=function(){

    $window.alert($scope.selectedDo+"..."+ $scope.selectedYear);
    $http({
        method:"post",
        url:"/com.az.BusinessRatioAnalysis/SectionServlet",
        data:{
           year:$scope.selectedYear,
           dosage:$scope.selectedDo,
        }
    }).then(function(result){
        $window.alert("Ajex call failed" + result);
    });
};

Servlet

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String year=request.getParameter("year");
        String dosage=request.getParameter("dosage");
                System.out.println(year+".."+dosage);
    }

Body:
Please try the below.

Payload Bean class:

class Bean {
    Year year;
    Dosage dosage;
    //getters and setters
}

Servlet Class:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    StringBuilder json = new StringBuilder();
    String str;
    while ((str = request.getReader().readLine()) != null) {
        json.append(str);
    }

    // Using Jackson
    ObjectMapper objectMapper = new ObjectMapper();
    Bean bean = objectMapper.readValue(json.toString(), Bean.class);

    System.out.println("Year ::" + bean.getYear());
    System.out.println("Dosage ::" + bean.getDosage());
}

pom.xml file in case of a maven project, else add jars accordingly:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

PS: Ignored Exception Handling in above code


问:
Is it possible to specify your own distance function using scikit-learn K-Means Clustering?
Is it possible to specify your own distance function using scikit-learn K-Means Clustering?</p>

答: Sklearn Kmeans uses the Euclidean distance. It has no metric parameter. This said, if you're clustering time series, you can use the tslearn python package, when you can specify a metric (dtw, softdtw, euclidean).


问:
How to transform a String into a Type / Component in Angular?
In Angular, i get a String and want to transform it to a Type / Component. For example, i get "ListComponent" and want to add a ListComponent to the Application.
I dont want to map these in an Map or something. Is it possible to get the Type out of a String?

stringComponent = "ListComponent";
typeComponent = *transform "ListComponent" to ListComponent;
method(typeComponent);
```

答:
Maybe something like:</p>

```<code>class ListComponent {
  foo = 'bar'
}
class LolComponent {}

const componentsMap = {
  ListComponent,
  LolComponent
}

type ComponentName = keyof typeof componentsMap;

function convertStringToComponent<Name extends ComponentName>(name: Name): (typeof componentsMap)[Name] {
  return componentsMap[name];
}

const CompByName = convertStringToComponent('ListComponent');

const instance = new CompByName();

instance.foo; // ok!
</code>```

Body:
Maybe something like:

class ListComponent {
  foo = 'bar'
}
class LolComponent {}

const componentsMap = {
  ListComponent,
  LolComponent
}

type ComponentName = keyof typeof componentsMap;

function convertStringToComponent<Name extends ComponentName>(name: Name): (typeof componentsMap)[Name] {
  return componentsMap[name];
}

const CompByName = convertStringToComponent('ListComponent');

const instance = new CompByName();

instance.foo; // ok!


问:
Renew kubernetes pki after expired
My kubernetes PKI expired (API server to be exact) and I can't find a way to renew it. The error I get is

```<code>May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922595    8751 server.go:417] Version: v1.14.2
May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922784    8751 plugins.go:103] No cloud provider specified.
May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922800    8751 server.go:754] Client rotation is on, will bootstrap in background
May 27 08:43:51 node1 kubelet[8751]: E0527 08:43:51.925859    8751 bootstrap.go:264] Part of the existing bootstrap client certificate is expired: 2019-05-24 13:24:42 +0000 UTC
May 27 08:43:51 node1 kubelet[8751]: F0527 08:43:51.925894    8751 server.go:265] failed to run Kubelet: unable to load bootstrap
kubeconfig: stat /etc/kubernetes/bootstrap-kubelet.conf: no such file or directory
</code>```

The documentation on https://kubernetes.io/docs/tasks/administer-cluster/kubeadm/kubeadm-certs/ describes how to renew but it only works if the API server is not expired. I have tried to do a

```<code>kubeadm alpha cert renew all
</code>```

and do a reboot but that just made the entire cluster fail so I did a rollback to a snapshot (my cluster is running on VMware).

The cluster is running and all containers seem to work but I can't access it via kubectl so I can't really deploy or query.

My kubernetes version is 1.14.2.

答:
Try to do cert renewal via kubeadm init phase certs command.

You can check certs expiration via the following command:

openssl x509 -in /etc/kubernetes/pki/apiserver.crt -noout -text

openssl x509 -in /etc/kubernetes/pki/apiserver-kubelet-client.crt -noout -text

First, ensure that you have most recent backup of k8s certificates inventory /etc/kubernetes/pki/*.

Delete apiserver.* and apiserver-kubelet-client.* cert files in /etc/kubernetes/pki/ directory.

Spawn a new certificates via kubeadm init phase certs command:

sudo kubeadm init phase certs apiserver

sudo kubeadm init phase certs apiserver-kubelet-client

Restart kubelet and docker daemons:

sudo systemctl restart docker; sudo systemctl restart kubelet

You can find more related information in the official K8s documentation.

Title: Renew kubernetes pki after expired

Body:
My kubernetes PKI expired (API server to be exact) and I can't find a way to renew it. The error I get is

May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922595    8751 server.go:417] Version: v1.14.2
May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922784    8751 plugins.go:103] No cloud provider specified.
May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922800    8751 server.go:754] Client rotation is on, will bootstrap in background
May 27 08:43:51 node1 kubelet[8751]: E0527 08:43:51.925859    8751 bootstrap.go:264] Part of the existing bootstrap client certificate is expired: 2019-05-24 13:24:42 +0000 UTC
May 27 08:43:51 node1 kubelet[8751]: F0527 08:43:51.925894    8751 server.go:265] failed to run Kubelet: unable to load bootstrap
kubeconfig: stat /etc/kubernetes/bootstrap-kubelet.conf: no such file or directory

The documentation on https://kubernetes.io/docs/tasks/administer-cluster/kubeadm/kubeadm-certs/ describes how to renew but it only works if the API server is not expired. I have tried to do a

kubeadm alpha cert renew all

and do a reboot but that just made the entire cluster fail so I did a rollback to a snapshot (my cluster is running on VMware).

The cluster is running and all containers seem to work but I can't access it via kubectl so I can't really deploy or query.

My kubernetes version is 1.14.2.


问:
What should I write in the "Edit" view code?
Im new to MVC and I want to learn how to make the Edit View to work. I've searched a lot in the internet, but there is not much people who use code similar to mine.

This is what I have right now in the Edit property:

```<code>public ActionResult Edit(int Id=0)
    {
        MoviesData movie = db.MoviesData.Find(Id);
        MovieViewModel MovieVM = new MovieViewModel
        {
            MovieID = movie.MovieID,
            MovieName = movie.MovieName,
            MovieDescription = movie.MovieDescription,
            MovieCategory = movie.MovieCategory,
            MovieYear = movie.MovieYear
        };

        return View(MovieVM);
    }
</code>```

'MoviesData' is the table in my database.
'MovieViewModel' contains the properties for the data.
The Edit View is the auto generated view of MVC.

what should i add to this to make it work?

答: copy & paste the code from create view and make the MovieID hidden field also change the redirection code create to edit .</p>

Body:
Im new to MVC and I want to learn how to make the Edit View to work. I've searched a lot in the internet, but there is not much people who use code similar to mine.

This is what I have right now in the Edit property:

public ActionResult Edit(int Id=0)
    {
        MoviesData movie = db.MoviesData.Find(Id);
        MovieViewModel MovieVM = new MovieViewModel
        {
            MovieID = movie.MovieID,
            MovieName = movie.MovieName,
            MovieDescription = movie.MovieDescription,
            MovieCategory = movie.MovieCategory,
            MovieYear = movie.MovieYear
        };

        return View(MovieVM);
    }

'MoviesData' is the table in my database.
'MovieViewModel' contains the properties for the data.
The Edit View is the auto generated view of MVC.

what should i add to this to make it work?


问:
Storing generated files in Git
We have a reasonably large, and far too messy code base that we wish to migrate to using Git. At the moment, it's a big monolithic chunk that can't easily be split into smaller independent components. The code builds a large number of shared libraries, but their source code is so interleaved that it can't be cleanly separated into separate repositories at the moment.

I'm not too concerned with whether Git can cope with having all the code in a single repository, but a problem is that we need to version both the source code and many of the libraries built from it. Building everything from scratch takes hours, so when checking out the code, developers should also get precompiled versions of these libraries to save time.

And this is where I could use some advice. The libraries don't need to be 100% up to date (as they generally maintain binary compatibility, and can always be rebuilt by the individual developer if necessary), so I'm looking for ways to to avoid cluttering up our source code repository with countless marginally different versions of binary files which can be regenerated from the source anyway, while still making the libraries easily accessible to developers so they don't have to rebuild everything from scratch.

So I'd like some way to achieve something like the following.

the libraries are generated by our build server on a regular basis, which could then commit them to the Git repository. The developers should then treat these files as read-only (pull the latest version, and when necessary, rebuild in place, but don't commit new versions), and ideally, Git should enforce this. (In particular, a developer running a quick git commit -a shouldn't end up accidentally polluting the repository with a new revision of all these generated files)

keep these files in a separate repository, so the source code won't have to carry around all these generated binary files perpetually (since they're a convenience to cut down on compilation time, but they're not actually necessary).

Of course, at the same time, the process of using these should be as smooth as possible. When checking out the source, the libraries built from it should follow (or at least, be easy to get). And when committing, it shouldn't be possible to accidentally commit new versions of these libraries, just because they were recompiled and now have a different timestamp embedded.

I've been looking at the option of using git's submodules, creating the "super" repository containing the source code, and then one or more submodules for the generated libraries, but so far, it seems a bit too clumsy and fragile for my taste. It seems that they don't actually prevent the developer from committing changes directly to the submodule, it just causes things to break further down the line (while playing around with submodules, I've ended up with more detached HEADs than I care to count).

Considering virtually all our developers are new to Git, that may end up wasting more time than it saves us.

So what are our options? Does the submodule approach sound sensible to you Git gurus out there? And how do I "tame" it, so it's as easy to use (and hard to mess up) as possible for our developers?

Or is there an entirely different solution we haven't considered?

I should mention that I've only used Git for a couple of days, so I'm pretty much a newbie myself.

答:
The ideal solution is to avoid versioning binaries and store them in an artifact repository like Nexus.

The issue with deliveries in a VCS is that a VCS is design to record and keep the history of all files it manages, whereas:

many versions of a delivery are intermediate builds that will need to be cleaned up at one point or another

cleaning (removing old versions) is quite hard to do in a VCS, very easy to do in an artifact repository.

the size of a repo will become an issue (especially for a DVCS, unless you always get the latest version, in which case a shallow clone might alleviate that issue)

there is no way of comparing a version of a binary with another (so "versioning" don't make a lot of sense)

Title: Storing generated files in Git


问:
How to correctly position a radial gradient background?
I have small problem with css position with this code.

Unfortunately I need this circle to be on the right side of the page (div) and not in the middle. Thanks for the answers

body{
 margin:0;
 padding:0;
 }

 .session-box{
 background:#333;
 width:100%;
 min-height:100vh;
 }

 .circle{
 position: absolute;
  top: 0;
  left 0;
  width: 100%;
  height: 100%;
 background: -moz-radial-gradient(transparent 200px, rgba(255,255,255,0.6) 200px);
  background: -webkit-radial-gradient(transparent 100px , rgba(255,255,255,0.6) 200px ) ;
  background: -ms-radial-gradient(transparent 100px, rgba(255,255,255,0.6) 200px);
  background: -o-radial-gradient(transparent 100px, rgba(255,255,255,0.6) 200px);
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="session-box">
  <div class="circle"></div>
</div></code>```

i need this

答:
Here is another syntax in case you want better support than the at one (Safari doesn't currently support the at syntax for background). The gradient will by default be placed at the center so we increase the size of the background to move the center position to the right.

body {
  margin: 0;
  padding: 0;
}

.session-box {
  background: #333;
  width: 100%;
  min-height: 100vh;
}

.circle {
  position: absolute;
  top: 0;
  left 0;
  width: 100%;
  height: 100%;
  /* Circle with 100px Radius*/
  background-image: radial-gradient(circle 100px, transparent 50%, rgba(255, 255, 255, 0.6) 100%);
  /* Twice bigger than the container minus 2xRadius */
  background-size: calc(200% - 200px) 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="session-box">
  <div class="circle">
  </div>
</div></code>```

You can also do it without calc():

body {
  margin: 0;
  padding: 0;
}

.session-box {
  background: #333;
  width: 100%;
  min-height: 100vh;
}

.circle {
  position: absolute;
  top: 0;
  left 0;
  width: 100%;
  height: 100%;
  padding-right:100px; /*Equal to radius*/
  /* Circle with 100px Radius*/
  background-image: radial-gradient(circle 100px, transparent 50%, rgba(255, 255, 255, 0.6) 100%);
  /* Twice bigger than the container */
  background-size: 200% 100%;
  background-origin:content-box; /* We don't consider the padding when doing the calculation */
  box-sizing:border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="session-box">
  <div class="circle">
  </div>
</div></code>```

Body:
I have small problem with css position with this code.

Unfortunately I need this circle to be on the right side of the page (div) and not in the middle. Thanks for the answers

body{
 margin:0;
 padding:0;
 }

 .session-box{
 background:#333;
 width:100%;
 min-height:100vh;
 }

 .circle{
 position: absolute;
  top: 0;
  left 0;
  width: 100%;
  height: 100%;
 background: -moz-radial-gradient(transparent 200px, rgba(255,255,255,0.6) 200px);
  background: -webkit-radial-gradient(transparent 100px , rgba(255,255,255,0.6) 200px ) ;
  background: -ms-radial-gradient(transparent 100px, rgba(255,255,255,0.6) 200px);
  background: -o-radial-gradient(transparent 100px, rgba(255,255,255,0.6) 200px);
  }

i need this

Body:
Here is another syntax in case you want better support than the at one (Safari doesn't currently support the at syntax for background). The gradient will by default be placed at the center so we increase the size of the background to move the center position to the right.

body {
  margin: 0;
  padding: 0;
}

.session-box {
  background: #333;
  width: 100%;
  min-height: 100vh;
}

.circle {
  position: absolute;
  top: 0;
  left 0;
  width: 100%;
  height: 100%;
  /* Circle with 100px Radius*/
  background-image: radial-gradient(circle 100px, transparent 50%, rgba(255, 255, 255, 0.6) 100%);
  /* Twice bigger than the container minus 2xRadius */
  background-size: calc(200% - 200px) 100%;
}

<div class="session-box">
  <div class="circle">
  </div>
</div>

You can also do it without calc():

body {
  margin: 0;
  padding: 0;
}

.session-box {
  background: #333;
  width: 100%;
  min-height: 100vh;
}

.circle {
  position: absolute;
  top: 0;
  left 0;
  width: 100%;
  height: 100%;
  padding-right:100px; /*Equal to radius*/
  /* Circle with 100px Radius*/
  background-image: radial-gradient(circle 100px, transparent 50%, rgba(255, 255, 255, 0.6) 100%);
  /* Twice bigger than the container */
  background-size: 200% 100%;
  background-origin:content-box; /* We don't consider the padding when doing the calculation */
  box-sizing:border-box;
}

<div class="session-box">
  <div class="circle">
  </div>
</div>


问:
Jar files are not opening
.jar files won't open on my PC. I've tried reinstalling Java and messed with the environment variables.</p>

答:
Try to do all of the following things:

Ensure that you have JRE installed by entering java -version in command prompt.

Ensure that Java is properly added to the system path. Read about that here.

Open your command prompt, navigate to the location of your jar and enter javaw.exe -jar <yourfile>.jar

If you are using a path instead of a jar name make sure you are wrapping it in double quotes.

Also make sure the jar file is actually present in the directory you are trying to access it from

If that doesn't work please provide additional information about what exactly didn't work.

Title: Jar files are not opening


问:
Anko CardView radius not work
I want to create cardView with anko and set cornerRadius param to it. But When I try to do - no such differents come.
In main class I do this:

```<code>override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
    with(applicationContext!!) {
        listView = listView {
            layoutParams = ViewGroup.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)
            dividerHeight = 20
        }
    }
    listView?.adapter = CustomAdapter(forms)

    return listView!!
}
</code>```

In CustomAdapter I return cardView like this:

```<code>override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    val currentForm = getItem(position)
    return convertView ?: createCardView(parent!!.context, currentForm)
}

private fun createCardView(context: Context, form: FormField): View =
        with(context) {
            frameLayout {
                cardView {
                    layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT).apply {
                        leftMargin = dip(10)
                        rightMargin = dip(10)
                        topMargin = dip(5)
                        bottomMargin = dip(5)

                    }
                    backgroundColor = Color.WHITE
                    radius = dip(8).toFloat()

                    verticalLayout {
                        // title
                        textView {
                            text = form.title
                            textColor = ContextCompat.getColor(context, R.color.colorPrimary)
                            textSize = 20f
                        }.lparams(width = matchParent) {
                            leftMargin = dip(15)
                            topMargin = dip(10)
                            bottomMargin = dip(10)
                        }
                        // subtitle
                        textView {
                            if (form.subTitle != null) {
                                text = form.subTitle
                                textColor = ContextCompat.getColor(context, R.color.colorPrimary)
                                textSize = 12f
                                visibility = View.VISIBLE
                            } else {
                                visibility = View.GONE
                            }
                        }.lparams(width = matchParent) {
                            leftMargin = dip(15)
                            topMargin = dip(10)
                            bottomMargin = dip(10)
                        }

                    }.lparams(width = matchParent, height = matchParent)
                }
            }
        }
</code>```

I try to call 'radius' setter in different ways and values, but result is always like this

As you can see - the corners are always rectangle. What I want - to round the corners with Anko

Small p.s. - when I return from getView inflated xml layout with same cardview - it has rounded corners.

答:
The previous answer didn't help me. That is worked for me:</p>

```<code>cardView {
    background = GradientDrawable().apply {
        shape = GradientDrawable.RECTANGLE
        cornerRadius = 8f
        setStroke(2, grey)
        ....
    }
}
</code>```

Title: Anko CardView radius not work

Body:
I want to create cardView with anko and set cornerRadius param to it. But When I try to do - no such differents come.
In main class I do this:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
    with(applicationContext!!) {
        listView = listView {
            layoutParams = ViewGroup.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)
            dividerHeight = 20
        }
    }
    listView?.adapter = CustomAdapter(forms)

    return listView!!
}

In CustomAdapter I return cardView like this:

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    val currentForm = getItem(position)
    return convertView ?: createCardView(parent!!.context, currentForm)
}

private fun createCardView(context: Context, form: FormField): View =
        with(context) {
            frameLayout {
                cardView {
                    layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT).apply {
                        leftMargin = dip(10)
                        rightMargin = dip(10)
                        topMargin = dip(5)
                        bottomMargin = dip(5)

                    }
                    backgroundColor = Color.WHITE
                    radius = dip(8).toFloat()

                    verticalLayout {
                        // title
                        textView {
                            text = form.title
                            textColor = ContextCompat.getColor(context, R.color.colorPrimary)
                            textSize = 20f
                        }.lparams(width = matchParent) {
                            leftMargin = dip(15)
                            topMargin = dip(10)
                            bottomMargin = dip(10)
                        }
                        // subtitle
                        textView {
                            if (form.subTitle != null) {
                                text = form.subTitle
                                textColor = ContextCompat.getColor(context, R.color.colorPrimary)
                                textSize = 12f
                                visibility = View.VISIBLE
                            } else {
                                visibility = View.GONE
                            }
                        }.lparams(width = matchParent) {
                            leftMargin = dip(15)
                            topMargin = dip(10)
                            bottomMargin = dip(10)
                        }

                    }.lparams(width = matchParent, height = matchParent)
                }
            }
        }

I try to call 'radius' setter in different ways and values, but result is always like this

As you can see - the corners are always rectangle. What I want - to round the corners with Anko

Small p.s. - when I return from getView inflated xml layout with same cardview - it has rounded corners.

Body:
The previous answer didn't help me. That is worked for me:

cardView {
    background = GradientDrawable().apply {
        shape = GradientDrawable.RECTANGLE
        cornerRadius = 8f
        setStroke(2, grey)
        ....
    }
}