问:
mysql isn't joining data
I get the code to load the pages initially with sports, entertainment and want-ads but when i push the button i get all of the articles instead of the ones that correlate with the page chosen. What i would like to happen is when i push the sports button I get all of the articles related to sports (with no entertainment or want-ad articles).
I have a database with tables as follows:

TABLES ARE AS FOLLOWS:

```<code>PAGES-
pages.pageId(INT),
pages.pageTitle(VARCHAR),

ARTICLES-
articles.acrticleId(INT),
articles.articleTitle(VARCHAR),
articles.pageId(INT),

VIDEOS-
videos.videoId(INT),
videos.videoTitle(VARCHAR),
videos.videoLoc(VARCHAR),
videos.articlesId(INT),

IMAGES-
images.imageId(INT),
images.imageTitle(VARCHAR),
images.imageLoc(VARCHAR),
images.articlesId(INT),

TEXT-
text.textId(INT),
text.text(medium),
text.articlesId(INT),
</code>```

I have a query that brings in all the pages with a while loop:

```<code>$sqlPAQuery = "SELECT pages.pageId, pages.pageTitle, articles.articleId,
articles.articleTitle FROM pages, articles GROUP BY pages.pageTitle";
$paqueryResult = mysqli_query($conn,$sqlPAQuery);

while ($paqueryRow = mysqli_fetch_object($paqueryResult))
{

    $pages = "<a href = articles.php?pageId=".$paqueryRow->pageId." data-
    role='button' ><button id ='wrapper'>".$paqueryRow->pageTitle."</button>
    </a><br/><br/>";
    echo $pages;
}
</code>```

when a button is pushed it brings in this query:

```<code>SELECT pages.pageId, pageTitle, articles.articleId, articles.articleTitle,
GROUP_CONCAT(articleTitle)
FROM articles join pages using (pageId)
GROUP BY pageId
</code>```

the html/javascript to send the info is:

```<code><div data-role="content" >
   <p>Is Nursing For You?</p>
    <br/>
        <div id = "div1" align="center"></div>
</div>

    </div>
<script type='text/javascript'>
$(document).ready(function() {
   $("#div1").load('FONWVhp.php', function() {
       $('#div1 a').button();
 });

$(document).on('click', '#div1 a', function(event){
        event.preventDefault();
       //   alert($(this).attr('href'));
        $("#div1").load(($(this).attr('href')), function() {
            $('#div1 a').button();
        });
    });

    $(document).on('click', '#div1 a', function(event){
        event.preventDefault();
        //alert($(this).attr('href'));
        $("#div1").load(($(this).attr('href')), function() {
            $('#div1 a').button();
        });
    });
});
</code>```

答:
You have to modify your query a little bit, Just you have to do is to add where clause in it. Like this:</p>

```<code>SELECT pages.pageId, pageTitle, articles.articleId, articles.articleTitle
FROM articles join pages using (pageId)
where pageId = 'current_page_id'
</code>```

Title: mysql isn't joining data

Body:
I get the code to load the pages initially with sports, entertainment and want-ads but when i push the button i get all of the articles instead of the ones that correlate with the page chosen. What i would like to happen is when i push the sports button I get all of the articles related to sports (with no entertainment or want-ad articles).
I have a database with tables as follows:

TABLES ARE AS FOLLOWS:

PAGES-
pages.pageId(INT),
pages.pageTitle(VARCHAR),

ARTICLES-
articles.acrticleId(INT),
articles.articleTitle(VARCHAR),
articles.pageId(INT),

VIDEOS-
videos.videoId(INT),
videos.videoTitle(VARCHAR),
videos.videoLoc(VARCHAR),
videos.articlesId(INT),

IMAGES-
images.imageId(INT),
images.imageTitle(VARCHAR),
images.imageLoc(VARCHAR),
images.articlesId(INT),

TEXT-
text.textId(INT),
text.text(medium),
text.articlesId(INT),

I have a query that brings in all the pages with a while loop:

$sqlPAQuery = "SELECT pages.pageId, pages.pageTitle, articles.articleId,
articles.articleTitle FROM pages, articles GROUP BY pages.pageTitle";
$paqueryResult = mysqli_query($conn,$sqlPAQuery);

while ($paqueryRow = mysqli_fetch_object($paqueryResult))
{

    $pages = "pageId." data-
    role='button' ><button id ='wrapper'>".$paqueryRow->pageTitle."</button>

";
    echo $pages;
}

when a button is pushed it brings in this query:

SELECT pages.pageId, pageTitle, articles.articleId, articles.articleTitle,
GROUP_CONCAT(articleTitle)
FROM articles join pages using (pageId)
GROUP BY pageId

the html/javascript to send the info is:

Is Nursing For You?

Body:
You have to modify your query a little bit, Just you have to do is to add where clause in it. Like this:

SELECT pages.pageId, pageTitle, articles.articleId, articles.articleTitle
FROM articles join pages using (pageId)
where pageId = 'current_page_id'


来源: stackexchange

问:
Removing items in list not corresponding to max value in another list
```<code>model_names = ['is1', 'is5', 'is10', 'im1', 'im5', 'im10']
</code>```

As an example,

```<code>models = [0.1, 0.2, 0.1, 0.3, 0.2, 0.3]
</code>```

The maximum of the list is 0.3, which corresponds to model names 'im1' and 'im10'. I'd like the function

```<code>dominant_model(models)
</code>```

to return

```<code>['im1', 'im10']
</code>```

i.e, the most 'dominant' model(s).

Here's my code which does the job, but I'd like to know if there's a shorter way of doing the same thing rather than all of the conditionals:

```<code>def dominant_model(models):
    m = max(models)
    dom_models = [i for i,j in enumerate(models) if j==m]
    for i in range(len(dom_models)):
        if dom_models[i]==0:
            dom_models[i]=model_names[0]
        elif dom_models[i]==1:
            dom_models[i]=model_names[1]
        elif dom_models[i]==2:
            dom_models[i]=model_names[2]
        elif dom_models[i]==3:
            dom_models[i]=model_names[3]
        elif dom_models[i]==4:
            dom_models[i]=model_names[4]
        elif dom_models[i]==5:
            dom_models[i]=model_names[5]
    return dom_models
</code>```

答:
Use two loops:</p>

```<code>def dominant_model(models):
    m = max(models)
    dom_models = [i for i,j in enumerate(models) if j==m]
    for i in range(len(dom_models)):
        for j in range(6):
            if dom_models[i]==j:
                dom_models[i]=model_names[j]
    return dom_models
</code>```

ContentLicense: CC BY-SA 3.0

Body:
model_names = ['is1', 'is5', 'is10', 'im1', 'im5', 'im10']

As an example,

models = [0.1, 0.2, 0.1, 0.3, 0.2, 0.3]

The maximum of the list is 0.3, which corresponds to model names 'im1' and 'im10'. I'd like the function

dominant_model(models)

to return

['im1', 'im10']

i.e, the most 'dominant' model(s).

Here's my code which does the job, but I'd like to know if there's a shorter way of doing the same thing rather than all of the conditionals:

def dominant_model(models):
    m = max(models)
    dom_models = [i for i,j in enumerate(models) if j==m]
    for i in range(len(dom_models)):
        if dom_models[i]==0:
            dom_models[i]=model_names[0]
        elif dom_models[i]==1:
            dom_models[i]=model_names[1]
        elif dom_models[i]==2:
            dom_models[i]=model_names[2]
        elif dom_models[i]==3:
            dom_models[i]=model_names[3]
        elif dom_models[i]==4:
            dom_models[i]=model_names[4]
        elif dom_models[i]==5:
            dom_models[i]=model_names[5]
    return dom_models

Body:
Use two loops:

def dominant_model(models):
    m = max(models)
    dom_models = [i for i,j in enumerate(models) if j==m]
    for i in range(len(dom_models)):
        for j in range(6):
            if dom_models[i]==j:
                dom_models[i]=model_names[j]
    return dom_models


问:
Powershell - Optimize CSV processing with nested JSON
I'm not a developer nor an CSV expert. I was able to put this piece of code     together and it's doing the job.
To give you a quick overview, I needed to process some JSON data that is nested in a CSV. So I'm reading the JSON and I'm splitting it into extra columns, then I'm saving the CSV.

Now, my issue is that although this is working fine, I now need to process a 1.5Gb CSV file and I don't want the processing to take 2 days...

So if you guys could help me tweak my script so that it runs in a reasonable amount of time, I would be extremely grateful :)

```<code>$file = Get-Content -Path 'input.csv' | Select-Object -Skip 2 | ConvertFrom-Csv
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_StreamingEndpointName -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_Id -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_AppServicePlanUri -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_ImageType -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_ServiceType -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_VMName -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_UsageType -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_DatabaseAccount -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_CollectionRid -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_ResourceCategory -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_displayName -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_ACCESSED-VIA-INTERNET' -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_APP-NAME' -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_APP-TYPE' -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_APPTYPE -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_CHARGECODE -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_COMMENTS -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_COUNTRY -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_EY-REGION' -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_IT-ENV' -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_OWNER -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_OWNER-EMAIL' -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_SERVICELINE -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_SUB-TYPE' -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_TECHCONTACTS -value $null

$count=1
ForEach ($line in $file) {
Write-Output "Processing line: $count"
$count++
try{
    if ($line.AdditionalInfo -ne $null -Or $line.Tags -ne $null){
        $line.AdditionalInfo_StreamingEndpointName = ($line.AdditionalInfo | ConvertFrom-JSON).StreamingEndpointName
        $line.AdditionalInfo_Id = ($line.AdditionalInfo | ConvertFrom-JSON).Id
        $line.AdditionalInfo_AppServicePlanUri = ($line.AdditionalInfo | ConvertFrom-JSON).AppServicePlanUri
        $line.AdditionalInfo_ImageType = ($line.AdditionalInfo | ConvertFrom-JSON).ImageType
        $line.AdditionalInfo_ServiceType = ($line.AdditionalInfo | ConvertFrom-JSON).ServiceType
        $line.AdditionalInfo_VMName = ($line.AdditionalInfo | ConvertFrom-JSON).VMName
        $line.AdditionalInfo_UsageType = ($line.AdditionalInfo | ConvertFrom-JSON).UsageType
        $line.AdditionalInfo_DatabaseAccount = ($line.AdditionalInfo | ConvertFrom-JSON).DatabaseAccount
        $line.AdditionalInfo_CollectionRid = ($line.AdditionalInfo | ConvertFrom-JSON).CollectionRid
        $line.AdditionalInfo_ResourceCategory = ($line.AdditionalInfo | ConvertFrom-JSON).ResourceCategory
        $line.Tags_displayName = ($line.Tags | ConvertFrom-JSON).displayName
        $line.'Tags_ACCESSED-VIA-INTERNET' = ($line.Tags | ConvertFrom-JSON).'ACCESSED-VIA-INTERNET'
        $line.'Tags_APP-NAME' = ($line.Tags | ConvertFrom-JSON).'APP-NAME'
        $line.'Tags_APP-TYPE' = ($line.Tags | ConvertFrom-JSON).'APP-TYPE'
        $line.Tags_APPTYPE = ($line.Tags | ConvertFrom-JSON).APPTYPE
        $line.Tags_CHARGECODE = ($line.Tags | ConvertFrom-JSON).CHARGECODE
        $line.Tags_COMMENTS = ($line.Tags | ConvertFrom-JSON).COMMENTS
        $line.Tags_COUNTRY = ($line.Tags | ConvertFrom-JSON).COUNTRY
        $line.'Tags_EY-REGION' = ($line.Tags | ConvertFrom-JSON).'EY-REGION'
        $line.'Tags_IT-ENV' = ($line.Tags | ConvertFrom-JSON).'IT-ENV'
        $line.Tags_OWNER = ($line.Tags | ConvertFrom-JSON).OWNER
        $line.'Tags_OWNER-EMAIL' = ($line.Tags | ConvertFrom-JSON).'OWNER-EMAIL'
        $line.Tags_SERVICELINE = ($line.Tags | ConvertFrom-JSON).SERVICELINE
        $line.'Tags_SUB-TYPE' = ($line.Tags | ConvertFrom-JSON).'SUB-TYPE'
        $line.Tags_TECHCONTACTS = ($line.Tags | ConvertFrom-JSON).TECHCONTACTS
        }
    }
    catch {}
}

#write-output $info
$file | Export-Csv 'C:\output.csv' -NoTypeInformation
</code>```

答:
Add-Member has terrible performance.  So does saving everything to variables over and over.  You might have better luck just keeping everything in a single pipeline and using Select-Object with computed properties:

```<code>Get-Content -Path 'input.csv' |
    Select-Object -Skip 2 |
    ConvertFrom-Csv |
    Select-Object -ErrorAction SilentlyContinue -Property *,
        @{n = 'AdditionalInfo_StreamingEndpointName' ; e = {($_.AdditionalInfo | ConvertFrom-JSON).StreamingEndpointName}},
        @{n = 'AdditionalInfo_Id'                    ; e = {($_.AdditionalInfo | ConvertFrom-JSON).Id}},
        @{n = 'AdditionalInfo_AppServicePlanUri'     ; e = {($_.AdditionalInfo | ConvertFrom-JSON).AppServicePlanUri}},
        @{n = 'AdditionalInfo_ImageType'             ; e = {($_.AdditionalInfo | ConvertFrom-JSON).ImageType}},
        @{n = 'AdditionalInfo_ServiceType'           ; e = {($_.AdditionalInfo | ConvertFrom-JSON).ServiceType}},
        @{n = 'AdditionalInfo_VMName'                ; e = {($_.AdditionalInfo | ConvertFrom-JSON).VMName}},
        @{n = 'AdditionalInfo_UsageType'             ; e = {($_.AdditionalInfo | ConvertFrom-JSON).UsageType}},
        @{n = 'AdditionalInfo_DatabaseAccount'       ; e = {($_.AdditionalInfo | ConvertFrom-JSON).DatabaseAccount}},
        @{n = 'AdditionalInfo_CollectionRid'         ; e = {($_.AdditionalInfo | ConvertFrom-JSON).CollectionRid}},
        @{n = 'AdditionalInfo_ResourceCategory'      ; e = {($_.AdditionalInfo | ConvertFrom-JSON).ResourceCategory}},
        @{n = 'Tags_displayName'                     ; e = {($_.Tags | ConvertFrom-JSON).displayName}},
        @{n = 'Tags_ACCESSED-VIA-INTERNET'           ; e = {($_.Tags | ConvertFrom-JSON).'ACCESSED-VIA-INTERNET'}},
        @{n = 'Tags_APP-NAME'                        ; e = {($_.Tags | ConvertFrom-JSON).'APP-NAME'}},
        @{n = 'Tags_APP-TYPE'                        ; e = {($_.Tags | ConvertFrom-JSON).'APP-TYPE'}},
        @{n = 'Tags_APPTYPE'                         ; e = {($_.Tags | ConvertFrom-JSON).APPTYPE}},
        @{n = 'Tags_CHARGECODE'                      ; e = {($_.Tags | ConvertFrom-JSON).CHARGECODE}},
        @{n = 'Tags_COMMENTS'                        ; e = {($_.Tags | ConvertFrom-JSON).COMMENTS}},
        @{n = 'Tags_COUNTRY'                         ; e = {($_.Tags | ConvertFrom-JSON).COUNTRY}},
        @{n = 'Tags_EY-REGION'                       ; e = {($_.Tags | ConvertFrom-JSON).'EY-REGION'}},
        @{n = 'Tags_IT-ENV'                          ; e = {($_.Tags | ConvertFrom-JSON).'IT-ENV'}},
        @{n = 'Tags_OWNER'                           ; e = {($_.Tags | ConvertFrom-JSON).OWNER}},
        @{n = 'Tags_OWNER-EMAIL'                     ; e = {($_.Tags | ConvertFrom-JSON).'OWNER-EMAIL'}},
        @{n = 'Tags_SERVICELINE'                     ; e = {($_.Tags | ConvertFrom-JSON).SERVICELINE}},
        @{n = 'Tags_SUB-TYPE'                        ; e = {($_.Tags | ConvertFrom-JSON).'SUB-TYPE'}},
        @{n = 'Tags_TECHCONTACTS'                    ; e = {($_.Tags | ConvertFrom-JSON).TECHCONTACTS}} |
    Export-Csv 'C:\output.csv' -NoTypeInformation
</code>```

It might also be faster to say:

```<code>Get-Content -Path 'input.csv' |
    Select-Object -Skip 2 |
    ConvertFrom-Csv |
    ForEach-Object {
        $AdditionalInfo = $_.AdditionalInfo | ConvertFrom-Json;
        $Tags = $_.Tags | ConvertFrom-Json;
        $_ | Select-Object -Property *,
            @{n = 'AdditionalInfo_StreamingEndpointName' ; e = {$AdditionalInfo.StreamingEndpointName}},
            @{n = 'AdditionalInfo_Id'                    ; e = {$AdditionalInfo.Id}},
            ...
    } | Export-Csv ...
</code>```

That way you're only converting the JSON once per line.

However, I suspect to get decent performance you'll have to write something using .Net methods.  I'd suggest using Microsoft.VisualBasic.FileIO.TextFieldParser to parse the CSV for you line by line and possibly JSON.Net to deserialize the JSON with JsonConvert.DeserializeObject().  Even then, this isn't going to be super fast.  1.5 GB of has got to be several million lines.  You may be better off to import the whole CSV into SQL Server 2016+ and use a query there with the built-in JSON parsing.

Body:
I'm not a developer nor an CSV expert. I was able to put this piece of code     together and it's doing the job.
To give you a quick overview, I needed to process some JSON data that is nested in a CSV. So I'm reading the JSON and I'm splitting it into extra columns, then I'm saving the CSV.

Now, my issue is that although this is working fine, I now need to process a 1.5Gb CSV file and I don't want the processing to take 2 days...

So if you guys could help me tweak my script so that it runs in a reasonable amount of time, I would be extremely grateful :)

$file = Get-Content -Path 'input.csv' | Select-Object -Skip 2 | ConvertFrom-Csv
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_StreamingEndpointName -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_Id -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_AppServicePlanUri -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_ImageType -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_ServiceType -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_VMName -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_UsageType -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_DatabaseAccount -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_CollectionRid -value $null
$file | Add-Member -MemberType NoteProperty -Name AdditionalInfo_ResourceCategory -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_displayName -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_ACCESSED-VIA-INTERNET' -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_APP-NAME' -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_APP-TYPE' -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_APPTYPE -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_CHARGECODE -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_COMMENTS -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_COUNTRY -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_EY-REGION' -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_IT-ENV' -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_OWNER -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_OWNER-EMAIL' -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_SERVICELINE -value $null
$file | Add-Member -MemberType NoteProperty -Name 'Tags_SUB-TYPE' -value $null
$file | Add-Member -MemberType NoteProperty -Name Tags_TECHCONTACTS -value $null

$count=1
ForEach ($line in $file) {
Write-Output "Processing line: $count"
$count++
try{
    if ($line.AdditionalInfo -ne $null -Or $line.Tags -ne $null){
        $line.AdditionalInfo_StreamingEndpointName = ($line.AdditionalInfo | ConvertFrom-JSON).StreamingEndpointName
        $line.AdditionalInfo_Id = ($line.AdditionalInfo | ConvertFrom-JSON).Id
        $line.AdditionalInfo_AppServicePlanUri = ($line.AdditionalInfo | ConvertFrom-JSON).AppServicePlanUri
        $line.AdditionalInfo_ImageType = ($line.AdditionalInfo | ConvertFrom-JSON).ImageType
        $line.AdditionalInfo_ServiceType = ($line.AdditionalInfo | ConvertFrom-JSON).ServiceType
        $line.AdditionalInfo_VMName = ($line.AdditionalInfo | ConvertFrom-JSON).VMName
        $line.AdditionalInfo_UsageType = ($line.AdditionalInfo | ConvertFrom-JSON).UsageType
        $line.AdditionalInfo_DatabaseAccount = ($line.AdditionalInfo | ConvertFrom-JSON).DatabaseAccount
        $line.AdditionalInfo_CollectionRid = ($line.AdditionalInfo | ConvertFrom-JSON).CollectionRid
        $line.AdditionalInfo_ResourceCategory = ($line.AdditionalInfo | ConvertFrom-JSON).ResourceCategory
        $line.Tags_displayName = ($line.Tags | ConvertFrom-JSON).displayName
        $line.'Tags_ACCESSED-VIA-INTERNET' = ($line.Tags | ConvertFrom-JSON).'ACCESSED-VIA-INTERNET'
        $line.'Tags_APP-NAME' = ($line.Tags | ConvertFrom-JSON).'APP-NAME'
        $line.'Tags_APP-TYPE' = ($line.Tags | ConvertFrom-JSON).'APP-TYPE'
        $line.Tags_APPTYPE = ($line.Tags | ConvertFrom-JSON).APPTYPE
        $line.Tags_CHARGECODE = ($line.Tags | ConvertFrom-JSON).CHARGECODE
        $line.Tags_COMMENTS = ($line.Tags | ConvertFrom-JSON).COMMENTS
        $line.Tags_COUNTRY = ($line.Tags | ConvertFrom-JSON).COUNTRY
        $line.'Tags_EY-REGION' = ($line.Tags | ConvertFrom-JSON).'EY-REGION'
        $line.'Tags_IT-ENV' = ($line.Tags | ConvertFrom-JSON).'IT-ENV'
        $line.Tags_OWNER = ($line.Tags | ConvertFrom-JSON).OWNER
        $line.'Tags_OWNER-EMAIL' = ($line.Tags | ConvertFrom-JSON).'OWNER-EMAIL'
        $line.Tags_SERVICELINE = ($line.Tags | ConvertFrom-JSON).SERVICELINE
        $line.'Tags_SUB-TYPE' = ($line.Tags | ConvertFrom-JSON).'SUB-TYPE'
        $line.Tags_TECHCONTACTS = ($line.Tags | ConvertFrom-JSON).TECHCONTACTS
        }
    }
    catch {}
}

#write-output $info
$file | Export-Csv 'C:\output.csv' -NoTypeInformation

Body:
Add-Member has terrible performance.  So does saving everything to variables over and over.  You might have better luck just keeping everything in a single pipeline and using Select-Object with computed properties:

Get-Content -Path 'input.csv' |
    Select-Object -Skip 2 |
    ConvertFrom-Csv |
    Select-Object -ErrorAction SilentlyContinue -Property *,
        @{n = 'AdditionalInfo_StreamingEndpointName' ; e = {($_.AdditionalInfo | ConvertFrom-JSON).StreamingEndpointName}},
        @{n = 'AdditionalInfo_Id'                    ; e = {($_.AdditionalInfo | ConvertFrom-JSON).Id}},
        @{n = 'AdditionalInfo_AppServicePlanUri'     ; e = {($_.AdditionalInfo | ConvertFrom-JSON).AppServicePlanUri}},
        @{n = 'AdditionalInfo_ImageType'             ; e = {($_.AdditionalInfo | ConvertFrom-JSON).ImageType}},
        @{n = 'AdditionalInfo_ServiceType'           ; e = {($_.AdditionalInfo | ConvertFrom-JSON).ServiceType}},
        @{n = 'AdditionalInfo_VMName'                ; e = {($_.AdditionalInfo | ConvertFrom-JSON).VMName}},
        @{n = 'AdditionalInfo_UsageType'             ; e = {($_.AdditionalInfo | ConvertFrom-JSON).UsageType}},
        @{n = 'AdditionalInfo_DatabaseAccount'       ; e = {($_.AdditionalInfo | ConvertFrom-JSON).DatabaseAccount}},
        @{n = 'AdditionalInfo_CollectionRid'         ; e = {($_.AdditionalInfo | ConvertFrom-JSON).CollectionRid}},
        @{n = 'AdditionalInfo_ResourceCategory'      ; e = {($_.AdditionalInfo | ConvertFrom-JSON).ResourceCategory}},
        @{n = 'Tags_displayName'                     ; e = {($_.Tags | ConvertFrom-JSON).displayName}},
        @{n = 'Tags_ACCESSED-VIA-INTERNET'           ; e = {($_.Tags | ConvertFrom-JSON).'ACCESSED-VIA-INTERNET'}},
        @{n = 'Tags_APP-NAME'                        ; e = {($_.Tags | ConvertFrom-JSON).'APP-NAME'}},
        @{n = 'Tags_APP-TYPE'                        ; e = {($_.Tags | ConvertFrom-JSON).'APP-TYPE'}},
        @{n = 'Tags_APPTYPE'                         ; e = {($_.Tags | ConvertFrom-JSON).APPTYPE}},
        @{n = 'Tags_CHARGECODE'                      ; e = {($_.Tags | ConvertFrom-JSON).CHARGECODE}},
        @{n = 'Tags_COMMENTS'                        ; e = {($_.Tags | ConvertFrom-JSON).COMMENTS}},
        @{n = 'Tags_COUNTRY'                         ; e = {($_.Tags | ConvertFrom-JSON).COUNTRY}},
        @{n = 'Tags_EY-REGION'                       ; e = {($_.Tags | ConvertFrom-JSON).'EY-REGION'}},
        @{n = 'Tags_IT-ENV'                          ; e = {($_.Tags | ConvertFrom-JSON).'IT-ENV'}},
        @{n = 'Tags_OWNER'                           ; e = {($_.Tags | ConvertFrom-JSON).OWNER}},
        @{n = 'Tags_OWNER-EMAIL'                     ; e = {($_.Tags | ConvertFrom-JSON).'OWNER-EMAIL'}},
        @{n = 'Tags_SERVICELINE'                     ; e = {($_.Tags | ConvertFrom-JSON).SERVICELINE}},
        @{n = 'Tags_SUB-TYPE'                        ; e = {($_.Tags | ConvertFrom-JSON).'SUB-TYPE'}},
        @{n = 'Tags_TECHCONTACTS'                    ; e = {($_.Tags | ConvertFrom-JSON).TECHCONTACTS}} |
    Export-Csv 'C:\output.csv' -NoTypeInformation

It might also be faster to say:

Get-Content -Path 'input.csv' |
    Select-Object -Skip 2 |
    ConvertFrom-Csv |
    ForEach-Object {
        $AdditionalInfo = $_.AdditionalInfo | ConvertFrom-Json;
        $Tags = $_.Tags | ConvertFrom-Json;
        $_ | Select-Object -Property *,
            @{n = 'AdditionalInfo_StreamingEndpointName' ; e = {$AdditionalInfo.StreamingEndpointName}},
            @{n = 'AdditionalInfo_Id'                    ; e = {$AdditionalInfo.Id}},
            ...
    } | Export-Csv ...

That way you're only converting the JSON once per line.

However, I suspect to get decent performance you'll have to write something using .Net methods.  I'd suggest using Microsoft.VisualBasic.FileIO.TextFieldParser to parse the CSV for you line by line and possibly JSON.Net to deserialize the JSON with JsonConvert.DeserializeObject().  Even then, this isn't going to be super fast.  1.5 GB of has got to be several million lines.  You may be better off to import the whole CSV into SQL Server 2016+ and use a query there with the built-in JSON parsing.


问:
Google Cloud Node.js dispatch.yaml is not working
I am making a web app with node.js using google app engine.

I want to redirect https://MY_PROJECT_ID.appspot.com to mycustome domain. I followed this maual but does not work. What is problem?

https://cloud.google.com/appengine/docs/flexible/nodejs/how-requests-are-routed#routing_with_a_dispatch_file

```<code>dispatch.yaml
dispatch:
  - url: 'fermi.me/' //my custom domain
    service: default

console
gcloud app deploy dispatch.yaml
Configurations to update:

descriptor:      [./nodejs-getting-started/2-structured-data/dispatch.yaml]
type:            [routing rules]
target project:  [XXXXXXX]

Do you want to continue (Y/n)?  Y

Updating config [dispatch]...done.
</code>```

Even though, dispatch.yaml is successfully deployed, if I executed 'app deploy', Redirection does not work. I already registered domain in Google cloud, and static websites worked.

I found the fundamental problem and it solved.

I already connected to static website with bucket.

https://cloud.google.com/storage/docs/hosting-static-website

There is a error in web-console in App-Engine domains setting.(Message: "Domain is already mapped to a project in google cloud platform". There is a critical error in this maunal.

https://cloud.google.com/appengine/docs/standard/python/mapping-custom-domains

The sample error message. It only appears when you already connect storage static website to domains.
error : domain is already mapped to a project in google cloud platform

You can use command-line tool with gcloud beta. Webconsole makes error but commandline works. After you mapped domain, you can now use webconsole. You should add cnames as the maunal above(mapping domains) explains There is a guide.

https://stackoverflow.com/a/46780534/9049333

答:
The dispatch file is only used to direct a request already reaching your app to the appropriate service/module. If the request doesn't match any dispatch.yaml rules it is automatically directed to the default service (making your rule redundant, BTW).

The dispatch file does NOT redirect a request to another domain (or anywhere back outside your app, really). So you're on the wrong track at this point.

You need to take care of such redirection in your application. Possibly relevant starting points for that:

Disable default domain https://[project-id].appspot.com of Node JS on Google App Engine

HTTP to HTTPS redirection on App Engine

Body:
I am making a web app with node.js using google app engine.

I want to redirect https://MY_PROJECT_ID.appspot.com to mycustome domain. I followed this maual but does not work. What is problem?

https://cloud.google.com/appengine/docs/flexible/nodejs/how-requests-are-routed#routing_with_a_dispatch_file

dispatch.yaml
dispatch:
  - url: 'fermi.me/' //my custom domain
    service: default

console
gcloud app deploy dispatch.yaml
Configurations to update:

descriptor:      [./nodejs-getting-started/2-structured-data/dispatch.yaml]
type:            [routing rules]
target project:  [XXXXXXX]

Do you want to continue (Y/n)?  Y

Updating config [dispatch]...done.

Even though, dispatch.yaml is successfully deployed, if I executed 'app deploy', Redirection does not work. I already registered domain in Google cloud, and static websites worked.

I found the fundamental problem and it solved.

I already connected to static website with bucket.

https://cloud.google.com/storage/docs/hosting-static-website

There is a error in web-console in App-Engine domains setting.(Message: "Domain is already mapped to a project in google cloud platform". There is a critical error in this maunal.

https://cloud.google.com/appengine/docs/standard/python/mapping-custom-domains

The sample error message. It only appears when you already connect storage static website to domains.
error : domain is already mapped to a project in google cloud platform

You can use command-line tool with gcloud beta. Webconsole makes error but commandline works. After you mapped domain, you can now use webconsole. You should add cnames as the maunal above(mapping domains) explains There is a guide.

https://stackoverflow.com/a/46780534/9049333


问:
Perl function: findOddCount

Hello,

I am trying to write a Perl findOddCount function which finds a value in the given list that occurs an odd number of times.

```<code>#!/usr/bin/perl

sub findOddCount{
    @array1 = $_[0];
    $res=0;
    for( $i=0; $i < $#array1; $i++) {
            $res=($res ^ $array1[i])
            }
    return $res
}

@a1 = (1,1,2,2,3,3,4,4,5,5,6,7,7,7,7);
@a2 = (10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10);
@a3 = (6,6,10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10);
@a4 = (10,10,7,7, 2,2,3,3,4,4,5,5,7,7,7,7,10,10,6);
@a5 = (6,6);
@a6 = (1);

print "odd value in a1 is "; print findOddCount(@a1); print "\n";
print "odd value in a2 is "; print findOddCount(@a2); print "\n";
print "odd value in a3 is "; print findOddCount(@a3); print "\n";
print "odd value in a4 is "; print findOddCount(@a4); print "\n";
print "odd value in a5 is "; print findOddCount(@a5); print "\n";
print "odd value in a6 is "; print findOddCount(@a6); print "\n";
</code>```

Expected Output:

```<code>odd value in a1 is 6
odd value in a2 is 6
odd value in a3 is 6
odd value in a4 is 6
odd value in a5 is 0
odd value in a6 is 1
</code>```

However, my actual output showed all 0:

```<code>odd value in a1 is 0
odd value in a2 is 0
odd value in a3 is 0
odd value in a4 is 0
odd value in a5 is 0
odd value in a6 is 0
</code>```

Any help would be appreciated. Thanks.

答:
There is a direct error with how arguments are used in the sub and a number of other deficiencies. However, even with that cleaned up the approach in the posted code doesn't do what you need.

Here is a working version first

```<code>use warnings;
use strict;
use feature 'say';

my @test_data = (
     [1,1,2,2,3,3,4,4,5,5,6,7,7,7,7],
     [10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10],
     [6,6,10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10],
     [10,10,7,7, 2,2,3,3,4,4,5,5,7,7,7,7,10,10,6],
     [6,6],
     [1]
);

for my $ra (@test_data)
{
    say "For: @$ra";
    if (my @odds = odd_count(@$ra)) {
        say "\tValue(s) with odd count: @odds";
    }
    else {
        say "\tNo values show odd number of times.";
    }
}

sub odd_count {
    my %cnt;
    ++$cnt{$_} for @_;
    return grep { $cnt{$_} % 2 } keys %cnt;
}
</code>```

Comments

Always start programs with use warnings; and use strict;.  It is hard to overstate how important these pragmas are. It's not  pedantry; it directly helps in every line of code

Arguments are passed to functions as a flattened list of scalars. So with func(@ary) the @_ in the function has (aliases) elements of @ary. Your code takes the first element, $_[0], and all must be wrong from there

The sub above takes an array as that cuts down on code and processing. But: (1) With big arrays pass by reference, odd_count($ra) (2) Since @_ aliases arguments, if it gets changed in the sub the caller's data may get changed.  See this post. If this is a problem create a local copy to work with, my @ary = @_, or my @ary = @{ $_[0] }; if you passed a reference

The $#array1 is the index of the last element in @array1, not the number of elements; so with that you'd need $i <= $#array1;, not < ...

but C-style for loop is almost never needed. Iterate over index by: for my $i (0..$#ary)

The ^ operator, which returns its operands XOR-ed bitwise, can't do what you want here since your code isn't working with groups of elements that are equal but is blindly running through all of them. Also, the code can record only one value

I use the hash to collect counts of values, what is very common, and postfix notation for for

To find the odd counts I use grep, which filters those keys whose value is odd

Title: Perl function: findOddCount

Body:
Hello,

I am trying to write a Perl findOddCount function which finds a value in the given list that occurs an odd number of times.

#!/usr/bin/perl

sub findOddCount{
    @array1 = $_[0];
    $res=0;
    for( $i=0; $i < $#array1; $i++) {
            $res=($res ^ $array1[i])
            }
    return $res
}

@a1 = (1,1,2,2,3,3,4,4,5,5,6,7,7,7,7);
@a2 = (10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10);
@a3 = (6,6,10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10);
@a4 = (10,10,7,7, 2,2,3,3,4,4,5,5,7,7,7,7,10,10,6);
@a5 = (6,6);
@a6 = (1);

print "odd value in a1 is "; print findOddCount(@a1); print "\n";
print "odd value in a2 is "; print findOddCount(@a2); print "\n";
print "odd value in a3 is "; print findOddCount(@a3); print "\n";
print "odd value in a4 is "; print findOddCount(@a4); print "\n";
print "odd value in a5 is "; print findOddCount(@a5); print "\n";
print "odd value in a6 is "; print findOddCount(@a6); print "\n";

Expected Output:

odd value in a1 is 6
odd value in a2 is 6
odd value in a3 is 6
odd value in a4 is 6
odd value in a5 is 0
odd value in a6 is 1

However, my actual output showed all 0:

odd value in a1 is 0
odd value in a2 is 0
odd value in a3 is 0
odd value in a4 is 0
odd value in a5 is 0
odd value in a6 is 0

Any help would be appreciated. Thanks.

Body:
There is a direct error with how arguments are used in the sub and a number of other deficiencies. However, even with that cleaned up the approach in the posted code doesn't do what you need.

Here is a working version first

use warnings;
use strict;
use feature 'say';

my @test_data = (
     [1,1,2,2,3,3,4,4,5,5,6,7,7,7,7],
     [10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10],
     [6,6,10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10],
     [10,10,7,7, 2,2,3,3,4,4,5,5,7,7,7,7,10,10,6],
     [6,6],
     [1]
);

for my $ra (@test_data)
{
    say "For: @$ra";
    if (my @odds = odd_count(@$ra)) {
        say "\tValue(s) with odd count: @odds";
    }
    else {
        say "\tNo values show odd number of times.";
    }
}

sub odd_count {
    my %cnt;
    ++$cnt{$_} for @_;
    return grep { $cnt{$_} % 2 } keys %cnt;
}

Comments

Always start programs with use warnings; and use strict;.  It is hard to overstate how important these pragmas are. It's not  pedantry; it directly helps in every line of code

Arguments are passed to functions as a flattened list of scalars. So with func(@ary) the @_ in the function has (aliases) elements of @ary. Your code takes the first element, $_[0], and all must be wrong from there

The sub above takes an array as that cuts down on code and processing. But: (1) With big arrays pass by reference, odd_count($ra) (2) Since @_ aliases arguments, if it gets changed in the sub the caller's data may get changed.  See this post. If this is a problem create a local copy to work with, my @ary = @_, or my @ary = @{ $_[0] }; if you passed a reference

The $#array1 is the index of the last element in @array1, not the number of elements; so with that you'd need $i <= $#array1;, not < ...

but C-style for loop is almost never needed. Iterate over index by: for my $i (0..$#ary)

The ^ operator, which returns its operands XOR-ed bitwise, can't do what you want here since your code isn't working with groups of elements that are equal but is blindly running through all of them. Also, the code can record only one value

I use the hash to collect counts of values, what is very common, and postfix notation for for

To find the odd counts I use grep, which filters those keys whose value is odd


问:
Typescript - classes composed of classes (nested classes?)
I've seen some post's about modules and namespaces but I haven't found anything online about doing something like this (not sure if it should be an interface or a class and I'm not convinced it matters). I'm using them to bind to some JSON data that is returned.

topLevelJsonElement.ts:

```<code>export interface TopLevelJsonElement {
    item: string;
    item2: SubItems[];
}
</code>```

subItems.ts

```<code>export interface SubItems {
    item: number;
    item2: any;
}
</code>```

Perhaps I could compose or nest them down as many levels as I wanted? But do you see how TopLevelJsonElement CONTAINS as list of SubItems

Currently I'm getting an error:
topLevelJsonElement"' has no exported member 'TopLevelJsonElement '.

答:
Thanks to @LLai in the comments. I'm using angular-cli and I had to restart my local host (ng serve).

Also I was able to boil my interface down to a similar version so I didn't need two interfaces. Not sure if it would have worked with the two. Something I need to try when I have more time.

```<code>export interface JsonElement {
    item: string;
    item2: JsonElement [];
}
</code>```

Body:
I've seen some post's about modules and namespaces but I haven't found anything online about doing something like this (not sure if it should be an interface or a class and I'm not convinced it matters). I'm using them to bind to some JSON data that is returned.

topLevelJsonElement.ts:

export interface TopLevelJsonElement {
    item: string;
    item2: SubItems[];
}

subItems.ts

export interface SubItems {
    item: number;
    item2: any;
}

Perhaps I could compose or nest them down as many levels as I wanted? But do you see how TopLevelJsonElement CONTAINS as list of SubItems

Currently I'm getting an error:
topLevelJsonElement"' has no exported member 'TopLevelJsonElement '.

Body:
Thanks to @LLai in the comments. I'm using angular-cli and I had to restart my local host (ng serve).

Also I was able to boil my interface down to a similar version so I didn't need two interfaces. Not sure if it would have worked with the two. Something I need to try when I have more time.

export interface JsonElement {
    item: string;
    item2: JsonElement [];
}


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
I'm not sure whereabouts you are within your C# journey, but I certainly found Head First C# a very good read and use the mini projects therein as practice. As someone who had been studying C# in their spare time for around a year and a half prior to reading the book, it gave me some mini 'Aha' moments, for example, with delegates and callbacks.

Granted, some of the examples within it are contrived, much like many other programming books, but hey, who doesn't want to build their own Space Invaders?!

OwnerDisplayName: GregD

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: GregD

OwnerDisplayName: Russ Cam


问:
Reload a model attribute
What's the best way to refresh a given model attribute?

I.e., functionally, I want this:

```<code>post.body = Post.find(post.id).body
</code>```

with a nicer syntax. Maybe

```<code>post.reload_body!
</code>```

Edit: I only want to reload a single attribute (not all attributes at once)

答:
Beats me why you'd want to do such a thing, but:

```<code>def reload_attribute(attr)
  value = self.class.where(:id=>id).select(attr).first[attr]
  self[attr] = value
end
</code>```

This issues a SELECT that retrieves just the one column and assigns its value to the attribute in the current model instance. Call with (eg):

```<code>post = Post.find(1)
post.reload_attribute(:body)
</code>```

Really though, you should just go with post.reload (doc). Unless you have hugely wide columns that impose some performance cost on doing SELECT *

Title: Reload a model attribute

Body:
What's the best way to refresh a given model attribute?

I.e., functionally, I want this:

post.body = Post.find(post.id).body

with a nicer syntax. Maybe

post.reload_body!

Edit: I only want to reload a single attribute (not all attributes at once)

Body:
Beats me why you'd want to do such a thing, but:

def reload_attribute(attr)
  value = self.class.where(:id=>id).select(attr).first[attr]
  self[attr] = value
end

This issues a SELECT that retrieves just the one column and assigns its value to the attribute in the current model instance. Call with (eg):

post = Post.find(1)
post.reload_attribute(:body)

Really though, you should just go with post.reload (doc). Unless you have hugely wide columns that impose some performance cost on doing SELECT *


问:
Running an Ansible Playbook using Python API 2.0.0.1
Ansible version : 2.0.0.1

I've been looking around quite a bit now, and most documentation I find is either incomplete or deprecated (this post is for version 1.8.4, ie)

I'm trying to launch an Ansible playbook through the Python API. Ansible's documentation seem to be showing how to generate and play tasks, but not how to load and run a playbook yml file. I've been digging into the code to try to understand how to launch it, and I think I've done some progress, but I'm really hitting a wall. Here's what I have so far :

```<code>def createcluster(region, environment, cluster):
    Options = namedtuple('Options', ['region','env', 'cluster'])

    # initialize needed objects
    variable_manager = VariableManager()
    loader = DataLoader()
    options = Options(region=region, env=environment, cluster=cluster)
    options.listhosts = False
    vault_password = getpass.getpass('Enter vault password :')
    passwords = dict(vault_pass=vault_password)

    #Getting hosts
    hostsread = open('provisioning/inventory/hosts','r')
    hosts =  hostsread.read()
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=hosts)
    variable_manager.set_inventory(inventory)
    #Create and load the playbook file
    playbook = Playbook(loader)
    playbook.load('provisioning/cluster.yml', variable_manager,loader)

    #Create an executor to launch the playbook ?
    executor = None
    executor = PlaybookExecutor(playbook,inventory,variable_manager,loader,options,passwords)
    try:
        result = executor.run()
    finally:
        if executor is not None:
            executor.cleanup()
</code>```

I'm not sure at all about the executor part, and I keep getting a "AttributeError: 'Options' object has no attribute 'listhosts'" error when I try to launch the code (weirdly enough as it should just ignore its absence, I think (line 60))

How am I supposed to load a YML file and launch it through the Python API ? Am I on the good path or did I lose myself ? Why isn't Ansible better documented ? Why would 42 be the answer to 7*7 ?

答:
Disclaimer

Posting for completion.

I had trouble setting verbosity for ansible 2.4. I will mainly talk about that.

TL;DR

Ansible use a global Display object in the __main__ file (the one you launch) if it doesn't exist some imports will create it.

This is considered a bad practice and not PEP8 compliant (second bullet point)

Explanation part

versions: (I am using python virtualenv)

ansible = 2.4.2.0 (also tested in 2.4.1.0)

python = 2.7.13

How is it used inside ansible

try:
    from __main__ import display
except ImportError:
    from ansible.utils.display import Display
    display = Display()
```

<p>It is called in almost every file (108).
Like so you have a new display in your entry point and then all other module will retrieve this first declared display.</p>

<h3>Running with another verbosity</h3>

<p>You just have to declare a Display object like so:</p>

<pre class="lang-py prettyprint-override"><code>from ansible.utils.display import Display
display = Display(verbosity=5)
</code>```

You can alternatively use this after: display.verbosity = 1000

Problem

I wanted to be able to completely remove ansible output (negative value = no output)

Solving

I ended up creating a new class like so:

from ansible.utils.display import Display

class AnsibleDisplay(Display):
    '''
    This  class override the display.display() function
    '''
    def display(self, *args, **kwargs):
        if self.verbosity >= 0:
            super(AnsibleDisplay, self).display(*args, **kwargs)
```

<p>Then import it in my <code>__main__</code> file</p>

<pre class="lang-py prettyprint-override"><code># Ansible call this global object for display
sys.path.append(ROOT_DIR + os.sep + 'lib')
from ansible_display import AnsibleDisplay
display = AnsibleDisplay(verbosity=0)
</code>```

And only after import all other modules

Example

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(SCRIPT_DIR)

## For ansible
import json
from collections import namedtuple

# Ansible call this global object for display
sys.path.append(ROOT_DIR + os.sep + 'lib')
from ansible_display import AnsibleDisplay
display = AnsibleDisplay(verbosity=0)

# Load other libs after to make sure they all use the above 'display'
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.playbook_executor import PlaybookExecutor

def apply_verbosity(args):
    global display
    verb = -1 if args.verbosity is None else args.verbosity
    display.verbosity = verb

def ansible_part():
    playbook_path = "%s/ansible/main_playbook.yml" % (ROOT_DIR)
    inventory_path = "%s/watev/my_inventory.ini"

    Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff', 'listhosts', 'listtasks', 'listtags', 'syntax'])
    # initialize needed objects
    loader = DataLoader()
    options = Options(connection='local', module_path='%s/' % (ROOT_DIR), forks=100, become=None, become_method=None, become_user=None, check=False,
                    diff=False, listhosts=True, listtasks=False, listtags=False, syntax=False)
    passwords = dict(vault_pass='secret')

    # create inventory and pass to var manager
    inventory = InventoryManager(loader=loader, sources=[inventory_path])
    variable_manager = VariableManager(loader=loader, inventory=inventory)

    pbex = PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords)
    results = pbex.run()

def main():
    ansible_part()
```

Notes

I needed to add the 4 options to the namedtuple:

listhosts=True, listtasks=False, listtags=False, syntax=False

The import __main__ makes debugging impractical because when using debugger (in my case pudb), the __main__ file is the debugger file hence from __main__ import display will never work

hth

[Edit1]: added note

Body:
Ansible version : 2.0.0.1

I've been looking around quite a bit now, and most documentation I find is either incomplete or deprecated (this post is for version 1.8.4, ie)

I'm trying to launch an Ansible playbook through the Python API. Ansible's documentation seem to be showing how to generate and play tasks, but not how to load and run a playbook yml file. I've been digging into the code to try to understand how to launch it, and I think I've done some progress, but I'm really hitting a wall. Here's what I have so far :

def createcluster(region, environment, cluster):
    Options = namedtuple('Options', ['region','env', 'cluster'])

    # initialize needed objects
    variable_manager = VariableManager()
    loader = DataLoader()
    options = Options(region=region, env=environment, cluster=cluster)
    options.listhosts = False
    vault_password = getpass.getpass('Enter vault password :')
    passwords = dict(vault_pass=vault_password)

    #Getting hosts
    hostsread = open('provisioning/inventory/hosts','r')
    hosts =  hostsread.read()
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=hosts)
    variable_manager.set_inventory(inventory)
    #Create and load the playbook file
    playbook = Playbook(loader)
    playbook.load('provisioning/cluster.yml', variable_manager,loader)

    #Create an executor to launch the playbook ?
    executor = None
    executor = PlaybookExecutor(playbook,inventory,variable_manager,loader,options,passwords)
    try:
        result = executor.run()
    finally:
        if executor is not None:
            executor.cleanup()

I'm not sure at all about the executor part, and I keep getting a "AttributeError: 'Options' object has no attribute 'listhosts'" error when I try to launch the code (weirdly enough as it should just ignore its absence, I think (line 60))

How am I supposed to load a YML file and launch it through the Python API ? Am I on the good path or did I lose myself ? Why isn't Ansible better documented ? Why would 42 be the answer to 7*7 ?

Body:
Disclaimer

Posting for completion.

I had trouble setting verbosity for ansible 2.4. I will mainly talk about that.

TL;DR

Ansible use a global Display object in the __main__ file (the one you launch) if it doesn't exist some imports will create it.

This is considered a bad practice and not PEP8 compliant (second bullet point)

Explanation part

versions: (I am using python virtualenv)

ansible = 2.4.2.0 (also tested in 2.4.1.0)

python = 2.7.13

How is it used inside ansible

try:
    from __main__ import display
except ImportError:
    from ansible.utils.display import Display
    display = Display()

It is called in almost every file (108).
Like so you have a new display in your entry point and then all other module will retrieve this first declared display.

Running with another verbosity

You just have to declare a Display object like so:

from ansible.utils.display import Display
display = Display(verbosity=5)

You can alternatively use this after: display.verbosity = 1000

Problem

I wanted to be able to completely remove ansible output (negative value = no output)

Solving

I ended up creating a new class like so:

from ansible.utils.display import Display

class AnsibleDisplay(Display):
    '''
    This  class override the display.display() function
    '''
    def display(self, *args, **kwargs):
        if self.verbosity >= 0:
            super(AnsibleDisplay, self).display(*args, **kwargs)

Then import it in my __main__ file

# Ansible call this global object for display
sys.path.append(ROOT_DIR + os.sep + 'lib')
from ansible_display import AnsibleDisplay
display = AnsibleDisplay(verbosity=0)

And only after import all other modules

Example

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(SCRIPT_DIR)

## For ansible
import json
from collections import namedtuple

# Ansible call this global object for display
sys.path.append(ROOT_DIR + os.sep + 'lib')
from ansible_display import AnsibleDisplay
display = AnsibleDisplay(verbosity=0)

# Load other libs after to make sure they all use the above 'display'
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.playbook_executor import PlaybookExecutor

def apply_verbosity(args):
    global display
    verb = -1 if args.verbosity is None else args.verbosity
    display.verbosity = verb

def ansible_part():
    playbook_path = "%s/ansible/main_playbook.yml" % (ROOT_DIR)
    inventory_path = "%s/watev/my_inventory.ini"

    Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff', 'listhosts', 'listtasks', 'listtags', 'syntax'])
    # initialize needed objects
    loader = DataLoader()
    options = Options(connection='local', module_path='%s/' % (ROOT_DIR), forks=100, become=None, become_method=None, become_user=None, check=False,
                    diff=False, listhosts=True, listtasks=False, listtags=False, syntax=False)
    passwords = dict(vault_pass='secret')

    # create inventory and pass to var manager
    inventory = InventoryManager(loader=loader, sources=[inventory_path])
    variable_manager = VariableManager(loader=loader, inventory=inventory)

    pbex = PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords)
    results = pbex.run()

def main():
    ansible_part()

Notes

I needed to add the 4 options to the namedtuple:

listhosts=True, listtasks=False, listtags=False, syntax=False

The import __main__ makes debugging impractical because when using debugger (in my case pudb), the __main__ file is the debugger file hence from __main__ import display will never work

hth

[Edit1]: added note


问:
Dropdown menu with equal width for justified button group in bootstrap
Using bootstrap, I'm trying to make a dropdown menu inside one of the buttons in a justified button group. More specifically, I want the dropdown menu list elements to have the same width as the dropdown toggle button. The code below does everything except the width of the dropdown elements is different from the toggle button. </p>

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
   <style>
   .pull-right{
        margin-top: 7px
    }
   </style>
</head>
<body>

<div class="container">
  <h2>Justified Button Groups</h2>
  <div class="btn-group btn-group-justified">
    <a href="#" class="btn btn-primary">Apple</a>
    <a href="#" class="btn btn-primary">Samsung</a>
    <div class="dropdown btn-group">
    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Sony<span class="caret pull-right"></span></button>
    <ul class="dropdown-menu">
    <li><a href="#" class="btn btn-default btn-block">HTML</a></li>
    <li><a href="#" class="btn btn-default btn-block">CSS</a></li>
    <li><a href="#" class="btn btn-default btn-block">JavaScript</a></li>
    </ul>
    </div>
  </div>
</div>

</body>
</html>
</code>```

答:
try this code :)    </p>

```<code>.dropdown-menu{
    width: 100%;
    text-align: center;
}
</code>```

Body:
Using bootstrap, I'm trying to make a dropdown menu inside one of the buttons in a justified button group. More specifically, I want the dropdown menu list elements to have the same width as the dropdown toggle button. The code below does everything except the width of the dropdown elements is different from the toggle button.

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Justified Button Groups

    Apple
    Samsung

    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Sony</button>

HTML

CSS

JavaScript

Body:
try this code :)

.dropdown-menu{
    width: 100%;
    text-align: center;
}


问:
Split list into smaller lists of n-size with stream
How can I take a Java list and split it into smaller lists of size n in Java using streams?

In JavaScript, I'd use the reduce() function and do something like this:

const n = 3;
const sublists = [1,2,3,4,5,6,7,8,9,0]
  .reduce((r, i) => {
    r[r.length - 1].length == n
      ? r.push([i])
      : r[r.length - 1].push(i);
    return r;
  }, [[]]);
console.log(sublists);```

I'm trying to do that with a Java stream, but I can't seem to figure out how to get it to let me use an ArrayList<ArrayList<Integer>> as my initial value and then add the lists. I'm a little confused how the combinator and accumulator play in to let me use them, or even if reduce() is the best approach for Java.

答:
It looks like you have a JavaScript array, so the equivalent Java code would presumably use an IntStream. First, calculate the correct number of rows and then use Arrays.copyOfRange collect to a List and then convert to an int[][]. Finally, use Arrays.deepToString to print the array. Like,

```<code>final int n = 3;
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int rows = 1 + arr.length / n;
int[][] sublists = IntStream.range(0, rows)
        .mapToObj(i ->
                Arrays.copyOfRange(arr, n * i, Math.min(n + (n * i), arr.length)))
        .collect(Collectors.toList()).toArray(new int[rows][n]);
System.out.println(Arrays.deepToString(sublists));
</code>```

Which outputs

```<code>[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]]
</code>```

For a List<Integer> it might be done like

```<code>final int n = 3;
List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
int rows = 1 + arr.size() / n;
List<List<Integer>> sublists = IntStream.range(0, rows)
        .mapToObj(i -> arr.subList(n * i, Math.min(n + (n * i), arr.size())))
        .collect(Collectors.toList());
System.out.println(sublists);
</code>```

for the same (requested) output.

Body:
How can I take a Java list and split it into smaller lists of size n in Java using streams?

In JavaScript, I'd use the reduce() function and do something like this:

const n = 3;
const sublists = [1,2,3,4,5,6,7,8,9,0]
  .reduce((r, i) => {
    r[r.length - 1].length == n
      ? r.push([i])
      : r[r.length - 1].push(i);
    return r;
  }, [[]]);
console.log(sublists);

I'm trying to do that with a Java stream, but I can't seem to figure out how to get it to let me use an ArrayList<ArrayList<Integer>> as my initial value and then add the lists. I'm a little confused how the combinator and accumulator play in to let me use them, or even if reduce() is the best approach for Java.

Body:
It looks like you have a JavaScript array, so the equivalent Java code would presumably use an IntStream. First, calculate the correct number of rows and then use Arrays.copyOfRange collect to a List and then convert to an int[][]. Finally, use Arrays.deepToString to print the array. Like,

final int n = 3;
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int rows = 1 + arr.length / n;
int[][] sublists = IntStream.range(0, rows)
        .mapToObj(i ->
                Arrays.copyOfRange(arr, n * i, Math.min(n + (n * i), arr.length)))
        .collect(Collectors.toList()).toArray(new int[rows][n]);
System.out.println(Arrays.deepToString(sublists));

Which outputs

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]]

For a List<Integer> it might be done like

final int n = 3;
List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
int rows = 1 + arr.size() / n;
List<List<Integer>> sublists = IntStream.range(0, rows)
        .mapToObj(i -> arr.subList(n * i, Math.min(n + (n * i), arr.size())))
        .collect(Collectors.toList());
System.out.println(sublists);

for the same (requested) output.


问:
PHP — Convert milliseconds to Hours : Minutes : Seconds.fractional
I've got a script that takes in a value in seconds (to 2 decimal points of fractional seconds):

```<code>$seconds_input = 23.75
</code>```

I then convert it to milliseconds:

```<code>$milliseconds = $seconds_input * 1000; // --> 23750
</code>```

And then I want to format it like so:

```<code>H:M:S.x // --> 0:0:23.75
</code>```

Where 'x' is the fraction of the second (however many places after the decimal there are).

Any help? I can't seem to wrap my mind around this. I tried using gmdate() but it kept lopping off the fractional seconds.

Thanks.

答:
My take

```<code>function formatSeconds( $seconds )
{
  $hours = 0;
  $milliseconds = str_replace( "0.", '', $seconds - floor( $seconds ) );

  if ( $seconds > 3600 )
  {
    $hours = floor( $seconds / 3600 );
  }
  $seconds = $seconds % 3600;

  return str_pad( $hours, 2, '0', STR_PAD_LEFT )
       . gmdate( ':i:s', $seconds )
       . ($milliseconds ? ".$milliseconds" : '')
  ;
}
</code>```

And then the test

```<code>$testData = array(
    23,              // Seconds, w/o millis
    23.75,           // Seconds, w/millis
    23.75123456789,  // Lots of millis
    123456789.75    // Lots of seconds
);

foreach ( $testData as $seconds )
{
  echo formatSeconds( $seconds ), PHP_EOL;
}
</code>```

which yields

```<code>00:00:23
00:00:23.75
00:00:23.75123456789
34293:33:09.75
</code>```

Body:
I've got a script that takes in a value in seconds (to 2 decimal points of fractional seconds):

$seconds_input = 23.75

I then convert it to milliseconds:

$milliseconds = $seconds_input * 1000; // --> 23750

And then I want to format it like so:

H:M:S.x // --> 0:0:23.75

Where 'x' is the fraction of the second (however many places after the decimal there are).

Any help? I can't seem to wrap my mind around this. I tried using gmdate() but it kept lopping off the fractional seconds.

Thanks.

Body:
My take

function formatSeconds( $seconds )
{
  $hours = 0;
  $milliseconds = str_replace( "0.", '', $seconds - floor( $seconds ) );

  if ( $seconds > 3600 )
  {
    $hours = floor( $seconds / 3600 );
  }
  $seconds = $seconds % 3600;

  return str_pad( $hours, 2, '0', STR_PAD_LEFT )
       . gmdate( ':i:s', $seconds )
       . ($milliseconds ? ".$milliseconds" : '')
  ;
}

And then the test

$testData = array(
    23,              // Seconds, w/o millis
    23.75,           // Seconds, w/millis
    23.75123456789,  // Lots of millis
    123456789.75    // Lots of seconds
);

foreach ( $testData as $seconds )
{
  echo formatSeconds( $seconds ), PHP_EOL;
}

which yields

00:00:23
00:00:23.75
00:00:23.75123456789
34293:33:09.75


问:
How many N Links does root's index node have?
Title says it all really, but here's the prompt.

For an operating systems class, we have been given some base code for a file system and asked to expand it.

Part of that feature list includes making our own implementation of fschk, which needs to verify the number of links per index node is correct.

My fschk (right or wrong) walks the file system and reads the index node number from each filename. It then adds one to an index in a table which maintains a reference count. It then walks this table and compares the counted values to what each index node actually says.

This has given me the correct number of Nlinks for all new files and directories I've added to the filesystem, except the root node itself. I always count one reference to root from walking the filesystem, but root's index node insists that it has 3 Nlinks.

That's just what prompted me to ask this question. In a general Unix filesystem, how many Nlinks does root's index node have? Where do they come from?

答:
I've learned it's 3. The name itself, followed by the . and ..

/

.

..


问:
Getting rid of unnecessary lines (axes?) in Choroplethr
Whenever I make a choropleth using the Choroplethr package, these unnecessary lines appear. I believe they're axes, but the state_choropleth function shouldn't be printing axes.

Example:

```<code>df <- data.frame(region = c("alabama", "alaska", "arizona", "arkansas", "california", "colorado", "connecticut", "delaware", "district of columbia", "florida", "georgia", "hawaii", "idaho", "illinois", "indiana", "iowa", "kansas", "kentucky", "louisiana", "maine", "maryland", "massachusetts", "michigan", "minnesota", "mississippi", "missouri", "montana", "nebraska", "nevada", "new hampshire", "new jersey", "new mexico", "new york", "north carolina", "north dakota", "ohio", "oklahoma", "oregon", "pennsylvania", "rhode island", "south carolina", "south dakota", "tennessee", "texas", "utah", "vermont", "virginia", "washington", "west virginia", "wisconsin", "wyoming"), value = runif(51))
state_choropleth(df)
</code>```

This is the result:
Map with extraneous lines

Can anyone help me get rid of these? I've poked around in the Choroplethr source code but can't seem to identify what these are.

Edit: I'm running Windows 10 Enterprise, R 3.4.2 64-bit, and have installed choroplethr 3.6.1 and ggplot2 2.2.1.

答:
Load ggplot library(ggplot2) and try state_choropleth(df) + theme(panel.border = element_blank()).

This removes the borders for the mainland US. However Alaska and Hawaii still have borders around them.

Body:
Whenever I make a choropleth using the Choroplethr package, these unnecessary lines appear. I believe they're axes, but the state_choropleth function shouldn't be printing axes.

Example:

df <- data.frame(region = c("alabama", "alaska", "arizona", "arkansas", "california", "colorado", "connecticut", "delaware", "district of columbia", "florida", "georgia", "hawaii", "idaho", "illinois", "indiana", "iowa", "kansas", "kentucky", "louisiana", "maine", "maryland", "massachusetts", "michigan", "minnesota", "mississippi", "missouri", "montana", "nebraska", "nevada", "new hampshire", "new jersey", "new mexico", "new york", "north carolina", "north dakota", "ohio", "oklahoma", "oregon", "pennsylvania", "rhode island", "south carolina", "south dakota", "tennessee", "texas", "utah", "vermont", "virginia", "washington", "west virginia", "wisconsin", "wyoming"), value = runif(51))
state_choropleth(df)

This is the result:
Map with extraneous lines

Can anyone help me get rid of these? I've poked around in the Choroplethr source code but can't seem to identify what these are.

Edit: I'm running Windows 10 Enterprise, R 3.4.2 64-bit, and have installed choroplethr 3.6.1 and ggplot2 2.2.1.


问:
Inserting incremented number where no identity / increment exists
I am working with a table which has a number assigned to each row (nulls not allowed) in the 'entryorder' column

```<code>1
2
3
</code>```

In order to insert a row I can do a @@rowcount and assign the result to a variable+1 then use that in the insert statement

Is this the safest way ?

答: if you are not able to change column properties to identity/autoincrement, then use max function to get max value of the column and add one to it for the new row. instead of using @@rowcount </p>

Body:
I am working with a table which has a number assigned to each row (nulls not allowed) in the 'entryorder' column

1
2
3

In order to insert a row I can do a @@rowcount and assign the result to a variable+1 then use that in the insert statement

Is this the safest way ?


答:
Create a function that checks your condition, if not, it returns an empty list/empty set etc.

Then apply that function to the variable, but also assigning the new calculated variable to the old one or to a new variable if you wish.

```<code>aa=pd.DataFrame({'d':[1,1,2,3,3,np.NaN],'r':[3,5,5,5,5,'e']})

def check_condition(x):
    if x>0:
        return x
    else:
        return list()

aa['d]=aa.d.apply(lambda x:check_condition(x))
</code>```

Title: How to fill dataframe Nan values with empty list [] in pandas?

Body:
This is my dataframe:

          date                          ids
0     2011-04-23  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...
1     2011-04-24  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...
2     2011-04-25  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...
3     2011-04-26  Nan
4     2011-04-27  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...
5     2011-04-28  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...

I want to replace Nan with []. How to do that? Fillna([]) did not work. I even tried replace(np.nan, []) but it gives error:

 TypeError('Invalid "to_replace" type: \'float\'',)

Body:
Create a function that checks your condition, if not, it returns an empty list/empty set etc.

Then apply that function to the variable, but also assigning the new calculated variable to the old one or to a new variable if you wish.

aa=pd.DataFrame({'d':[1,1,2,3,3,np.NaN],'r':[3,5,5,5,5,'e']})

def check_condition(x):
    if x>0:
        return x
    else:
        return list()

aa['d]=aa.d.apply(lambda x:check_condition(x))


问:
Percetile complications
I am trying to find the bottom 33%, middle 33% and upper 33% from my dataset.

What I need:
I need to get the percentile for individuals in excel. I have hundreds of people and next to them the managers name so I have been using the below formula to get the percentile based on manager.

Current Formula:

```<code>=IF(G2<AGGREGATE(18,6,G$2:G$1000/(AS$2:AS$1000=AS2),0.3333333),"Bottom",IF(G2<AGGREGATE(18,6,G$2:G$1000/(AS$2:AS$1000=AS2),0.66666666),"Middle","Top"))
</code>```

Problem:

This formula should have the words top, middle and bottom against every manager at least once. But I have noticed some managers only having a top and middle. Clearly I am missing something?

Update:
I have also used the below formula against just the numbers and not receiving 'bottom' at all

```<code>=IF(A1<PERCENTILE.EXC(A:A,33.33333%),"Bottom 33%",IF(A1<PERCENTILE.EXC(A:A,66.666666%),"Middle","Upper"))
</code>```

SAMPLE NUMBERS:

```<code>6.31025416
5.18260342
5.25185395
4.57484582
4.99563873
6.31717482
3.49576271
4.21992744
5.02853494
4.77338476
4.9579394
4.00174679
4.04134247
4.66614821
4.264681
1.94515737
3.96117421 0 0
1.35109777 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0.97126669
0.99805933 0 0 0
</code>```

Title: Percetile complications

Body:
I am trying to find the bottom 33%, middle 33% and upper 33% from my dataset.

What I need:
I need to get the percentile for individuals in excel. I have hundreds of people and next to them the managers name so I have been using the below formula to get the percentile based on manager.

Current Formula:

=IF(G2<AGGREGATE(18,6,G$2:G$1000/(AS$2:AS$1000=AS2),0.3333333),"Bottom",IF(G2<AGGREGATE(18,6,G$2:G$1000/(AS$2:AS$1000=AS2),0.66666666),"Middle","Top"))

Problem:

This formula should have the words top, middle and bottom against every manager at least once. But I have noticed some managers only having a top and middle. Clearly I am missing something?

Update:
I have also used the below formula against just the numbers and not receiving 'bottom' at all

=IF(A1<PERCENTILE.EXC(A:A,33.33333%),"Bottom 33%",IF(A1<PERCENTILE.EXC(A:A,66.666666%),"Middle","Upper"))

SAMPLE NUMBERS:

6.31025416
5.18260342
5.25185395
4.57484582
4.99563873
6.31717482
3.49576271
4.21992744
5.02853494
4.77338476
4.9579394
4.00174679
4.04134247
4.66614821
4.264681
1.94515737
3.96117421 0 0
1.35109777 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0.97126669
0.99805933 0 0 0

Body:
If you want to exclude the 0 use this:

=IF(G2<>0,IF(G2<AGGREGATE(18,6,G$2:G$1000/((AS$2:AS$1000=AS2)*(G$2:G$1000<>0)),0.3333333),"Bottom",IF(G2<AGGREGATE(18,6,G$2:G$1000/((AS$2:AS$1000=AS2)*(G$2:G$1000<>0)),0.66666666),"Middle","Top")),"")


问:
Exception mapper rerouting
I have a set of jersey exception mapper and today I realized that
google cache wraps my exceptions into UncheckedExecutionException.
Wrapped exceptions bypass my exception mappers.

There is an idea to define another exception mapper for UncheckedExecutionException and inject all my exception mappers, but how to avoid code duplication in dispatching mechanism. The new exception mapper should just shell out the caused exception.

答:
My expected solution was close.
The only trick there is avoiding cycle references in HK2. </p>

```<code>@Inject
private Provider<ExceptionMappers> mappersProvider;

register(UncheckedExecutionExceptionMapper.class);

    @Override
    public Response toResponse(UncheckedExecutionException exception) {
        log.error("Error {}", exception.getMessage(), exception);
        return mappersProvider.get().findMapping(exception.getCause()).toResponse(exception.getCause());
    }
</code>```

Title: Exception mapper rerouting

Body:
My expected solution was close.
The only trick there is avoiding cycle references in HK2.

@Inject
private Provider<ExceptionMappers> mappersProvider;

register(UncheckedExecutionExceptionMapper.class);

    @Override
    public Response toResponse(UncheckedExecutionException exception) {
        log.error("Error {}", exception.getMessage(), exception);
        return mappersProvider.get().findMapping(exception.getCause()).toResponse(exception.getCause());
    }


问:
Conver a Pandas Dataframe into a Dictionary of Lists, grouping by one column
I have data in this format:

```<code>term_x       similar_sounding_term

insurance    insurance_policy
insurance    insurance_quote
insurance    car_insurance
car rental   rental cars in Nantucket
car rental   damaged car rental policy
</code>```

I want to transform this dataframe into a dictionary where the key is term_x but the value is a list of all of the values asscoiated in that term, so:

```<code>insurance : [insurance_policy, insurance_quote, car_insurance, rental cars in Nantucket....]
</code>```

and so forth:

I though the answer here solved my problem but it did not merge the lists under one key like I had hoped.

答:
IIUC</p>

```<code>df.groupby('term_x')['similar_sounding_term'].apply(list).to_dict()
Out[1690]:
{'carrental': ['rentalcarsinNantucket', 'damagedcarrentalpolicy'],
 'insurance': ['insurance_policy', 'insurance_quote', 'car_insurance']}
</code>```

Body:
I have data in this format:

term_x       similar_sounding_term

insurance    insurance_policy
insurance    insurance_quote
insurance    car_insurance
car rental   rental cars in Nantucket
car rental   damaged car rental policy

I want to transform this dataframe into a dictionary where the key is term_x but the value is a list of all of the values asscoiated in that term, so:

insurance : [insurance_policy, insurance_quote, car_insurance, rental cars in Nantucket....]

and so forth:

I though the answer here solved my problem but it did not merge the lists under one key like I had hoped.

Body:
IIUC

df.groupby('term_x')['similar_sounding_term'].apply(list).to_dict()
Out[1690]:
{'carrental': ['rentalcarsinNantucket', 'damagedcarrentalpolicy'],
 'insurance': ['insurance_policy', 'insurance_quote', 'car_insurance']}


问:
Random Color loop using ChartJs and loops
I have a javascript issue using chartJs and a loop
I am trying to get a different color for each database_set rendered but for some reason it render the same color each time

Here is my code if you can have a look please ;)

```<code>function getRandomColor() {
      var letters = '0123456789ABCDEF'.split('');
      var color = '#';
      for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;

var datasetValue = [];
for (var j=0; j<team_member_count; j++) {
    datasetValue[j] = {
        backgroundColor: getRandomColor,
        label : name[j],
        data : info_data,
    };
}
var looped_data = datasetValue

var info_process = new Chart(ctx2,{
  type: 'radar',
  data: {
    labels: labels_info,
    datasets: looped_data
        },
    options: {
       scale: {display: true,
               ticks: {
                 beginAtZero: true,
 }
              },
       responsive:true,
       maintainAspectRatio: true,
      }
});
</code>```

答:
The backgroundColor property should be assigned some kind of string.  You're assigning it a function.

I think you want the string result of calling the function instead.

So this:

backgroundColor: getRandomColor,

Should probably be:

backgroundColor: getRandomColor(),

Body:
I have a javascript issue using chartJs and a loop
I am trying to get a different color for each database_set rendered but for some reason it render the same color each time

Here is my code if you can have a look please ;)

function getRandomColor() {
      var letters = '0123456789ABCDEF'.split('');
      var color = '#';
      for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;

var datasetValue = [];
for (var j=0; j<team_member_count; j++) {
    datasetValue[j] = {
        backgroundColor: getRandomColor,
        label : name[j],
        data : info_data,
    };
}
var looped_data = datasetValue

var info_process = new Chart(ctx2,{
  type: 'radar',
  data: {
    labels: labels_info,
    datasets: looped_data
        },
    options: {
       scale: {display: true,
               ticks: {
                 beginAtZero: true,
 }
              },
       responsive:true,
       maintainAspectRatio: true,
      }
});


问:
How to get better lemmas from Spacy
While "PM" can mean "pm(time)" it can also mean "Prime Minister".

I want to capture the latter. I want lemma of "PM" to return "Prime Minister". How can I do this using spacy?

Example returning unexpected lemma:

```<code>>>> import spacy
>>> #nlp = spacy.load('en')
>>> nlp = spacy.load('en_core_web_lg')
>>> doc = nlp(u'PM means prime minister')
>>> for word in doc:
...     print(word.text, word.lemma_)
...
PM pm
means mean
prime prime
minister minister
</code>```

As per doc https://spacy.io/api/annotation, spacy uses WordNet for lemmas;

A lemma is the uninflected form of a word. The English lemmatization data is taken from WordNet..

When I tried inputting "pm" in Wordnet, it shows "Prime Minister" as one of the lemmas.

What am I missing here?

答:
When I run lemmas of prime minister on nltk.wordnet (which uses it as well) I get:

>>>[str(lemma.name()) for lemma in wn.synset('prime_minister.n.01').lemmas()]  ['Prime_Minister', 'PM', 'premier']

It keeps acronyms the same so maybe you want to check word.lemma() which would give you a different ID according to the context?

ContentLicense: CC BY-SA 4.0

Title: How to get better lemmas from Spacy

Body:
While "PM" can mean "pm(time)" it can also mean "Prime Minister".

I want to capture the latter. I want lemma of "PM" to return "Prime Minister". How can I do this using spacy?

Example returning unexpected lemma:

>>> import spacy
>>> #nlp = spacy.load('en')
>>> nlp = spacy.load('en_core_web_lg')
>>> doc = nlp(u'PM means prime minister')
>>> for word in doc:
...     print(word.text, word.lemma_)
...
PM pm
means mean
prime prime
minister minister

As per doc https://spacy.io/api/annotation, spacy uses WordNet for lemmas;

A lemma is the uninflected form of a word. The English lemmatization data is taken from WordNet..

When I tried inputting "pm" in Wordnet, it shows "Prime Minister" as one of the lemmas.

What am I missing here?


答:
if you really want to do it using date function you are right, you have to deal with milliseconds externally, is only based on second-timestamps.

you could do something like this:

```<code><?
$input = "23.75";
$seconds = floor($input);
$date = DateTime::createFromFormat('s', floor($seconds));
$ms = ($input-$seconds);
if($ms == 0) {
$ms = "";
} else {
$ms = ltrim($ms,"0,");
}
echo $date->format('H:i:s').$ms;
</code>```

but be aware of the hour-overflow, if your hours exceed 24 you will probably end up discarding the days.

in your case i would say your approach with floor to get the seconds is correct, and then you should probably just use modulo arithmetics like this:

```<code><?
$totalsecs = 86400*10;

$secs = $totalsecs%60;

echo "secs: $secs \n";

$minutes = ($totalsecs - $secs) % (60*60);
?>
</code>```

and so on..

Title: PHP — Convert milliseconds to Hours : Minutes : Seconds.fractional

Body:
if you really want to do it using date function you are right, you have to deal with milliseconds externally, is only based on second-timestamps.

you could do something like this:

<?
$input = "23.75";
$seconds = floor($input);
$date = DateTime::createFromFormat('s', floor($seconds));
$ms = ($input-$seconds);
if($ms == 0) {
$ms = "";
} else {
$ms = ltrim($ms,"0,");
}
echo $date->format('H:i:s').$ms;

but be aware of the hour-overflow, if your hours exceed 24 you will probably end up discarding the days.

in your case i would say your approach with floor to get the seconds is correct, and then you should probably just use modulo arithmetics like this:

<?
$totalsecs = 86400*10;

$secs = $totalsecs%60;

echo "secs: $secs \n";

$minutes = ($totalsecs - $secs) % (60*60);
?>

and so on..


问:
Carbon createFromFormat unexpected result
::createFromFormat() results in being one month ahead:

```<code>var_dump($_GET['archive']);
var_dump(Carbon::createFromFormat('m/Y', $_GET['archive']));
</code>```

Result:

```<code>string '11/2015' (length=7)
object(Carbon\Carbon)[160]
  public 'date' => string '2015-12-01 10:38:41.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)
</code>```

答:
Seems that you just got unlucky because you were testing on the 31st of the month.

However, this is (apparently) a documented feature.  See: http://php.net/manual/en/datetime.createfromformat.php

If you set your format mask "correctly", it works as you'd expect.

```<code>$x = Carbon::createFromFormat   ('m/Y', '04/2009');
$y = DateTime::createFromFormat ('m/Y|', '04/2009');
dd ($x, $y);
</code>```

To avoid ambiguity, the Carbon function is just a wrapper for the underlying DateTime function of PHP; I'm just aiming to prove that this is not a Carbon feature that's causing our headache.

If you test on the 31st of the month, $x above will be read as 31 April 2009 which will be displayed as 1st May.

With the pipe symbol in the mask though, all the non-declared time variables (H, i, s) are set to zero, and date variables (d, m) set to 1, so $y will always respond as you expect regardless of the day of the week.

For me testing at 17:46 in the evening of the 4th day of the month, the above code produces the following:

```<code>Carbon @1233769590 {#219 ▼
    date: 2009-02-04 17:46:30.0 Europe/London (+00:00)
}

DateTime @1233446400 {#217 ▼
    date: 2009-02-01 00:00:00.0 Europe/London (+00:00)
}
</code>```

This is a really weird implementation of date/time function in my opinion.  The only real-world situation that you'd want to use this function in, is if you're reading data from an external source (such as an XML "date" field).

Which programmer on earth would want their program to assume that the missing time (or in your case, day) component of the incoming data, should be taken from the runtime execution time?  It's absolutely crazy bonkers.

Body:
::createFromFormat() results in being one month ahead:

var_dump($_GET['archive']);
var_dump(Carbon::createFromFormat('m/Y', $_GET['archive']));

Result:

string '11/2015' (length=7)
object(Carbon\Carbon)[160]
  public 'date' => string '2015-12-01 10:38:41.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

Body:
Seems that you just got unlucky because you were testing on the 31st of the month.

However, this is (apparently) a documented feature.  See: http://php.net/manual/en/datetime.createfromformat.php

If you set your format mask "correctly", it works as you'd expect.

$x = Carbon::createFromFormat   ('m/Y', '04/2009');
$y = DateTime::createFromFormat ('m/Y|', '04/2009');
dd ($x, $y);

To avoid ambiguity, the Carbon function is just a wrapper for the underlying DateTime function of PHP; I'm just aiming to prove that this is not a Carbon feature that's causing our headache.

If you test on the 31st of the month, $x above will be read as 31 April 2009 which will be displayed as 1st May.

With the pipe symbol in the mask though, all the non-declared time variables (H, i, s) are set to zero, and date variables (d, m) set to 1, so $y will always respond as you expect regardless of the day of the week.

For me testing at 17:46 in the evening of the 4th day of the month, the above code produces the following:

Carbon @1233769590 {#219 ▼
    date: 2009-02-04 17:46:30.0 Europe/London (+00:00)
}

DateTime @1233446400 {#217 ▼
    date: 2009-02-01 00:00:00.0 Europe/London (+00:00)
}

This is a really weird implementation of date/time function in my opinion.  The only real-world situation that you'd want to use this function in, is if you're reading data from an external source (such as an XML "date" field).

Which programmer on earth would want their program to assume that the missing time (or in your case, day) component of the incoming data, should be taken from the runtime execution time?  It's absolutely crazy bonkers.


问:
Removing items in list not corresponding to max value in another list
```<code>model_names = ['is1', 'is5', 'is10', 'im1', 'im5', 'im10']
</code>```

As an example,

```<code>models = [0.1, 0.2, 0.1, 0.3, 0.2, 0.3]
</code>```

The maximum of the list is 0.3, which corresponds to model names 'im1' and 'im10'. I'd like the function

```<code>dominant_model(models)
</code>```

to return

```<code>['im1', 'im10']
</code>```

i.e, the most 'dominant' model(s).

Here's my code which does the job, but I'd like to know if there's a shorter way of doing the same thing rather than all of the conditionals:

```<code>def dominant_model(models):
    m = max(models)
    dom_models = [i for i,j in enumerate(models) if j==m]
    for i in range(len(dom_models)):
        if dom_models[i]==0:
            dom_models[i]=model_names[0]
        elif dom_models[i]==1:
            dom_models[i]=model_names[1]
        elif dom_models[i]==2:
            dom_models[i]=model_names[2]
        elif dom_models[i]==3:
            dom_models[i]=model_names[3]
        elif dom_models[i]==4:
            dom_models[i]=model_names[4]
        elif dom_models[i]==5:
            dom_models[i]=model_names[5]
    return dom_models
</code>```

答:
After finding the max m = max(model), zip the model names to the values and take the names where the value is equal to m .

```<code>def dominant(names, values):
    m = max(values)
    return [name for name, value in zip(names, values) if value == m]
</code>```

Demo

```<code>>>> model_names = ['is1', 'is5', 'is10', 'im1', 'im5', 'im10']
>>> model_values = [0.1, 0.2, 0.1, 0.3, 0.2, 0.3]
>>> dominant(model_names, model_values)
['im1', 'im10']
</code>```

Body:
model_names = ['is1', 'is5', 'is10', 'im1', 'im5', 'im10']

As an example,

models = [0.1, 0.2, 0.1, 0.3, 0.2, 0.3]

The maximum of the list is 0.3, which corresponds to model names 'im1' and 'im10'. I'd like the function

dominant_model(models)

to return

['im1', 'im10']

i.e, the most 'dominant' model(s).

Here's my code which does the job, but I'd like to know if there's a shorter way of doing the same thing rather than all of the conditionals:

def dominant_model(models):
    m = max(models)
    dom_models = [i for i,j in enumerate(models) if j==m]
    for i in range(len(dom_models)):
        if dom_models[i]==0:
            dom_models[i]=model_names[0]
        elif dom_models[i]==1:
            dom_models[i]=model_names[1]
        elif dom_models[i]==2:
            dom_models[i]=model_names[2]
        elif dom_models[i]==3:
            dom_models[i]=model_names[3]
        elif dom_models[i]==4:
            dom_models[i]=model_names[4]
        elif dom_models[i]==5:
            dom_models[i]=model_names[5]
    return dom_models

Body:
After finding the max m = max(model), zip the model names to the values and take the names where the value is equal to m .

def dominant(names, values):
    m = max(values)
    return [name for name, value in zip(names, values) if value == m]

Demo

>>> model_names = ['is1', 'is5', 'is10', 'im1', 'im5', 'im10']
>>> model_values = [0.1, 0.2, 0.1, 0.3, 0.2, 0.3]
>>> dominant(model_names, model_values)
['im1', 'im10']


问:
jQuery Ajax spinner not displaying in IE7
I am trying to display an ajax spinner when loading AJAX content.

The following code appears to work fine in Firefox but not in IE7.  The functions to show and hide the spinner are being called but the browser just does not display it.

Here is the jQuery:

```<code>        $.ajax({
            url: filterorSearch,
            data: {filterParams: JSON.stringify(filters), requestTime: new Date().getTime()},
            beforeSend: function(){
                showLoadingGraphic();
            },
            complete: function(){
                hideLoadingGraphic();
            },
            success: function(data){
                $("#BreakingNews").html(data);
                GetRelatedarticles();
            }
        });

    function showLoadingGraphic() {
        alert("show");
        var showSpinner = $('#page-placeholder-wrapper #main-left').prepend('<div id="ajaxLoader"></div>');
        return showSpinner;
    }

    function hideLoadingGraphic() {
        alert("hide");
        var hideSpinner = $('#ajaxLoader').remove();
        return hideSpinner;
    }
</code>```

And the associated CSS for the spinner:

```<code>#page-placeholder-wrapper #main-left
{
    position:relative;
    }

#ajaxLoader
{
    background:rgba(255,255,255,.7) url("../images/icon-ajax-loading.gif") no-repeat center center;
    height:100%;
    left:0;
    position:absolute;
    top:0;
    width:100%;
    z-index:9999;
    }
</code>```

答:
To get you working try this:

```<code>    background: url("../images/icon-ajax-loading.gif") no-repeat center center rgba(255,255,255,.7);
</code>```

I don't know why the rgba has to be last!

[EDIT]

IE does not support rgba, therefore with it starting on background: it errors and the rest of the line isn't executed for the css

See: Browser Support for RGBa

Body:
I am trying to display an ajax spinner when loading AJAX content.

The following code appears to work fine in Firefox but not in IE7.  The functions to show and hide the spinner are being called but the browser just does not display it.

Here is the jQuery:

        $.ajax({
            url: filterorSearch,
            data: {filterParams: JSON.stringify(filters), requestTime: new Date().getTime()},
            beforeSend: function(){
                showLoadingGraphic();
            },
            complete: function(){
                hideLoadingGraphic();
            },
            success: function(data){
                $("#BreakingNews").html(data);
                GetRelatedarticles();
            }
        });

    function showLoadingGraphic() {
        alert("show");
        var showSpinner = $('#page-placeholder-wrapper #main-left').prepend('

');
        return showSpinner;
    }

    function hideLoadingGraphic() {
        alert("hide");
        var hideSpinner = $('#ajaxLoader').remove();
        return hideSpinner;
    }

And the associated CSS for the spinner:

#page-placeholder-wrapper #main-left
{
    position:relative;
    }

#ajaxLoader
{
    background:rgba(255,255,255,.7) url("../images/icon-ajax-loading.gif") no-repeat center center;
    height:100%;
    left:0;
    position:absolute;
    top:0;
    width:100%;
    z-index:9999;
    }

Body:
To get you working try this:

    background: url("../images/icon-ajax-loading.gif") no-repeat center center rgba(255,255,255,.7);

I don't know why the rgba has to be last!

[EDIT]

IE does not support rgba, therefore with it starting on background: it errors and the rest of the line isn't executed for the css

See: Browser Support for RGBa