问:
Having another Where Filter on Laravel
I am trying to do a search and would only like to return the users with status of 1,4. Although when I try to use this, it grabs them all and ignores my last where.

```<code>$officiants = Officiant::where('status',1)
                        ->where('email', 'like',  '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->whereIn('status', [1,4])
                        ->get();
</code>```

I have also tried

```<code>$officiants = Officiant::where('status',1)
                        ->where('email', 'like',  '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->where('status', 1)
                        ->where('status', 4)
                        ->get();
</code>```

答:
The problem is you need to understand how where chaining and orWhere chaining works in Laravel.

When you say $query->where(..a..)->orWhere(..b..)->where(..c..)->orWhere(..d..) it will evaluate to: (a || (b && c) || d). Where you may have intended ((a || b) && (c || d)) or you may have intended ((a && c) || b || d). This is why when you need advanced where clauses, use parameter grouping

Title: Having another Where Filter on Laravel

Body:
I am trying to do a search and would only like to return the users with status of 1,4. Although when I try to use this, it grabs them all and ignores my last where.

$officiants = Officiant::where('status',1)
                        ->where('email', 'like',  '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->whereIn('status', [1,4])
                        ->get();

I have also tried

$officiants = Officiant::where('status',1)
                        ->where('email', 'like',  '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->where('status', 1)
                        ->where('status', 4)
                        ->get();


来源: stackexchange

答:
you need something like this :

```<code>$officiants = Officiant::where('status',1)
    ->where(function($query) use($item){
        $query->where('email', 'like',  '%'.$item.'%')
            ->orWhere('lname', 'like', '%'.$item.'%')
            ->orWhere('lname', 'like', '%'.$item.'%')
    })
        ->whereIn('status', [1,4])
        ->get();
</code>```

note : this is not tested

ContentLicense: CC BY-SA 3.0

Title: Having another Where Filter on Laravel

Body:
you need something like this :

$officiants = Officiant::where('status',1)
    ->where(function($query) use($item){
        $query->where('email', 'like',  '%'.$item.'%')
            ->orWhere('lname', 'like', '%'.$item.'%')
            ->orWhere('lname', 'like', '%'.$item.'%')
    })
        ->whereIn('status', [1,4])
        ->get();

note : this is not tested


问:
"Unknown props" warning on console when attaching additional props
I'm using Styled Components v2.1.1.
The documentation says that to avoid unnecessary wrappers we can use the .attrs constructor. See: https://www.styled-components.com/docs/basics#attaching-additional-props

I've tried to use it but I always receive the following warning in the console:

```<code>Warning: Unknown props `margin`, `padding` on <input> tag. Remove these props from the element. For details, see (removed )
 in input (created by styled.input)
in styled.input (created by InputContainer)
in div (created by InputContainer)
in InputContainer
</code>```

I've created a Webpack Bin to show the error: https://www.webpackbin.com/bins/-KpKbVG-Ed0jysHeFVVY

Am I using it in the wrong way or is there an issue?

答:
As it seems, the example provided on the styled components website is not an actual usable example.

Since the attrs function creates attributes for the properties you set, the error is correct in saying that the html <input> tag does not support the attributes margin and padding: MDN - HTML input attributes

The error you're seeing was marked as an issue on the styled-components GitHub.
The actual solution is not to literally use the example given in the styled-components documentation. For the full explanation, please refer to the issue report.

The code example given by one of the contributers on Github is to modify the example as follows:

```<code>const getSize = p => p.size || '1em'

const Input = styled.input.attrs({
    // we can define static props
    type: 'password'
})`
    color: palevioletred;
    font-size: 1em;
    border: 2px solid palevioletred;
    border-radius: 3px;

    /* here we use the dynamically computed props */
    margin: ${getSize};
    padding: ${getSize};
`;
</code>```

Body:
I'm using Styled Components v2.1.1.
The documentation says that to avoid unnecessary wrappers we can use the .attrs constructor. See: https://www.styled-components.com/docs/basics#attaching-additional-props

I've tried to use it but I always receive the following warning in the console:

Warning: Unknown props `margin`, `padding` on <input> tag. Remove these props from the element. For details, see (removed )
 in input (created by styled.input)
in styled.input (created by InputContainer)
in div (created by InputContainer)
in InputContainer

I've created a Webpack Bin to show the error: https://www.webpackbin.com/bins/-KpKbVG-Ed0jysHeFVVY

Am I using it in the wrong way or is there an issue?

Body:
As it seems, the example provided on the styled components website is not an actual usable example.

Since the attrs function creates attributes for the properties you set, the error is correct in saying that the html <input> tag does not support the attributes margin and padding: MDN - HTML input attributes

The error you're seeing was marked as an issue on the styled-components GitHub.
The actual solution is not to literally use the example given in the styled-components documentation. For the full explanation, please refer to the issue report.

The code example given by one of the contributers on Github is to modify the example as follows:

const getSize = p => p.size || '1em'

const Input = styled.input.attrs({
    // we can define static props
    type: 'password'
})`
    color: palevioletred;
    font-size: 1em;
    border: 2px solid palevioletred;
    border-radius: 3px;

    /* here we use the dynamically computed props */
    margin: ${getSize};
    padding: ${getSize};
`;


问:
Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
while trying this mongo command in ubuntu
I am getting this error.

```<code>    ritzysystem@ritzysystem-Satellite-L55-A:~$ mongo
    MongoDB shell version: 2.6.1
    connecting to: test
    2014-10-06T12:59:35.802+0530 warning: Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
    2014-10-06T12:59:35.802+0530 Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed at src/mongo/shell/mongo.js:146
    exception: connect failed
</code>```

how can I rectify this is anyone had the same problem.

答: I solved that simply by entering sudo mongo after mongod command.

Body:
while trying this mongo command in ubuntu
I am getting this error.

    ritzysystem@ritzysystem-Satellite-L55-A:~$ mongo
    MongoDB shell version: 2.6.1
    connecting to: test
    2014-10-06T12:59:35.802+0530 warning: Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
    2014-10-06T12:59:35.802+0530 Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed at src/mongo/shell/mongo.js:146
    exception: connect failed

how can I rectify this is anyone had the same problem.


问:
How to load values from query to myClass properties using Dapper
I have a class called Students

```<code>    public class Students
    {
     private string name ;
     private string age;
     private string adress;

    //Constructor
    public Students (string name,string age,string adress)
    {
    this.name=name;
    this.age=age;
    this.adress=adress;
    }
  }
</code>```

and a Query myQuery :

```<code>Select h.name
b.age,
v.adress
FROM Tb.Students h
INNER JOIN db.tb_1 d
ON h.id= d.id
 INNER JOIN db.TB_2 v
 ON d.id = v.id
</code>```

Now when I run this :

```<code> Connection conn = new Connection();
        OracleConnection connection = conn.GetDBConnection();

 var studentsInfo= connection.Query<Students>(myQuery).ToList();
</code>```

I noticed studentsInfo has results and row size is loaded but when I put the cursor on  studentsInfo , the properties , Name , Age, Adress are empty

What I am missing ? How to assign the result of the query to my properties so I can use them like that :

```<code>foreach ( var student in studentsInfo )
{
 console.writeline(sutdent.age);
}
</code>```

答:
Not sure this will help, but it looks like what you have should work. I tend to work with SQL Server, but the ADO.NET layer is mostly the same, and I tried the following case:

```<code>using Dapper;
using System.Data.SqlClient;
using System.Linq;

public class Students
{
    private string name;
    private string age;
    private string adress;

    public Students(string name, string age, string adress)
    {
        this.name = name;
        this.age = age;
        this.adress = adress;
    }
    public override string ToString() => $"{name}, {age}, {adress}";
}
static class P
{
    static void Main()
    {
        using (var connection = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=SSPI;"))
        {
            const string myQuery = "select 'fred' as [name], '27' as [age], 'somewhere' as [adress]";
            var studentsInfo = connection.Query<Students>(myQuery).ToList();
            foreach(var student in studentsInfo)
            {
                System.Console.WriteLine(student);
            }
        }
    }
}
</code>```

It worked fine, outputting:

```<code>fred, 27, somewhere
</code>```

So my main thoughts would be: does the query output what you think it outputs? Is the data what you think it is? Also: are you sure that age is a string?

Body:
I have a class called Students

    public class Students
    {
     private string name ;
     private string age;
     private string adress;

    //Constructor
    public Students (string name,string age,string adress)
    {
    this.name=name;
    this.age=age;
    this.adress=adress;
    }
  }

and a Query myQuery :

Select h.name
b.age,
v.adress
FROM Tb.Students h
INNER JOIN db.tb_1 d
ON h.id= d.id
 INNER JOIN db.TB_2 v
 ON d.id = v.id

Now when I run this :

 Connection conn = new Connection();
        OracleConnection connection = conn.GetDBConnection();

 var studentsInfo= connection.Query<Students>(myQuery).ToList();

I noticed studentsInfo has results and row size is loaded but when I put the cursor on  studentsInfo , the properties , Name , Age, Adress are empty

What I am missing ? How to assign the result of the query to my properties so I can use them like that :

foreach ( var student in studentsInfo )
{
 console.writeline(sutdent.age);
}

Body:
Not sure this will help, but it looks like what you have should work. I tend to work with SQL Server, but the ADO.NET layer is mostly the same, and I tried the following case:

using Dapper;
using System.Data.SqlClient;
using System.Linq;

public class Students
{
    private string name;
    private string age;
    private string adress;

    public Students(string name, string age, string adress)
    {
        this.name = name;
        this.age = age;
        this.adress = adress;
    }
    public override string ToString() => $"{name}, {age}, {adress}";
}
static class P
{
    static void Main()
    {
        using (var connection = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=SSPI;"))
        {
            const string myQuery = "select 'fred' as [name], '27' as [age], 'somewhere' as [adress]";
            var studentsInfo = connection.Query<Students>(myQuery).ToList();
            foreach(var student in studentsInfo)
            {
                System.Console.WriteLine(student);
            }
        }
    }
}

It worked fine, outputting:

fred, 27, somewhere

So my main thoughts would be: does the query output what you think it outputs? Is the data what you think it is? Also: are you sure that age is a string?


问:
PHP array_search not working when deleting entries
This sample code is giving me a headache. I'm trying to get 2 random values from the array. Delete the 2 entries that was chosen, and then continue until all elements is chosen. My problem is that the first 1-2 picks works fine, but then is chosen values that's not in the array, some times the same value is chosen 2 times...when removing the 2 unset-lines the code is ok...
I belive it's about the reindexing of the array after deleting, but the line "$number=array_values($number)" should do the job...</p>

```<code>    <?php

$number=array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);//range(1,10);

//var_dump($number)." - ";//

for ($p = 1; $p <= 5; $p++) {
    echo "Nr. :".$p."</br>";
    echo implode(",",$number)."</br></br>";

    $udtrak = array_rand($number,2); // udvælger 2
    $pos[0] = array_search($udtrak[0], $number);
    $pos[1] = array_search($udtrak[1], $number);
    echo "Number: ".$number[$pos[0]]." Found at: " . $pos[0]."</br>";
    echo "Number: ".$number[$pos[1]]." Found at: " . $pos[1]."</br>";

    //unset($number[$pos[0]]);
    //unset($number[$pos[1]]);
    //var_dump($pos);

$number=array_values($number);

echo implode(",",$number)."</br></br>";
} // for $p

?>
</code>```

答:
If you don't want to see any chance of duplication, just shuffle the array once from the start and output the data in pairs.  No counters required.  This also does not remove any array elements, so you can re-use them again "downscript".  My method employs the "Don't Repeat Yourself" principle of coding and makes no iterated function calls (well, I guess it does while sorting).

Code: (Demo)

```<code>$numbers=array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);//range(1,10);
uksort($numbers,function(){return rand()>rand();});  // shuffle and preserve indexes
//var_export($numbers);
$pairs=array_chunk($numbers,2,true);  // pair the values together (preserving indexes)
//var_export($pairs);
foreach($pairs as $pair){
    foreach($pair as $index=>$value){
        echo "Number: $value Found at: $index\n";
    }
}
</code>```

Possible Output:

```<code>Number: 2 Found at: 1
Number: 1 Found at: 0
Number: 5 Found at: 4
Number: 3 Found at: 2
Number: 6 Found at: 5
Number: 4 Found at: 3
Number: 7 Found at: 6
Number: 8 Found at: 7
Number: 10 Found at: 9
Number: 9 Found at: 8
</code>```

...hmm, perhaps a more efficient sort would be:

```<code>$mid=getrandmax()/2;
uksort($numbers, function()use($mid){return rand()>$mid;});  // shuffle and preserve indexes
</code>```

And finally, if you want to leave the input totally untouched, shuffle an array of indexes instead. (This is probably my most recommended option)

Code: (Demo)

```<code>$numbers=array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);//range(1,10);
$indexes=array_keys($numbers);  // store indexes as values
shuffle($indexes);
$pairs=array_chunk($indexes,2);  // group indexes by two
foreach($pairs as $pair){
    foreach($pair as $index){
        echo "Number: {$numbers[$index]} Found at: $index\n";
    }
}
</code>```

Body:
This sample code is giving me a headache. I'm trying to get 2 random values from the array. Delete the 2 entries that was chosen, and then continue until all elements is chosen. My problem is that the first 1-2 picks works fine, but then is chosen values that's not in the array, some times the same value is chosen 2 times...when removing the 2 unset-lines the code is ok...
I belive it's about the reindexing of the array after deleting, but the line "$number=array_values($number)" should do the job...

    <?php

$number=array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);//range(1,10);

//var_dump($number)." - ";//

for ($p = 1; $p <= 5; $p++) {
    echo "Nr. :".$p."
";
    echo implode(",",$number)."

";

    $udtrak = array_rand($number,2); // udvælger 2
    $pos[0] = array_search($udtrak[0], $number);
    $pos[1] = array_search($udtrak[1], $number);
    echo "Number: ".$number[$pos[0]]." Found at: " . $pos[0]."
";
    echo "Number: ".$number[$pos[1]]." Found at: " . $pos[1]."
";

    //unset($number[$pos[0]]);
    //unset($number[$pos[1]]);
    //var_dump($pos);

$number=array_values($number);

echo implode(",",$number)."

";
} // for $p

?>

Body:
If you don't want to see any chance of duplication, just shuffle the array once from the start and output the data in pairs.  No counters required.  This also does not remove any array elements, so you can re-use them again "downscript".  My method employs the "Don't Repeat Yourself" principle of coding and makes no iterated function calls (well, I guess it does while sorting).

Code: (Demo)

$numbers=array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);//range(1,10);
uksort($numbers,function(){return rand()>rand();});  // shuffle and preserve indexes
//var_export($numbers);
$pairs=array_chunk($numbers,2,true);  // pair the values together (preserving indexes)
//var_export($pairs);
foreach($pairs as $pair){
    foreach($pair as $index=>$value){
        echo "Number: $value Found at: $index\n";
    }
}

Possible Output:

Number: 2 Found at: 1
Number: 1 Found at: 0
Number: 5 Found at: 4
Number: 3 Found at: 2
Number: 6 Found at: 5
Number: 4 Found at: 3
Number: 7 Found at: 6
Number: 8 Found at: 7
Number: 10 Found at: 9
Number: 9 Found at: 8

...hmm, perhaps a more efficient sort would be:

$mid=getrandmax()/2;
uksort($numbers, function()use($mid){return rand()>$mid;});  // shuffle and preserve indexes

And finally, if you want to leave the input totally untouched, shuffle an array of indexes instead. (This is probably my most recommended option)

Code: (Demo)

$numbers=array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);//range(1,10);
$indexes=array_keys($numbers);  // store indexes as values
shuffle($indexes);
$pairs=array_chunk($indexes,2);  // group indexes by two
foreach($pairs as $pair){
    foreach($pair as $index){
        echo "Number: {$numbers[$index]} Found at: $index\n";
    }
}


问:
High CPU load delaying UIView redraw (iOS)
I'm making an iOS app with an OpenGL ES view. On top of the 3D view I draw miscellaneous GUI bits using Cocoa Touch.

This works fine as long as the framerate is good. However, when the CPU load gets to high (GLES view drops to 20-ish FPS), it seems like the next UIKit display cycle is being pushed forward.

Specifically, I'm trying to display a tooltip view, based on various UIView subclasses. When it's time to display it, I update the tooltip label text and resize its background, then set hidden to NO for the main UIView and call setNeedsDisplay and setNeedsLayout.

When the framerate is low (i.e. CPU load is high), the next display cycle seems to be pushed forward indefinitely. But immediately when the CPU load goes down, the view is displayed as expected.

Is there any way I can instigate a draw cycle in UIKit between my 3D engine redraws? Any other ideas?

答:
On iPhone, all applications do their UI drawing and logic on one thread, unless otherwise specified.

You could move your 3D drawing code into another thread:

```<code>[NSThread detachNewThreadSelector:@selector(3DRenderingMethod) toTarget:self withObject:nil]
</code>```

Here's the relevant documentation: http://developer.apple.com/library/iOS/#documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html

ContentLicense: CC BY-SA 2.5

Body:
On iPhone, all applications do their UI drawing and logic on one thread, unless otherwise specified.

You could move your 3D drawing code into another thread:

[NSThread detachNewThreadSelector:@selector(3DRenderingMethod) toTarget:self withObject:nil]

Here's the relevant documentation: http://developer.apple.com/library/iOS/#documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html


问:
Use AMP with Material Design Lite in angular 5
I would like to create an e-commerce progressive web app with angular 5. How can I use AMP with angular 5 in Google Material Design Lite?
If it is not scalable or feasible then what are the other good options?</p>

答:
I presume that you are already familiar with SSR/server-side rendering using Angular Universal, before anything else. Since no custom JavaScript is allowed on AMP.

Having said that, let's talk a bit about AMP standards and restrictions and see what possible issues are when it comes to Angular.

1. How does a website/app implement AMP, in my experience?

Well, you'd practically have 2 versions for each page (the regular version and the AMP version - with strict rules to adhere to).
Let's say you have a video page on my-app.com/video/1234/some-video-slug. And you want to tell Google that you have an AMP version for this page. You do that by adding the following in the : <link rel="amphtml" href="my-app.com/video-amp/1234/some-video-slug"> where /video-amp would be the route that serves the AMP version. All the next points are about what happens on that AMP route/page.

2. You are not allowed to have any external styles

So, no <link rel="stylesheet" href="path-to-some.css">.

Only a few allowed by AMP (like Font Awesome //maxcdn.bootstrapcdn.com/font-awesome/ or Material Icons/Google Fonts //font.googleapis.com, so from specific cdns only, definitely NOT hosted on your own server).

What does this mean? Well, when on an AMP route, you need to strip the server-rendered document of all external css references that aren't allowed by AMP and add those that are allowed, if/when needed - like when you need some icons or google fonts. Removing and Adding tags in the document (so, this includes the  section) is possible using the document and renderer provided by Angular. But, to me it seemed slow even to only traverse the children nodes of the  section in order to remove any <link> tag. And I don't think you could do that outside of your Angular app, since you have very little knowledge about what needs to be done on what route.

3. How do you style your app then?

Well the only custom css that AMP allows you to have is inside a

Body:
I presume that you are already familiar with SSR/server-side rendering using Angular Universal, before anything else. Since no custom JavaScript is allowed on AMP.

Having said that, let's talk a bit about AMP standards and restrictions and see what possible issues are when it comes to Angular.

1. How does a website/app implement AMP, in my experience?

Well, you'd practically have 2 versions for each page (the regular version and the AMP version - with strict rules to adhere to).
Let's say you have a video page on my-app.com/video/1234/some-video-slug. And you want to tell Google that you have an AMP version for this page. You do that by adding the following in the <head>: <link rel="amphtml" href="my-app.com/video-amp/1234/some-video-slug"> where /video-amp would be the route that serves the AMP version. All the next points are about what happens on that AMP route/page.

2. You are not allowed to have any external styles

So, no <link rel="stylesheet" href="path-to-some.css">.

Only a few allowed by AMP (like Font Awesome //maxcdn.bootstrapcdn.com/font-awesome/ or Material Icons/Google Fonts //font.googleapis.com, so from specific cdns only, definitely NOT hosted on your own server).

What does this mean? Well, when on an AMP route, you need to strip the server-rendered document of all external css references that aren't allowed by AMP and add those that are allowed, if/when needed - like when you need some icons or google fonts. Removing and Adding tags in the document (so, this includes the <head> section) is possible using the document and renderer provided by Angular. But, to me it seemed slow even to only traverse the children nodes of the <head> section in order to remove any <link> tag. And I don't think you could do that outside of your Angular app, since you have very little knowledge about what needs to be done on what route.

3. How do you style your app then?

Well the only custom css that AMP allows you to have is inside a <style> block within the document.

How do you do that? Well, I don't see any other solution other than having a separate build just for some css, which targets the AMP version and has nothing to do with any Angular/Angular CLI workflow, other than maybe compiling/merging the existing css files you already wrote for your components. And somehow, put the generated result in a <style> block inside the <head> section, only when on the AMP version.

But keep in mind that those styles aren't necessarily 100% valid css. You might have /deep/ or :host.

4. You are not allowed to have ANY custom JavaScript.

So, basically your entire Angular app code should not be included. You have to strip the server-rendered html out of any <script> tags.

5. How do you javascript then, without custom JavaScript?

For example, it would seem crazy to not have a sliding menu or a dropdown menu, on mobile. Well... You can! But only by using AMP "components".

You'd have to use <amp-sidebar> instead of <mat-sidenav> or whatever custom component you might have built. But - somehow - only when on the AMP route, because I love Angular Material components.

And how does it work? The <amp-sidebar>?

Well, when AMP offers you components, that includes JavaScript. In order to make the sidebar work, you can include: https://cdn.ampproject.org/v0/amp-sidebar-0.1.js. That is allowed. You generally have a lot of common used/needed components available: amp-carousel, amp-img (yes, you are not allowed to simply use the <img> tag), amp-video, amp-accordion...

6. What about the rest of the HTML document?

Well, by simply passing a server-rendered html of an Angular app through the AMP validator, there are a lot of problems here also:

It errors on any custom attributes. And Angular is full of those, especially to emulate a native ViewEncapsulation (you've seen all the _ngcontent-c1 and such attributes). In order to get rid of those, I guess you'd either have to go with ViewEncapsulation.None, but then each component style will become global OR strip the server rendered html out of all those _ng... attributes and go though a great deal of pain to somehow build an AMP css that only targets by class/id etc. and use more classes in your components to style by anyway.

It also errors on all custom tags (that aren't AMP, of course).
And you know Angular apps and Material Components are build with
those. Even the very first one: <app-root>. And, honestly, I
wouldn't work with anything else other than tag selectors and, in
some cases attribute selectors (like with Directives).

This is all that I could think of, so far.

I would say that implementing AMP on an Angular app is close to impossible at this point in time.

But, given that AMP and Angular are both Google projects, I would expect to see some progress in regards to Angular+AMP soon enough. I've heard someone saying that Rob Wormald actually mentioned something about AMP early this year, like in April at Ng-Conf... But I couldn't find anything on that, or any progress so far, and we're close to 2018 already. Plus, maybe there were just some ideas, not even a road map... don't know!?

Hopefully, with Angular 6! I'm an optimist.

For now, I think that a progressive web-app should be fast enough that AMP wouldn't be able to improve much on that speed (as long as you're not on a bad connection on the first load). I don't know how you'd rank on that, though (having a really good PWA versus implementing AMP - when it's one or the other, not both)


问:
Ternary operator VB vs C#: why resolves Nothing to zero?
I just shoot myself in the foot and would like to know whether there were actual reasons to make this situation possible.

And anyway, this question can stay for the convenience of the future foot shooters.

Suppose we have a nullable value in vb.net:

Dim i as Integer?
```

<p>We want to assign a value to it, basing on a condition, and using a ternary operator, because it's so neat and stuff:</p>

<pre class="lang-vb prettyprint-override"><code>i = If(condition(), Nothing, 42)
</code>```

That is, if a condition is true, employ the nullability, otherwise the value.

At which point the shooting occurs. For no apparent reason VB compiler decides that the common base type for Nothing and Integer is Integer, at which point it silently translates the statement to:

i = If(condition(), 0, 42)
```

<hr>

<p>Now, if you were to do this in C#:</p>

<pre class="lang-cs prettyprint-override"><code>i = (condition()) ? null : 42;
</code>```

You would immediately get a compiler error saying that <null> doesn't mix well with int. Which is great, as my foot would have been healthier had I went the C# way this time. And for this to compile, you have to explicitly write:

i = (condition()) ? null : (int?)42;
```

<hr>

<p>Now, you <em>can</em> do the same in VB and get the correct null-ness you would expect:</p>

<pre class="lang-vb prettyprint-override"><code>i = If(condition(), Nothing, CType(42, Integer?))
</code>```

But that requires having your foot shot in the first place. There's no compiler error and there's no warning. That's with Explicit On and Strict On.

So my question is, why?

Should I take this as a compiler bug?

Or can someone explain why the compiler behaves this way?

答:
This is actually now possible in VS2015 (at the very least) by using New Integer?

Ex.:

If(testInt> 0, testInt, New Integer?), where testInt is of type Integer?

Body:
I just shoot myself in the foot and would like to know whether there were actual reasons to make this situation possible.

And anyway, this question can stay for the convenience of the future foot shooters.

Suppose we have a nullable value in vb.net:

Dim i as Integer?

We want to assign a value to it, basing on a condition, and using a ternary operator, because it's so neat and stuff:

i = If(condition(), Nothing, 42)

That is, if a condition is true, employ the nullability, otherwise the value.

At which point the shooting occurs. For no apparent reason VB compiler decides that the common base type for Nothing and Integer is Integer, at which point it silently translates the statement to:

i = If(condition(), 0, 42)

Now, if you were to do this in C#:

i = (condition()) ? null : 42;

You would immediately get a compiler error saying that <null> doesn't mix well with int. Which is great, as my foot would have been healthier had I went the C# way this time. And for this to compile, you have to explicitly write:

i = (condition()) ? null : (int?)42;

Now, you can do the same in VB and get the correct null-ness you would expect:

i = If(condition(), Nothing, CType(42, Integer?))

But that requires having your foot shot in the first place. There's no compiler error and there's no warning. That's with Explicit On and Strict On.

So my question is, why?

Should I take this as a compiler bug?

Or can someone explain why the compiler behaves this way?


问:
How change import scss based on current selected language with Angular
I'm using angular-translate in my Angular application.

And I want to change the importing scss files based on the current selected languge

```<code>@import 'partials/reset';
@import 'partials/variables_ar';     <--------- OR
@import 'partials/variables_en';     <--------- Based on  $translate.use();
@import 'partials/mixins';
@import 'partials/angular-material-extend';
@import 'partials/layouts-template';
@import 'partials/layouts-page';
@import 'partials/animations';
@import 'partials/colors';
@import 'partials/icons';
</code>```

答:
Since SASS is built at compile time, not run time, you can't achieve what you're trying to do that way.

I think the best approach for you is to change the  class based on the user's selected language, and then style your webapp depending on that class. For example your HTML:

```<code><body class="{{ languageCode }}">
  <header>My Header</header>
</body>
</code>```

and your SCSS:

```<code>body.en {
  header { color: blue; }
}

body.fr {
  header { color: red; }
}
</code>```

Body:
I'm using angular-translate in my Angular application.

And I want to change the importing scss files based on the current selected languge

@import 'partials/reset';
@import 'partials/variables_ar';     <--------- OR
@import 'partials/variables_en';     <--------- Based on  $translate.use();
@import 'partials/mixins';
@import 'partials/angular-material-extend';
@import 'partials/layouts-template';
@import 'partials/layouts-page';
@import 'partials/animations';
@import 'partials/colors';
@import 'partials/icons';

Body:
Since SASS is built at compile time, not run time, you can't achieve what you're trying to do that way.

I think the best approach for you is to change the  class based on the user's selected language, and then style your webapp depending on that class. For example your HTML:

<body class="{{ languageCode }}">
  <header>My Header</header>
</body>

and your SCSS:

body.en {
  header { color: blue; }
}

body.fr {
  header { color: red; }
}


问:
converting datetime string to the correct timezone
I've went through a few useful discussions on the topic, but still don't understand the following:

Say, I have a string "20080730 06:23:54 PDT" which I want to convert to a timezone aware datetime object. I understand, that dateutil.parser.parse() doesn't generally parse timezones like "PDT", but looks like it does parse "UTC" and "EDT" correctly. Are these exceptions? Is "EDT" an exception b/c it's my local timezone?

```<code>import pytz
from dateutil.parser import parse
sdt="20080730 06:23:54 UTC"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54, tzinfo=tzutc())
sdt="20080730 06:23:54 EDT"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54, tzinfo=tzlocal())
sdt="20080730 06:23:54 PDT"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54)
</code>```

答: In similar situations I've found that Eastern Daylight Time is an exception: It's often available / parseable alongside the equivalent Standard timezone names, even though the same isn't true for Pacific time or others.</p>

Body:
I've went through a few useful discussions on the topic, but still don't understand the following:

Say, I have a string "20080730 06:23:54 PDT" which I want to convert to a timezone aware datetime object. I understand, that dateutil.parser.parse() doesn't generally parse timezones like "PDT", but looks like it does parse "UTC" and "EDT" correctly. Are these exceptions? Is "EDT" an exception b/c it's my local timezone?

import pytz
from dateutil.parser import parse
sdt="20080730 06:23:54 UTC"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54, tzinfo=tzutc())
sdt="20080730 06:23:54 EDT"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54, tzinfo=tzlocal())
sdt="20080730 06:23:54 PDT"
dt_obj = parse(sdt)
dt_obj
datetime.datetime(2008, 7, 30, 6, 23, 54)


问:
How do I get 2 different width divs right next to each other in a row?
I need to have an email layout where it has a header, and in the body will be two divs where one is 2/3rds the width of the main container div, and the other right next to it that will be 1/3rd the total width.

I also would like to know if there's a trick for making vertical rules, similar to horizontal rules we classically see.

Here's the code I was told to try, but I am not getting two divs next to each other inside the main container div:

```<code><html>
<head>
<meta charset="UTF-8">
<title>AUSA email</title>
</head>

<body style="font-family:sans-serif;"
      #wrapper {
    width: 500px;
    border: 1px solid black;
}
#first {
    width: 400px;
    border: 1px solid red;
}
#second {
    width: 200px;
    border: 1px solid green;
}></style>
    <div id="wrapper">
    <div id="first">Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text.</div>
    <div id="second">Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text.</div>
</div>
</body>

</html>
</code>```

答:
Use Flexbox

Here is a guide you should read.

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

CSS

```<code>#wrapper {
width: 500px;
border: 1px solid black;
display: flex;
justify-content: center;
}
#first {
width: 300px;
border: 1px solid red;
}
#second {
width: 200px;
border: 1px solid green;
}
</code>```

HTML

```<code><html>
<head>
<meta charset="UTF-8">
<title>AUSA email</title>
</head>
<body>
<div id="wrapper">
<div id="first">Sample text.</div>
<div id="second">Sample text.</div>
</div>
</body>
</html>
</code>```

Body:
I need to have an email layout where it has a header, and in the body will be two divs where one is 2/3rds the width of the main container div, and the other right next to it that will be 1/3rd the total width.

I also would like to know if there's a trick for making vertical rules, similar to horizontal rules we classically see.

Here's the code I was told to try, but I am not getting two divs next to each other inside the main container div:

<meta charset="UTF-8">
<title>AUSA email</title>

</style>

Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text.

Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text.

Body:
Use Flexbox

Here is a guide you should read.

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

CSS

#wrapper {
width: 500px;
border: 1px solid black;
display: flex;
justify-content: center;
}
#first {
width: 300px;
border: 1px solid red;
}
#second {
width: 200px;
border: 1px solid green;
}

HTML

<html>
<head>
<meta charset="UTF-8">
<title>AUSA email</title>
</head>
<body>
<div id="wrapper">
<div id="first">Sample text.</div>
<div id="second">Sample text.</div>
</div>
</body>
</html>


问:
Does this C code leak memory?
So here is my code:

```<code>typedef struct {
    int x;
    int *t;
}vector;

vector fct (vector v){
    vector w;
    int i;
    w.x=v.x;
    w.t=malloc(w.x *sizeof(int));
    for (i=0; i<w.x; i++)
        w.t[i]=2*v.t[i];
    return w;
}

int main (){
    int i;
    vector v;
    v.x=2;
    v.t=malloc(2*sizeof(int));
    v.t[0]=1; v.t[1]=5;
    v=fct(v);
    for (i=0; i<2; i++)
        printf("%d \t",v.t[i]);
    puts("");
    free(v.t);
    return 0;
}
</code>```

I'm quite worried about whether or not it causes a memory leak, and how I can fix that in case it does.
Oh, and I know that if I define another vector let's say w, such that
w = fct(v)
it would clear the problem, but I need a different method, one that would work even if the function is returned to the original vector.

答:
I'm quite worried about whether or not it causes a memory leak, and how I can fix that in case it does.

It does.  In main(), you allocate memory and point v.t to it; then you overwrite that pointer with one from the return value of fct().  The original pointer is lost, and you've no other copy of it, so the pointed-to memory is leaked.

Oh, and I know that if I define another vector let's say w, such that w = fct(v) it would clear the problem, but I need a different method, one that would work even if the function is returned to the original vector.

With every dynamic memory allocation comes an obligation to free that memory.  You can consider that obligation to be associated with exactly one copy of the pointer to that memory, as a kind of notional tag.  You can freely (notionally) transfer the tag to a different copy of the pointer.  If the copy then bearing the tag ever goes out of scope or is overwritten with a different value, however, then you leak the pointed-to memory.

Consider how that applies to your case:

You allocate memory and assign a pointer to v.t.  This is initially the only copy of the pointer to the allocated memory, so the obligation to free that memory is associated with it.

You pass a copy of v, including a copy of v.t, to function fct().  You have two alternatives: the obligation to free can stay with the original copy of v.t, or it can be transferred to the copy received by the function.  That is an inherent characteristic of the definition of fct(), and should be documented with it -- you cannot choose on a call-by-call basis.  Since fct() does not free the pointer, you have implicitly chosen for the obligation to free to remain with the original copy.

fct() performs its own allocation and returns a copy of the resulting pointer; that's the only copy that survives the execution of the function, so the obligation to free must go with it.

By overwriting the original v.t with a different value while it holds an obligation to free, you leak the original memory.  There is still an obligation to free the (new) value of v.t, but there is no longer any way to access the old dynamically-allocated memory.

Now you had one option in there: whether to transfer the obligation to free as part of the function call.  Suppose that you did transfer it; in that case, fct() must not fail to perform that free() before it returns.  In that case, however, main() must not use the original value of v.t after calling fct(), whether it overwrites v with that function's result or not.

So you have a choice: either fct() takes responsibility for freeing v.t (which it could pass on to another function if it wished, or which it could return to the caller via its return value), or fct() does not take that responsibility.  Its callers need to behave accordingly.  You cannot have it both ways.

Title: Does this C code leak memory?

Body:
So here is my code:

typedef struct {
    int x;
    int *t;
}vector;

vector fct (vector v){
    vector w;
    int i;
    w.x=v.x;
    w.t=malloc(w.x *sizeof(int));
    for (i=0; i<w.x; i++)
        w.t[i]=2*v.t[i];
    return w;
}

int main (){
    int i;
    vector v;
    v.x=2;
    v.t=malloc(2*sizeof(int));
    v.t[0]=1; v.t[1]=5;
    v=fct(v);
    for (i=0; i<2; i++)
        printf("%d \t",v.t[i]);
    puts("");
    free(v.t);
    return 0;
}

I'm quite worried about whether or not it causes a memory leak, and how I can fix that in case it does.
Oh, and I know that if I define another vector let's say w, such that
w = fct(v)
it would clear the problem, but I need a different method, one that would work even if the function is returned to the original vector.


问:
Java 8, Lambda: Sorting within grouped Lists and merging all groups to a list
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

```<code>Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
</code>```

I need the Grouping based on the order of the Elements in the origin List.

```<code>First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"
</code>```

The result would then look like the following:

```<code>List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"
</code>```

I have tried the following:

```<code>studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
</code>```

But this doesn't work.

答:
not 100% clear whether you're expected a Map<String, List<Student>> or just a List<Student>, nevertheless here are both solutions:

imports:

```<code>import static java.util.stream.Collectors.*;
import java.util.*;
import java.util.function.Function;
</code>```

retrieving a Map<String, List<Student>> where each List<Student> contains students sorted by their ids.

```<code>Map<String, List<Student>> resultSet = studlist.stream()
      .collect(groupingBy(Student::getLocation,
             mapping(Function.identity(),
                  collectingAndThen(toList(),
                      e -> e.stream().sorted(Comparator.comparingInt(Student::getId))
                                            .collect(toList())))));
</code>```

on the other hand, if you want to retrieve just a list of Student objects sorted by a given property then it would be a waste of resources to perform a groupingBy, sorted, collect and somehow reduce the map values into a single list. Rather just sort the Student objects within the list providing a sort key i.e.

```<code>studlist.sort(Comparator.comparingInt(Student::getId));
</code>```

or

```<code>studlist.sort(Comparator.comparing(Student::getLocation));
</code>```

or depending on whether you want to sort by more than one property then you could do something like shmosel's answer.

Body:
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

I need the Grouping based on the order of the Elements in the origin List.

First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"

The result would then look like the following:

List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"

I have tried the following:

studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))

But this doesn't work.

Body:
not 100% clear whether you're expected a Map<String, List<Student>> or just a List<Student>, nevertheless here are both solutions:

imports:

import static java.util.stream.Collectors.*;
import java.util.*;
import java.util.function.Function;

retrieving a Map<String, List<Student>> where each List<Student> contains students sorted by their ids.

Map<String, List<Student>> resultSet = studlist.stream()
      .collect(groupingBy(Student::getLocation,
             mapping(Function.identity(),
                  collectingAndThen(toList(),
                      e -> e.stream().sorted(Comparator.comparingInt(Student::getId))
                                            .collect(toList())))));

on the other hand, if you want to retrieve just a list of Student objects sorted by a given property then it would be a waste of resources to perform a groupingBy, sorted, collect and somehow reduce the map values into a single list. Rather just sort the Student objects within the list providing a sort key i.e.

studlist.sort(Comparator.comparingInt(Student::getId));

or

studlist.sort(Comparator.comparing(Student::getLocation));

or depending on whether you want to sort by more than one property then you could do something like shmosel's answer.


问:
Using .NET membership provider throughout n-tier web app
I'm currently building an n-tier web application, mainly to practice new technologies and patterns - repositories, uow, services, ioc, ef4 and mvc3.

After lots of hair-pulling I now have ef4 saving my entities through my service layer using repositories.

I'm now starting to define methods I'll need in the service layer and am thinking now's a good time to start implementing authentication. Normally I would roll my own authentication code however I've been told by a friend to try the Membership Provider.

Now obviously I'm going to use this within the mvc3 web app but I'm wondering if I can use this within my service layer as well? Can anyone point me to any articles or blog posts?

NB. Apologies if I'm stating the obvious however I just wanted to be clear that when I'm referring to my service layer, I don't mean WCF; these are my own classes which respect the service layer pattern - http://martinfowler.com/eaaCatalog/serviceLayer.html. Having said that, I may wish to expose this service layer through WCF services at a later date.

I've been googling for a couple of hours now and haven't come up with anything!

Any help is really appreciated.

答:
This is a 18 part series articles from Scott Mitchell.

It's a very deep explanation of all the features that regards Authentication, Authorization and Membership providers in asp.net. I did never found a better source on this from the same author.

You can hide the implementation throgh the usage of the repository pattern as you already do today with EF4 without any particular change

Hope this helps!


问:
Is there better way to create lazy variable initialization?
I want to create code that initialize variable only when I really need it. But initializing in the regular way:

```<code>var = None

if var is None:
    var = factory()
var2 = var
</code>```

Make too much noise in the code.

I tried to create fast solution but I feel there is better option. This is my solution that is fast but can't get parameters and use defaultdict for this.

```<code>def lazy_variable(factory):
    data = defaultdict(factory)
    return lambda: data['']

var = lazy_variable(a_factory)
var2 = var()
</code>```

More questions:

is there fast python container that holds only one variable?

is there a way to return value without calling the function with parenthesis?

EDIT:

Please consider performance. I know i can create a class that can have this behavior, but it slower then the simple solution and also the default dict solution.

trying some of the solutions:

define:

```<code>import cachetools.func
import random

@cachetools.func.lru_cache(None)
def factory(i):
    return random.random()
</code>```

and run:

```<code>%%timeit

for i in xrange(100):
    q = factory(i)
    q = factory(i)
</code>```

got:

```<code>100 loops, best of 3: 2.63 ms per loop
</code>```

naive:

```<code>%%timeit

for i in xrange(100):
    a = None
    if a is None:
        a = random.random()
    q = a
    q = a
</code>```

got:

```<code>The slowest run took 4.71 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.8 µs per loop
</code>```

I'm not sure what was cached

defaultdict solution:

```<code>%%timeit

for i in xrange(100):
    a = lazy_variable(random.random)
    q = a()
    q = a()
</code>```

got:

```<code>The slowest run took 4.11 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 76.3 µs per loop
</code>```

Tnx!

答:
If we're talking about instance variables, then yes - you can write your own wrapper and have it behave the way you want:

```<code>class LazyVar(object):

    def __init__(self, factory, *args, **kwargs):
        self.id = "__value_" + str(id(self))  # internal store
        self.factory = factory
        self.args = args
        self.kwargs = kwargs

    def __get__(self, instance, owner):
        if instance is None:
            return self
        else:
            try:
                return getattr(instance, self.id)
            except AttributeError:
                value = self.factory(*self.args, **self.kwargs)
                setattr(instance, self.id, value)
                return value

def factory(name):
    print("Factory called, initializing: " + name)
    return name.upper()  # just for giggles

class TestClass(object):

    foo = LazyVar(factory, "foo")
    bar = LazyVar(factory, "bar")
</code>```

You can test it as:

```<code>test = TestClass()
print("Foo will get initialized the moment we mention it")
print("Foo's value is:", test.foo)
print("It will also work for referencing, so even tho bar is not initialized...")
another_bar = test.bar
print("It gets initialized the moment we set its value to some other variable")
print("They, of course, have the same value: `{}` vs `{}`".format(test.bar, another_bar))
</code>```

Which will print:

```Foo will get initialized the moment we mention it
Factory called, initializing: foo
Foo's value is: FOO
It will also work for referencing, so even tho bar is not initialized...
Factory called, initializing: bar
It gets initialized the moment we set its value to some other variable
They, of course, have the same value: `BAR` vs `BAR````

Unfortunately, you cannot use the same trick for globally declared variables  as __get__() gets called only when accessed as instance vars.

Body:
I want to create code that initialize variable only when I really need it. But initializing in the regular way:

var = None

if var is None:
    var = factory()
var2 = var

Make too much noise in the code.

I tried to create fast solution but I feel there is better option. This is my solution that is fast but can't get parameters and use defaultdict for this.

def lazy_variable(factory):
    data = defaultdict(factory)
    return lambda: data['']

var = lazy_variable(a_factory)
var2 = var()

More questions:

is there fast python container that holds only one variable?

is there a way to return value without calling the function with parenthesis?

EDIT:

Please consider performance. I know i can create a class that can have this behavior, but it slower then the simple solution and also the default dict solution.

trying some of the solutions:

define:

import cachetools.func
import random

@cachetools.func.lru_cache(None)
def factory(i):
    return random.random()

and run:

%%timeit

for i in xrange(100):
    q = factory(i)
    q = factory(i)

got:

100 loops, best of 3: 2.63 ms per loop

naive:

%%timeit

for i in xrange(100):
    a = None
    if a is None:
        a = random.random()
    q = a
    q = a

got:

The slowest run took 4.71 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.8 µs per loop

I'm not sure what was cached

defaultdict solution:

%%timeit

for i in xrange(100):
    a = lazy_variable(random.random)
    q = a()
    q = a()

got:

The slowest run took 4.11 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 76.3 µs per loop

Tnx!

Body:
If we're talking about instance variables, then yes - you can write your own wrapper and have it behave the way you want:

class LazyVar(object):

    def __init__(self, factory, *args, **kwargs):
        self.id = "__value_" + str(id(self))  # internal store
        self.factory = factory
        self.args = args
        self.kwargs = kwargs

    def __get__(self, instance, owner):
        if instance is None:
            return self
        else:
            try:
                return getattr(instance, self.id)
            except AttributeError:
                value = self.factory(*self.args, **self.kwargs)
                setattr(instance, self.id, value)
                return value

def factory(name):
    print("Factory called, initializing: " + name)
    return name.upper()  # just for giggles

class TestClass(object):

    foo = LazyVar(factory, "foo")
    bar = LazyVar(factory, "bar")

You can test it as:

test = TestClass()
print("Foo will get initialized the moment we mention it")
print("Foo's value is:", test.foo)
print("It will also work for referencing, so even tho bar is not initialized...")
another_bar = test.bar
print("It gets initialized the moment we set its value to some other variable")
print("They, of course, have the same value: `{}` vs `{}`".format(test.bar, another_bar))

Which will print:

Foo will get initialized the moment we mention it
Factory called, initializing: foo
Foo's value is: FOO
It will also work for referencing, so even tho bar is not initialized...
Factory called, initializing: bar
It gets initialized the moment we set its value to some other variable
They, of course, have the same value: `BAR` vs `BAR`

Unfortunately, you cannot use the same trick for globally declared variables  as __get__() gets called only when accessed as instance vars.


问:
Optimise T-sql query
The query I need to develop is to list out sites which have no records (retail transactions) for a given date.  I've been able to accomplish this for a specific site, but I know the query can be written more efficiently using joins but my foray into inners and outers hasn't been much fun.

Here's what I have so far:

```<code>DECLARE @StartDate DATE = '2017-11-01',
    @EndDate DATE = '2017-11-30';

SELECT tx.Txndate, count(*) as txCount
FROM [Report].[dbo].[FactTransactions] tx
where tx.Site = 2
and tx.TxnDate between @StartDate and @EndDate
group by tx.TxnDate
union all
select db.daybookdate, 0 as txCount
from DimDaybook db
where db.daybookdate between @StartDate and @EndDate
and NOT EXISTS (SELECT 1 FROM [Report].[dbo].[FactTransactions] AS t WHERE t.TxnDate = db.daybookdate and t.txndate between @StartDate and @EndDate and t.site = 2)
order by tx.Txndate
</code>```

This returns me the result set for site 2

```<code>Txndate txCount
2017-11-01  1691
2017-11-02  1657
2017-11-03  1835
2017-11-04  1587
2017-11-05  1489
2017-11-06  1544
2017-11-07  1525
2017-11-08  1782
2017-11-09  1848
2017-11-10  1990
2017-11-11  0
2017-11-12  0
</code>```

What I'd really like to have is a result set that looks like this and runs much much quicker than my hack (currently around 2mins - for context the transactions table has 83,486,412 records)

```<code>Site    Date    Transactions
2   11/11/17    0
2   12/11/27    0
3   12/11/17    0
22  1/11/17     0
</code>```

答:
Generate all the rows using a cross join.  Then filter out the ones with data:

```<code>select s.site, db.daybookdate
from DimDaybook db cross join
     (select distinct site
      from [Report].[dbo].[FactTransactions] ft
     ) s
where db.daybookdate between @StartDate and @EndDate and
      not exists (select 1
                  from [Report].[dbo].[FactTransactions] ft
                  where ft.TxnDate = db.daybookdate and
                        ft.site = s.site
                 )
order by tx.Txndate
</code>```

Title: Optimise T-sql query

Body:
The query I need to develop is to list out sites which have no records (retail transactions) for a given date.  I've been able to accomplish this for a specific site, but I know the query can be written more efficiently using joins but my foray into inners and outers hasn't been much fun.

Here's what I have so far:

DECLARE @StartDate DATE = '2017-11-01',
    @EndDate DATE = '2017-11-30';

SELECT tx.Txndate, count(*) as txCount
FROM [Report].[dbo].[FactTransactions] tx
where tx.Site = 2
and tx.TxnDate between @StartDate and @EndDate
group by tx.TxnDate
union all
select db.daybookdate, 0 as txCount
from DimDaybook db
where db.daybookdate between @StartDate and @EndDate
and NOT EXISTS (SELECT 1 FROM [Report].[dbo].[FactTransactions] AS t WHERE t.TxnDate = db.daybookdate and t.txndate between @StartDate and @EndDate and t.site = 2)
order by tx.Txndate

This returns me the result set for site 2

Txndate txCount
2017-11-01  1691
2017-11-02  1657
2017-11-03  1835
2017-11-04  1587
2017-11-05  1489
2017-11-06  1544
2017-11-07  1525
2017-11-08  1782
2017-11-09  1848
2017-11-10  1990
2017-11-11  0
2017-11-12  0

What I'd really like to have is a result set that looks like this and runs much much quicker than my hack (currently around 2mins - for context the transactions table has 83,486,412 records)

Site    Date    Transactions
2   11/11/17    0
2   12/11/27    0
3   12/11/17    0
22  1/11/17     0

Body:
Generate all the rows using a cross join.  Then filter out the ones with data:

select s.site, db.daybookdate
from DimDaybook db cross join
     (select distinct site
      from [Report].[dbo].[FactTransactions] ft
     ) s
where db.daybookdate between @StartDate and @EndDate and
      not exists (select 1
                  from [Report].[dbo].[FactTransactions] ft
                  where ft.TxnDate = db.daybookdate and
                        ft.site = s.site
                 )
order by tx.Txndate


问:
css of
 is lost when a .net page is postBack
I have a html list and in each tag  place an icon, the user selects an icon and I get the value that I assign to the icon and the option that the user selects (icon) I highlight it with css styles, the problem I have is that when the form was sent, if the FieldValidator is activated by any field, data is not sent to the DB but the styles of the selected icon are lost. How to preserve the styles?

This is what it looks like when the icon is selected

and this is what it looks like when the data is sent the requiredField validator is activated and returns to the page again to show the wrong fields and the css is lost since the icon does not appear selected again

        $(document).ready(function () {

            var iconos = document.querySelectorAll('.fa');

            var input = document.getElementById('<%=txtIcono.ClientID%>');

            for (var i = 0; i < iconos.length; i++) {

                iconos[i].addEventListener('click', function () {

                    input.value = this.className;
                });
            }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.list-unstyled {
    padding-left: 0;
    list-style: none;
}

.list-inline li {
    display: inline-block;
    padding-right: 5px;
    padding-left: 5px;
    margin-bottom: 10px;
}

.social-icons .fa {
    font-size: 1em;
}

.social-icons .fa {
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    color: #FFF;
    -webkit-transition: all 0.3s ease-in-out;
    -moz-transition: all 0.3s ease-in-out;
    -ms-transition: all 0.3s ease-in-out;
    -o-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
}

.social-icons.icon-circle .fa {
    border-radius: 50%;
}

.social-icons.icon-rounded .fa {
    border-radius: 5px;
}

.social-icons.icon-flat .fa {
    border-radius: 0;
}

.social-icons .fa:hover, .social-icons .fa:active {
    background-color: blue;
    color: #FFF;
    -webkit-box-shadow: 1px 1px 3px #333;
    -moz-box-shadow: 1px 1px 3px #333;
    box-shadow: 1px 1px 3px #333;
}

.social-icons.icon-zoom .fa:hover, .social-icons.icon-zoom .fa:active {
    -webkit-transform: scale(1.1);
    -moz-transform: scale(1.1);
    -ms-transform: scale(1.1);
    -o-transform: scale(1.1);
    transform: scale(1.1);
}

.social-icons.icon-rotate .fa:hover, .social-icons.icon-rotate .fa:active {
    -webkit-transform: scale(1.1) rotate(360deg);
    -moz-transform: scale(1.1) rotate(360deg);
    -ms-transform: scale(1.1) rotate(360deg);
    -o-transform: scale(1.1) rotate(360deg);
    transform: scale(1.1) rotate(360deg);
}

.enlace > a:focus .fa {
    cursor: pointer;
    background-color: gold;
    border-radius: 50%;
}</code>```

                            Seleccione un Icono:

                                <asp:TextBox runat="server" ID="txtIcono" MaxLength="100" SkinID="txtGral" Width="168px" hidden="true"></asp:TextBox>
                                <asp:RequiredFieldValidator runat="server" ID="rfIcono" ControlToValidate="txtIcono" ErrorMessage="*Seleccione un icono para el anuncio." Display="Dynamic">*</asp:RequiredFieldValidator>

```

答:
Some pseudo code.
file.aspx:

```<code><%-- add hf --%>
<asp:HiddenField ID="hfID" runat="server">
</code>```

file.js:

```<code>function onIconClick() {
//highlight Icon
var hf =document.getElementByID("hfID");
hf.value = hf.value + ";clickedIcon"
}
function onPageLoad() {
var hf =document.getElementByID("hfID");
var iconsToHighlight = hf.value.split(";");
for(i=0;i<iconsToHighlight. Length;i++) {
HighlightIcon(iconsToHighlight[i]) ;
}
}
</code>```

I'm not sure but you might have to add the tag asp:scriptmanager to make the on pageload to work. Or if you use jquery i think its automatically included but don't take my word on it

Title: css of <ul> is lost when a .net page is postBack

Body:
I have a html list and in each tag  place an icon, the user selects an icon and I get the value that I assign to the icon and the option that the user selects (icon) I highlight it with css styles, the problem I have is that when the form was sent, if the FieldValidator is activated by any field, data is not sent to the DB but the styles of the selected icon are lost. How to preserve the styles?

This is what it looks like when the icon is selected

and this is what it looks like when the data is sent the requiredField validator is activated and returns to the page again to show the wrong fields and the css is lost since the icon does not appear selected again

        $(document).ready(function () {

            var iconos = document.querySelectorAll('.fa');

            var input = document.getElementById('<%=txtIcono.ClientID%>');

            for (var i = 0; i < iconos.length; i++) {

                iconos[i].addEventListener('click', function () {

                    input.value = this.className;
                });
            }

.list-unstyled {
    padding-left: 0;
    list-style: none;
}

.list-inline li {
    display: inline-block;
    padding-right: 5px;
    padding-left: 5px;
    margin-bottom: 10px;
}

.social-icons .fa {
    font-size: 1em;
}

.social-icons .fa {
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    color: #FFF;
    -webkit-transition: all 0.3s ease-in-out;
    -moz-transition: all 0.3s ease-in-out;
    -ms-transition: all 0.3s ease-in-out;
    -o-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
}

.social-icons.icon-circle .fa {
    border-radius: 50%;
}

.social-icons.icon-rounded .fa {
    border-radius: 5px;
}

.social-icons.icon-flat .fa {
    border-radius: 0;
}

.social-icons .fa:hover, .social-icons .fa:active {
    background-color: blue;
    color: #FFF;
    -webkit-box-shadow: 1px 1px 3px #333;
    -moz-box-shadow: 1px 1px 3px #333;
    box-shadow: 1px 1px 3px #333;
}

.social-icons.icon-zoom .fa:hover, .social-icons.icon-zoom .fa:active {
    -webkit-transform: scale(1.1);
    -moz-transform: scale(1.1);
    -ms-transform: scale(1.1);
    -o-transform: scale(1.1);
    transform: scale(1.1);
}

.social-icons.icon-rotate .fa:hover, .social-icons.icon-rotate .fa:active {
    -webkit-transform: scale(1.1) rotate(360deg);
    -moz-transform: scale(1.1) rotate(360deg);
    -ms-transform: scale(1.1) rotate(360deg);
    -o-transform: scale(1.1) rotate(360deg);
    transform: scale(1.1) rotate(360deg);
}

.enlace > a:focus .fa {
    cursor: pointer;
    background-color: gold;
    border-radius: 50%;
}

                            Seleccione un Icono:

                                <asp:TextBox runat="server" ID="txtIcono" MaxLength="100" SkinID="txtGral" Width="168px" hidden="true"></asp:TextBox>
                                <asp:RequiredFieldValidator runat="server" ID="rfIcono" ControlToValidate="txtIcono" ErrorMessage="*Seleccione un icono para el anuncio." Display="Dynamic">*</asp:RequiredFieldValidator>

Body:
Some pseudo code.
file.aspx:

<%-- add hf --%>
<asp:HiddenField ID="hfID" runat="server">

file.js:

function onIconClick() {
//highlight Icon
var hf =document.getElementByID("hfID");
hf.value = hf.value + ";clickedIcon"
}
function onPageLoad() {
var hf =document.getElementByID("hfID");
var iconsToHighlight = hf.value.split(";");
for(i=0;i<iconsToHighlight. Length;i++) {
HighlightIcon(iconsToHighlight[i]) ;
}
}

I'm not sure but you might have to add the tag asp:scriptmanager to make the on pageload to work. Or if you use jquery i think its automatically included but don't take my word on it


问:
looking for direction with basic grep function in R (incorporated into a function)
Help with the following function. I am trying to create a function that will take values (from 'years')  and run a simple grep on a data.frame(searches).

The data.frame(searches) looks like;

```<code>> data.table(searches)[53:58]
         date hits    keyword          geo gprop   category
1: 2014-01-05   34 Price world             web        0
2: 2014-01-12   25 Price world             web        0
3: 2014-01-19   44 Price world             web        0
4: 2014-01-26   30 Price world             web        0
5: 2014-02-02   31 Price world             web        0
6: 2014-02-09   29 Price world             web        0
</code>```

I am trying to extract each year, 2013, 2014, 2015 etc. at the moment using the grep function and save just the columns from the above data.frame "date" and "hits".

The code I currently have is;

```<code>years <- c("2013", "2014", "2015", "2016", "2017")

func_src <- for(i in ncol(1:5)){

  func_src[i] <- searches[grep(years(ncol[1:5]), searches$date),]
  print(func_src[i])
}
</code>```

This returns a NULL value.

The final output I am hoping to obtain would have something like

```<code>colnames <- date hits1 hits2 hits3 hits4
</code>```

(I am tidying the data based on date and not keyword as the keyword can change based on previous inputs, i.e. "sell world" and the date 2014, 2015, 2016 does not change)

EDIT: For clarification I paste in all the code and add in further comments.

The following code should get you to where I am at (it is just test data/var names so the number of hits = 0 does not matter).

```<code>library(gtrendsR)

Variable_names <- c("VAR1")

keywords <- c("US news", "", "Canada News", "US Car news", "Canada Car news")

trends <- apply(expand.grid(Variable_names, keywords), 1, paste, collapse=" ")
trends

searches <- gtrends(trends)$interest_over_time
searches <- searches[-c(1:4), ]

years <- c("2013", "2014", "2015", "2016", "2017")
</code>```

After running this code, I hope to apply a function which will split across different years, 2013, 2014, 2015 etc. I have each keyword from 2013:2017 and I am only interested in keeping the date column and hits column. so;

I am trying to create a data.frame to have a date column, and then split on each row once we have reached the end of 2017 (as thats when a new keyword would come into play).

Ultimately I am trying to acheive

```<code>date hits1 hits2 hits3 hits4
</code>```

each hits column would also correspond to each "keyword" in the keywords dataframe (but I am trying to split on year and not keyword)

hope this makes what I am trying to do a little clearer.

答:
Your code does not define a function, and, as written, it should not run. ncol is not  a defined variable, and yet you subset it (ncol[1:5]). See some example code below which is syntatically valid and will iteratively search for the years listed:

```<code>years <- c("2013", "2014", "2015", "2016", "2017")
## Define a list to store the results
year_results <- list()
## A simple function which "greps" for the year and returns all results
func_src <- function(year) {
    searches[grep(year, searches$date), ]
}
## You can simply iterate through the vector "years"
for (year in years) {
    ## Store the result with the year as a name
    year_results[[year]]  <- func_src(year)
}
print(year_results)
</code>```

Alternatively you can use the lapply function, which will iterate over the years and store the result in a list:

```<code>lapply(years, func_src)
</code>```

And if you want a named list:

```<code>setNames(lapply(years, func_src), years)
</code>```

Body:
Help with the following function. I am trying to create a function that will take values (from 'years')  and run a simple grep on a data.frame(searches).

The data.frame(searches) looks like;

> data.table(searches)[53:58]
         date hits    keyword          geo gprop   category
1: 2014-01-05   34 Price world             web        0
2: 2014-01-12   25 Price world             web        0
3: 2014-01-19   44 Price world             web        0
4: 2014-01-26   30 Price world             web        0
5: 2014-02-02   31 Price world             web        0
6: 2014-02-09   29 Price world             web        0

I am trying to extract each year, 2013, 2014, 2015 etc. at the moment using the grep function and save just the columns from the above data.frame "date" and "hits".

The code I currently have is;

years <- c("2013", "2014", "2015", "2016", "2017")

func_src <- for(i in ncol(1:5)){

  func_src[i] <- searches[grep(years(ncol[1:5]), searches$date),]
  print(func_src[i])
}

This returns a NULL value.

The final output I am hoping to obtain would have something like

colnames <- date hits1 hits2 hits3 hits4

(I am tidying the data based on date and not keyword as the keyword can change based on previous inputs, i.e. "sell world" and the date 2014, 2015, 2016 does not change)

EDIT: For clarification I paste in all the code and add in further comments.

The following code should get you to where I am at (it is just test data/var names so the number of hits = 0 does not matter).

library(gtrendsR)

Variable_names <- c("VAR1")

keywords <- c("US news", "", "Canada News", "US Car news", "Canada Car news")

trends <- apply(expand.grid(Variable_names, keywords), 1, paste, collapse=" ")
trends

searches <- gtrends(trends)$interest_over_time
searches <- searches[-c(1:4), ]

years <- c("2013", "2014", "2015", "2016", "2017")

After running this code, I hope to apply a function which will split across different years, 2013, 2014, 2015 etc. I have each keyword from 2013:2017 and I am only interested in keeping the date column and hits column. so;

I am trying to create a data.frame to have a date column, and then split on each row once we have reached the end of 2017 (as thats when a new keyword would come into play).

Ultimately I am trying to acheive

date hits1 hits2 hits3 hits4

each hits column would also correspond to each "keyword" in the keywords dataframe (but I am trying to split on year and not keyword)

hope this makes what I am trying to do a little clearer.

Body:
Your code does not define a function, and, as written, it should not run. ncol is not  a defined variable, and yet you subset it (ncol[1:5]). See some example code below which is syntatically valid and will iteratively search for the years listed:

years <- c("2013", "2014", "2015", "2016", "2017")
## Define a list to store the results
year_results <- list()
## A simple function which "greps" for the year and returns all results
func_src <- function(year) {
    searches[grep(year, searches$date), ]
}
## You can simply iterate through the vector "years"
for (year in years) {
    ## Store the result with the year as a name
    year_results[[year]]  <- func_src(year)
}
print(year_results)

Alternatively you can use the lapply function, which will iterate over the years and store the result in a list:

lapply(years, func_src)

And if you want a named list:

setNames(lapply(years, func_src), years)


问:
How to pull a specific piece of json from an array
I am currently using an API for steam prices and I am wondering how I can pull one specific piece of this file for example:

```<code>{"60's Army Jacket":"4.49","Addicted Guitarist":"3.13","Agony Yellow":"0.92","Aircraft Parts AK47":"0.89",
</code>```

Just the prices of the item and not the market name, I am very new to this so I don't know for sure I tried a different method but I got lost and it was not working as planned so if I can be provided with resources or assistance that would be great <3.

答:
Here you go:

const data = ({"60's Army Jacket":"4.49","Addicted Guitarist":"3.13","Agony Yellow":"0.92","Aircraft Parts AK47":"0.89"});
var extractedData = [];

for (const item in data) {
   if (data.hasOwnProperty(item)) {
       extractedData.push(data[item]);
   }
}

console.log(extractedData);```
</div>
</div>
</p>

<p>Updated from comment:</p>

```const extractedValue = Object.values(data);
```

Body:
I am currently using an API for steam prices and I am wondering how I can pull one specific piece of this file for example:

{"60's Army Jacket":"4.49","Addicted Guitarist":"3.13","Agony Yellow":"0.92","Aircraft Parts AK47":"0.89",

Just the prices of the item and not the market name, I am very new to this so I don't know for sure I tried a different method but I got lost and it was not working as planned so if I can be provided with resources or assistance that would be great <3.

Body:
Here you go:

const data = ({"60's Army Jacket":"4.49","Addicted Guitarist":"3.13","Agony Yellow":"0.92","Aircraft Parts AK47":"0.89"});
var extractedData = [];

for (const item in data) {
   if (data.hasOwnProperty(item)) {
       extractedData.push(data[item]);
   }
}

console.log(extractedData);

Updated from comment:

const extractedValue = Object.values(data);


问:
How to initialize an object using async-await pattern
I'm trying to follow RAII pattern in my service classes, meaning that when an object is constructed, it is fully initialized. However, I'm facing difficulties with asynchronous APIs. The structure of class in question looks like following

```<code>class ServiceProvider : IServiceProvider // Is only used through this interface
{
    public int ImportantValue { get; set; }
    public event EventHandler ImportantValueUpdated;

    public ServiceProvider(IDependency1 dep1, IDependency2 dep2)
    {
        // IDependency1 provide an input value to calculate ImportantValue
        // IDependency2 provide an async algorithm to calculate ImportantValue
    }
}
</code>```

I'm also targeting to get rid of side-effects in ImportantValue getter, to make it thread-safe.

Now users of ServiceProvider will create an instance of it, subscribe to an event of ImportantValue change, and get the initial ImportantValue. And here comes the problem, with the initial value. Since the ImportantValue is calculated asynchronously, the class cannot be fully initialized in constructor. It may be okay to have this value as null initially, but then I need to have some place where it will be calculated first time. A natural place for that could be the ImportantValue's getter, but I'm targeting to make it thread-safe and with no side-effects.

So I'm basically stuck with these contradictions. Could you please help me and offer some alternative? Having value initialized in constructor while nice is not really necessary, but no side-effects and thread-safety of property is mandatory.

Thanks in advance.

EDIT: One more thing to add. I'm using Ninject for instantiation, and as far as I understand, it doesn't support async methods to create a binding. While approach with initiating some Task-based operation in constructor will work, I cannot await its result.

I.e. two next approaches (offered as answers so far) will not compile, since Task is returned, not my object:

```<code>Kernel.Bind<IServiceProvider>().ToMethod(async ctx => await ServiceProvider.CreateAsync())
</code>```

or

```<code>Kernel.Bind<IServiceProvider>().ToMethod(async ctx =>
{
    var sp = new ServiceProvider();
    await sp.InitializeAsync();
})
</code>```

Simple binding will work, but I'm not awaiting the result of asynchronous initialization started in constructor, as proposed by Stephen Cleary:

```<code>Kernel.Bind<IServiceProvider>().To<ServiceProvider>();
</code>```

... and that's not looking good for me.

答:
This is a slight modification to @StephenCleary pattern of async initialization.

The difference being the caller doesn't need to 'remember' to await the InitializationTask, or even know anything about the initializationTask (in fact it is now changed to private).

The way it works is that in every method that uses the initialized data there is an initial call to await _initializationTask. This returns instantly the second time around - because the _initializationTask object itself will have a boolean set (IsCompleted which the 'await' mechanism checks) - so don't worry about it initializing multiple times.

The only catch I'm aware of is you mustn't forget to call it in every method that uses the data.

```<code>public sealed class MyType
{
    public MyType()
    {
        _initializationTask = InitializeAsync();
    }

    private Task _initializationTask;

    private async Task InitializeAsync()
    {
        // Asynchronously initialize this instance.
        _customers = await LoadCustomersAsync();
    }

    public async Task<Customer> LookupCustomer(string name)
    {
         // Waits to ensure the class has been initialized properly
         // The task will only ever run once, triggered initially by the constructor
         // If the task failed this will raise an exception
         // Note: there are no () since this is not a method call
         await _initializationTask;

         return _customers[name];
    }

    // one way of clearing the cache
    public void ClearCache()
    {
         InitializeAsync();
    }

    // another approach to clearing the cache, will wait until complete
    // I don't really see a benefit to this method since any call using the
    // data (like LookupCustomer) will await the initialization anyway
    public async Task ClearCache2()
    {
         await InitializeAsync();
    }
 }
</code>```

Body:
I'm trying to follow RAII pattern in my service classes, meaning that when an object is constructed, it is fully initialized. However, I'm facing difficulties with asynchronous APIs. The structure of class in question looks like following

class ServiceProvider : IServiceProvider // Is only used through this interface
{
    public int ImportantValue { get; set; }
    public event EventHandler ImportantValueUpdated;

    public ServiceProvider(IDependency1 dep1, IDependency2 dep2)
    {
        // IDependency1 provide an input value to calculate ImportantValue
        // IDependency2 provide an async algorithm to calculate ImportantValue
    }
}

I'm also targeting to get rid of side-effects in ImportantValue getter, to make it thread-safe.

Now users of ServiceProvider will create an instance of it, subscribe to an event of ImportantValue change, and get the initial ImportantValue. And here comes the problem, with the initial value. Since the ImportantValue is calculated asynchronously, the class cannot be fully initialized in constructor. It may be okay to have this value as null initially, but then I need to have some place where it will be calculated first time. A natural place for that could be the ImportantValue's getter, but I'm targeting to make it thread-safe and with no side-effects.

So I'm basically stuck with these contradictions. Could you please help me and offer some alternative? Having value initialized in constructor while nice is not really necessary, but no side-effects and thread-safety of property is mandatory.

Thanks in advance.

EDIT: One more thing to add. I'm using Ninject for instantiation, and as far as I understand, it doesn't support async methods to create a binding. While approach with initiating some Task-based operation in constructor will work, I cannot await its result.

I.e. two next approaches (offered as answers so far) will not compile, since Task is returned, not my object:

Kernel.Bind<IServiceProvider>().ToMethod(async ctx => await ServiceProvider.CreateAsync())

or

Kernel.Bind<IServiceProvider>().ToMethod(async ctx =>
{
    var sp = new ServiceProvider();
    await sp.InitializeAsync();
})

Simple binding will work, but I'm not awaiting the result of asynchronous initialization started in constructor, as proposed by Stephen Cleary:

Kernel.Bind<IServiceProvider>().To<ServiceProvider>();

... and that's not looking good for me.

Body:
This is a slight modification to @StephenCleary pattern of async initialization.

The difference being the caller doesn't need to 'remember' to await the InitializationTask, or even know anything about the initializationTask (in fact it is now changed to private).

The way it works is that in every method that uses the initialized data there is an initial call to await _initializationTask. This returns instantly the second time around - because the _initializationTask object itself will have a boolean set (IsCompleted which the 'await' mechanism checks) - so don't worry about it initializing multiple times.

The only catch I'm aware of is you mustn't forget to call it in every method that uses the data.

public sealed class MyType
{
    public MyType()
    {
        _initializationTask = InitializeAsync();
    }

    private Task _initializationTask;

    private async Task InitializeAsync()
    {
        // Asynchronously initialize this instance.
        _customers = await LoadCustomersAsync();
    }

    public async Task<Customer> LookupCustomer(string name)
    {
         // Waits to ensure the class has been initialized properly
         // The task will only ever run once, triggered initially by the constructor
         // If the task failed this will raise an exception
         // Note: there are no () since this is not a method call
         await _initializationTask;

         return _customers[name];
    }

    // one way of clearing the cache
    public void ClearCache()
    {
         InitializeAsync();
    }

    // another approach to clearing the cache, will wait until complete
    // I don't really see a benefit to this method since any call using the
    // data (like LookupCustomer) will await the initialization anyway
    public async Task ClearCache2()
    {
         await InitializeAsync();
    }
 }


问:
remove value from string
If I have a string with IDs

```<code>$myIDs = '22,34,445,67889,23';
</code>```

and I am given a value, how do I remove it from the string, assuming I know for sure it is in the string?

```<code>$removeID = '445';
</code>```

Do I user preg_replace or is there a better method? For example, if it is in the middle of the string and I remove just a value, I'll end up with two commas and then I need to replace those with a single comma?

```<code>preg_replace($removeID, '', $myIDs);
</code>```

UPDATE: These are all great suggestions. However, I just thought about one potential issue. This probably need to be handled as an array instead of regex. What is my string looks like this

```<code>$myIDs = '2312,23,234234';
</code>```

and ID to remove

```<code>$removeID = '23';
</code>```

There's too many potential matches...

答:
```<code>$array = explode(',',$myIDs);
$array = array_diff($array,array($removeID));
$output = implode(',',$array);
</code>```

Title: remove value from string

Body:
If I have a string with IDs

$myIDs = '22,34,445,67889,23';

and I am given a value, how do I remove it from the string, assuming I know for sure it is in the string?

$removeID = '445';

Do I user preg_replace or is there a better method? For example, if it is in the middle of the string and I remove just a value, I'll end up with two commas and then I need to replace those with a single comma?

preg_replace($removeID, '', $myIDs);

UPDATE: These are all great suggestions. However, I just thought about one potential issue. This probably need to be handled as an array instead of regex. What is my string looks like this

$myIDs = '2312,23,234234';

and ID to remove

$removeID = '23';

There's too many potential matches...


问:
SSRS 2016 Oracle Date Casting Fails
After upgrading from SSRS 2012 to 2016, we've had to rewrite all of our reports because of an issue with SSRS giving ORA-01830: date format picture ends before converting entire input string.

The code that causes the issue is below:

```<code>WHERE   (
  trunc(date_processed) BETWEEN NVL(:start_date,:subscription_start_date) AND NVL(:end_date,:subscription_end_date)
)
</code>```

Start/End_date are both null at the beginning of the report execution.  subscription_start/end_date is NEVER null and is always set.  To make things even more frustrating, the following works fine:

```<code>WHERE   (
  trunc(date_processed) BETWEEN  NVL(:start_date ,'01-JAN-1848') AND NVL(:end_date,'31-DEC-2039')
  and trunc(date_processed) BETWEEN :subscription_start_date and :subscription_end_date
)
</code>```

The issue, however, is that now the :start_date parameter can not override the subscription date parameter when it is set by the user.

This did not occur on previous versions.  This is happening to ALL reports we have which isn't a few.

答:
Setting the variable parameters in SSRS to text and using TO_DATE resolved similar situations for me using SSRS with an Oracle source.</p>

```<code>WHERE ( trunc(date_processed) BETWEEN NVL(TO_DATE(:start_date,'mm/dd/yyyy'),TO_DATE(:subscription_start_date,'mm/dd/yyyy')) AND NVL(TO_DATE(:end_date,'mm/dd/yyyy'),TO_DATE(:subscription_end_date, 'mm/dd/yyyy') )
</code>```

Title: SSRS 2016 Oracle Date Casting Fails

Body:
After upgrading from SSRS 2012 to 2016, we've had to rewrite all of our reports because of an issue with SSRS giving ORA-01830: date format picture ends before converting entire input string.

The code that causes the issue is below:

WHERE   (
  trunc(date_processed) BETWEEN NVL(:start_date,:subscription_start_date) AND NVL(:end_date,:subscription_end_date)
)

Start/End_date are both null at the beginning of the report execution.  subscription_start/end_date is NEVER null and is always set.  To make things even more frustrating, the following works fine:

WHERE   (
  trunc(date_processed) BETWEEN  NVL(:start_date ,'01-JAN-1848') AND NVL(:end_date,'31-DEC-2039')
  and trunc(date_processed) BETWEEN :subscription_start_date and :subscription_end_date
)

The issue, however, is that now the :start_date parameter can not override the subscription date parameter when it is set by the user.

This did not occur on previous versions.  This is happening to ALL reports we have which isn't a few.

Body:
Setting the variable parameters in SSRS to text and using TO_DATE resolved similar situations for me using SSRS with an Oracle source.

WHERE ( trunc(date_processed) BETWEEN NVL(TO_DATE(:start_date,'mm/dd/yyyy'),TO_DATE(:subscription_start_date,'mm/dd/yyyy')) AND NVL(TO_DATE(:end_date,'mm/dd/yyyy'),TO_DATE(:subscription_end_date, 'mm/dd/yyyy') )


问:
Jenkins 2.0: Running SBT in a docker container
I have the following Jenkinsfile:

```<code>def notifySlack = { String color, String message ->
    slackSend(color: color, message: "${message}: Job ${env.JOB_NAME} [${env.BUILD_NUMBER}] (${env.BUILD_URL})")
}

node {
    try {
        notifySlack('#FFFF00', 'STARTED')
        stage('Checkout project') {
            checkout scm
        }
        scalaImage = docker.image('<myNexus>/centos-sbt:2.11.8')
        stage('Test project') {
            docker.withRegistry('<myNexus>', 'jenkins-nexus') {
                scalaImage.inside('-v /var/lib/jenkins/.ivy2:/root/.ivy2') { c ->
                    sh 'sbt clean test'
                }
            }
        }
        if (env.BRANCH_NAME == 'master') {
            stage('Release new version') {
                docker.withRegistry('<myNexus>', 'jenkins-nexus') {
                    scalaImage.inside('-v /var/lib/jenkins/.ivy2:/root/.ivy2') { c ->
                        sh 'sbt release'
                    }
                }
            }
        }
        notifySlack('#00FF00', 'SUCCESSFUL')
    } catch (e) {
        currentBuild.result = "FAILED"
        notifySlack('#FF0000', 'FAILED')
        throw e
    }

}
</code>```

Unfortunately when I reach the sbt clean test line I end up with the following error:

```<code>java.lang.IllegalArgumentException: URI has a query component
    at java.io.File.<init>(File.java:427)
    at sbt.IO$.uriToFile(IO.scala:160)
    at sbt.IO$.toFile(IO.scala:135)
    at sbt.Classpaths$.sbt$Classpaths$$bootRepository(Defaults.scala:1942)
    at sbt.Classpaths$$anonfun$appRepositories$1.apply(Defaults.scala:1912)
    at sbt.Classpaths$$anonfun$appRepositories$1.apply(Defaults.scala:1912)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:34)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
    at scala.collection.AbstractTraversable.map(Traversable.scala:105)
    at sbt.Classpaths$.appRepositories(Defaults.scala:1912)
    at sbt.Classpaths$$anonfun$58.apply(Defaults.scala:1193)
    at sbt.Classpaths$$anonfun$58.apply(Defaults.scala:1190)
    at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
    at sbt.EvaluateSettings$MixedNode.evaluate0(INode.scala:175)
    at sbt.EvaluateSettings$INode.evaluate(INode.scala:135)
    at sbt.EvaluateSettings$$anonfun$sbt$EvaluateSettings$$submitEvaluate$1.apply$mcV$sp(INode.scala:69)
    at sbt.EvaluateSettings.sbt$EvaluateSettings$$run0(INode.scala:78)
    at sbt.EvaluateSettings$$anon$3.run(INode.scala:74)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

If I run the simple docker run ... followed by docker exec I get what I want but I would like to work with the defined Jenkins functionality.

So this seems to be an SBT issue. I use version 0.13.16 inside the docker image. From what I understand the classpath contains a query parameter that SBT:

doesn't like

doesn't know how to handle

is illegal

I put no such query parameters myself so I thought that this .inside method does that. I checked the env in the container and found a single entry RUN_CHANGES_DISPLAY_URL=<my_ip>/job/scheduler/job/fix-jenkins-pipeline/23/display/redirect?page=changes. I tried to unset it but didn't manage to.

I'm out of ideas and am not really sure I'm in the right direction. Any help would be appreciated.

答:
I spent a lot of time tracing this down through the code.

It looks like the easiest solution is to just pass -Duser.home=<path> to sbt, or to set it in the SBT_OPTS environment variable; then all the rest of the directories will be built as if the <path> is the user's home directory.

Body:
I have the following Jenkinsfile:

def notifySlack = { String color, String message ->
    slackSend(color: color, message: "${message}: Job ${env.JOB_NAME} [${env.BUILD_NUMBER}] (${env.BUILD_URL})")
}

node {
    try {
        notifySlack('#FFFF00', 'STARTED')
        stage('Checkout project') {
            checkout scm
        }
        scalaImage = docker.image('<myNexus>/centos-sbt:2.11.8')
        stage('Test project') {
            docker.withRegistry('<myNexus>', 'jenkins-nexus') {
                scalaImage.inside('-v /var/lib/jenkins/.ivy2:/root/.ivy2') { c ->
                    sh 'sbt clean test'
                }
            }
        }
        if (env.BRANCH_NAME == 'master') {
            stage('Release new version') {
                docker.withRegistry('<myNexus>', 'jenkins-nexus') {
                    scalaImage.inside('-v /var/lib/jenkins/.ivy2:/root/.ivy2') { c ->
                        sh 'sbt release'
                    }
                }
            }
        }
        notifySlack('#00FF00', 'SUCCESSFUL')
    } catch (e) {
        currentBuild.result = "FAILED"
        notifySlack('#FF0000', 'FAILED')
        throw e
    }

}

Unfortunately when I reach the sbt clean test line I end up with the following error:

java.lang.IllegalArgumentException: URI has a query component
    at java.io.File.<init>(File.java:427)
    at sbt.IO$.uriToFile(IO.scala:160)
    at sbt.IO$.toFile(IO.scala:135)
    at sbt.Classpaths$.sbt$Classpaths$$bootRepository(Defaults.scala:1942)
    at sbt.Classpaths$$anonfun$appRepositories$1.apply(Defaults.scala:1912)
    at sbt.Classpaths$$anonfun$appRepositories$1.apply(Defaults.scala:1912)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:34)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
    at scala.collection.AbstractTraversable.map(Traversable.scala:105)
    at sbt.Classpaths$.appRepositories(Defaults.scala:1912)
    at sbt.Classpaths$$anonfun$58.apply(Defaults.scala:1193)
    at sbt.Classpaths$$anonfun$58.apply(Defaults.scala:1190)
    at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
    at sbt.EvaluateSettings$MixedNode.evaluate0(INode.scala:175)
    at sbt.EvaluateSettings$INode.evaluate(INode.scala:135)
    at sbt.EvaluateSettings$$anonfun$sbt$EvaluateSettings$$submitEvaluate$1.apply$mcV$sp(INode.scala:69)
    at sbt.EvaluateSettings.sbt$EvaluateSettings$$run0(INode.scala:78)
    at sbt.EvaluateSettings$$anon$3.run(INode.scala:74)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

If I run the simple docker run ... followed by docker exec I get what I want but I would like to work with the defined Jenkins functionality.

So this seems to be an SBT issue. I use version 0.13.16 inside the docker image. From what I understand the classpath contains a query parameter that SBT:

doesn't like

doesn't know how to handle

is illegal

I put no such query parameters myself so I thought that this .inside method does that. I checked the env in the container and found a single entry RUN_CHANGES_DISPLAY_URL=<my_ip>/job/scheduler/job/fix-jenkins-pipeline/23/display/redirect?page=changes. I tried to unset it but didn't manage to.

I'm out of ideas and am not really sure I'm in the right direction. Any help would be appreciated.


答:
Well you could simply access locals() or globals() and type

```<code>var2 = locals().get('var', factory())
</code>```

but I have never been in a situation where that would be useful, so you should probably evaluate why you want to do what you want to do.

Title: Is there better way to create lazy variable initialization?

Body:
Well you could simply access locals() or globals() and type

var2 = locals().get('var', factory())

but I have never been in a situation where that would be useful, so you should probably evaluate why you want to do what you want to do.