问:
Grant permissions to empty Postgres database
I created a new Postgres database using PGAdmin 4. I also created a new user that I only want to access that database. How can I grant the permissions so I can create tables, etc with that new user? Can I do this within PGAdmin? When I try to use Grant Wizard it does not work because no tables exist yet. </p>

答:
SOP USER CREATION IN POSTGRESQL

CREATE ROLE

=> create role priv1 identified by 'priv1';

ALLOWING CONNECT TO DATABASE

=> grant connect on database testdb to priv1;

ALLOWING LOGIN to DATABASE

=> alter role priv1 with login;

GRANT ALL PRIVILEGES

=> grant all on all tables in schema public to priv1;

REVOKE SPECIFIC PRIVILEGES

=> revoke TRUNCATE ON table_name from priv1 ;


来源: stackexchange

问:
applying CSS to ul > li
I am currently using multisites in WP and I am applying minor changes on individual sites instead of the whole network by using Custom CSS plugin.

In our website, nav menu's sub menu consists of two columns but I want to make it 1 column. In chrome inspector I am able to do that easily but however when I am trying to apply it in CSS nothing changes. I am sure that I am doing mistake in linking the div classes and other elements. What I am doing basically is copying the classes name in the inspector and pasting to Custom CSS plugin. Like below

This is the set of classes that I copied from inspector. .header-area .main-menu > ul > li .submenu-wrap ul

```<code>.header-area.main-menu > ul > li .submenu-wrap ul{
   column-count:1;
}
</code>```

but when I do this it does not process.

答:
Try:

```<code>.header-area .main-menu > ul > li .submenu-wrap ul{
  -webkit-column-count: 1;
  -moz-column-count: 1;
  column-count: 1;
}
</code>```

or if that doesn't work try:

```<code>.header-area .main-menu > ul#menu-main-menu > li .submenu-wrap ul{
  -webkit-column-count: 1;
  -moz-column-count: 1;
  column-count: 1;
}
</code>```

What might be happening is that the Custom CSS plugin is placing your new css in the document before the existing css. If that is the case your changes will be overwritten by the existing stylesheet because you are using the same selector. By adding the ID "#menu-main-menu" (just for example in your case) I have given your new selector a higher specificity so it therefore won't be overwritten by the original.

Note:

Does ".header-area" exist on the same element as your ".main-menu" ?
because it is not there in your jsfiddle example. If not, remove it
from your new css.

Check your document after you make the change and confirm in the
inspector that the new css is actually being added to the document,
regardless of whether it works or not. We need to confirm that the
plugin actually works and renders to the page.

ContentLicense: CC BY-SA 3.0

Title: applying CSS to ul > li

Body:
I am currently using multisites in WP and I am applying minor changes on individual sites instead of the whole network by using Custom CSS plugin.

In our website, nav menu's sub menu consists of two columns but I want to make it 1 column. In chrome inspector I am able to do that easily but however when I am trying to apply it in CSS nothing changes. I am sure that I am doing mistake in linking the div classes and other elements. What I am doing basically is copying the classes name in the inspector and pasting to Custom CSS plugin. Like below

This is the set of classes that I copied from inspector. .header-area .main-menu > ul > li .submenu-wrap ul

.header-area.main-menu > ul > li .submenu-wrap ul{
   column-count:1;
}

but when I do this it does not process.

Body:
Try:

.header-area .main-menu > ul > li .submenu-wrap ul{
  -webkit-column-count: 1;
  -moz-column-count: 1;
  column-count: 1;
}

or if that doesn't work try:

.header-area .main-menu > ul#menu-main-menu > li .submenu-wrap ul{
  -webkit-column-count: 1;
  -moz-column-count: 1;
  column-count: 1;
}

What might be happening is that the Custom CSS plugin is placing your new css in the document before the existing css. If that is the case your changes will be overwritten by the existing stylesheet because you are using the same selector. By adding the ID "#menu-main-menu" (just for example in your case) I have given your new selector a higher specificity so it therefore won't be overwritten by the original.

Note:

Does ".header-area" exist on the same element as your ".main-menu" ?
because it is not there in your jsfiddle example. If not, remove it
from your new css.

Check your document after you make the change and confirm in the
inspector that the new css is actually being added to the document,
regardless of whether it works or not. We need to confirm that the
plugin actually works and renders to the page.


问:
Static class to use in many activity?
I making a static class so I can access it in different activity..
I need to pass 1 data to another activity, but I don't know to make it properly.
I tried to use put extra things, but it is for passing data to next activity (not global (maybe)).

this is my class..

```<code>static class AuthorizedUserIdClass
{
    private static Guid _authorizedUserId;

    static Guid AuthorizedUserId
    {
        get { return _authorizedUserId; }
        set { _authorizedUserId = value; }
    }
    static AuthorizedUserIdClass()
    {
        AuthorizedUserId = _authorizedUserId;
    }

}
</code>```

is it right?
then, how to use it in activity? and how to call the filled data in another activity?

Thanks in advance :)

答:
```<code>public class AuthorizedUserIdClass
{
    private static AuthorizedUserIdClass instance;

    public static AuthorizedUserIdClass getInstance() {
        if (instance == null) {
            instance = new AuthorizedUserIdClass();
        }
        return instance;
    }
    private static Guid _authorizedUserId;

    static Guid AuthorizedUserId
    {
        get { return _authorizedUserId; }
        set { _authorizedUserId = value; }
    }

}
</code>```

in your activitys.

```<code>AuthorizedUserIdClass authorizedUserIdClass = AuthorizedUserIdClass.getInstance();
authorizedUserIdClass.set(value);
authorizedUserIdClass.get();
</code>```

Title: Static class to use in many activity?

Body:
I making a static class so I can access it in different activity..
I need to pass 1 data to another activity, but I don't know to make it properly.
I tried to use put extra things, but it is for passing data to next activity (not global (maybe)).

this is my class..

static class AuthorizedUserIdClass
{
    private static Guid _authorizedUserId;

    static Guid AuthorizedUserId
    {
        get { return _authorizedUserId; }
        set { _authorizedUserId = value; }
    }
    static AuthorizedUserIdClass()
    {
        AuthorizedUserId = _authorizedUserId;
    }

}

is it right?
then, how to use it in activity? and how to call the filled data in another activity?

Thanks in advance :)

Body:
public class AuthorizedUserIdClass
{
    private static AuthorizedUserIdClass instance;

    public static AuthorizedUserIdClass getInstance() {
        if (instance == null) {
            instance = new AuthorizedUserIdClass();
        }
        return instance;
    }
    private static Guid _authorizedUserId;

    static Guid AuthorizedUserId
    {
        get { return _authorizedUserId; }
        set { _authorizedUserId = value; }
    }

}

in your activitys.

AuthorizedUserIdClass authorizedUserIdClass = AuthorizedUserIdClass.getInstance();
authorizedUserIdClass.set(value);
authorizedUserIdClass.get();


问:
Django REST Framework Filter Queryset Based On URL
When user visits "baseurl/companies/6/inquiry/", I know that the company_id is 6.

Then user then has the option to create an inquiry with specific products, but should only see the products that belong to company 6.

Here's my viewset:

```<code>class InquiryViewSet(viewsets.ModelViewSet):
    queryset = Inquiry.objects.all()
    serializer_class = InquirySerializer

    def get_serializer(self, *args, **kwargs):
        serializer_class = self.get_serializer_class()
        context = self.get_serializer_context()
        return serializer_class(*args, company_id=self.kwargs['company_id'], context=context, **kwargs)
</code>```

Here's my serializer:

```<code>class InquirySerializer(serializers.ModelSerializer):
    def __init__(self, *args, company_id=None, **kwargs):
        super(InquirySerializer, self).__init__(*args, **kwargs)
        company_set = Company.objects.filter(pk=company_id)
        self.fields['company'].queryset = company_set

    company = serializers.HyperlinkedRelatedField(many=False,
                                                  view_name='company-detail',
                                                  queryset=Company.objects.all())
    inquirer = UserPKField(many=False)
    is_anonymous = serializers.BooleanField
    product_rows = CompanyProductField(many=True, company_id= 'Want to access company_id in __init__')

    class Meta:
        model = Inquiry
        fields = ('pk', 'company', 'inquirer_email', 'inquirer', 'is_anonymous', 'inquiry_date', 'product_rows')
        read_only_fields = ('inquirer', 'inquiry_date')
</code>```

And here's the CompanyProductField

```<code>class CompanyProductField(serializers.PrimaryKeyRelatedField):
    def __init__(self, *args, company_id=None, **kwargs):
        super(CompanyProductField, self).__init__(*args, **kwargs)
        self.company_id = company_id

    def get_queryset(self):
        product_query = Q(company__pk=self.company_id)
        return Product.objects.filter(product_query)
</code>```

There has to be a simple way I can access the company_id that's already in InquirySerializer's init method and just pass that on, but I'm stumped.

答:
You could just remove the self from self.kwargs['company_id'] in yourget_serializer()` method,

```<code>def get_serializer(self, *args, **kwargs):
    serializer_class = self.get_serializer_class()
    kwargs['context'] = self.get_serializer_context()
    return serializer_class(company_id=kwargs['company_id'], *args, **kwargs)
</code>```

Body:
When user visits "baseurl/companies/6/inquiry/", I know that the company_id is 6.

Then user then has the option to create an inquiry with specific products, but should only see the products that belong to company 6.

Here's my viewset:

class InquiryViewSet(viewsets.ModelViewSet):
    queryset = Inquiry.objects.all()
    serializer_class = InquirySerializer

    def get_serializer(self, *args, **kwargs):
        serializer_class = self.get_serializer_class()
        context = self.get_serializer_context()
        return serializer_class(*args, company_id=self.kwargs['company_id'], context=context, **kwargs)

Here's my serializer:

class InquirySerializer(serializers.ModelSerializer):
    def __init__(self, *args, company_id=None, **kwargs):
        super(InquirySerializer, self).__init__(*args, **kwargs)
        company_set = Company.objects.filter(pk=company_id)
        self.fields['company'].queryset = company_set

    company = serializers.HyperlinkedRelatedField(many=False,
                                                  view_name='company-detail',
                                                  queryset=Company.objects.all())
    inquirer = UserPKField(many=False)
    is_anonymous = serializers.BooleanField
    product_rows = CompanyProductField(many=True, company_id= 'Want to access company_id in __init__')

    class Meta:
        model = Inquiry
        fields = ('pk', 'company', 'inquirer_email', 'inquirer', 'is_anonymous', 'inquiry_date', 'product_rows')
        read_only_fields = ('inquirer', 'inquiry_date')

And here's the CompanyProductField

class CompanyProductField(serializers.PrimaryKeyRelatedField):
    def __init__(self, *args, company_id=None, **kwargs):
        super(CompanyProductField, self).__init__(*args, **kwargs)
        self.company_id = company_id

    def get_queryset(self):
        product_query = Q(company__pk=self.company_id)
        return Product.objects.filter(product_query)

There has to be a simple way I can access the company_id that's already in InquirySerializer's init method and just pass that on, but I'm stumped.

Body:
You could just remove the self from self.kwargs['company_id'] in yourget_serializer()` method,

def get_serializer(self, *args, **kwargs):
    serializer_class = self.get_serializer_class()
    kwargs['context'] = self.get_serializer_context()
    return serializer_class(company_id=kwargs['company_id'], *args, **kwargs)


问:
d3 line chart runs off the chart when threshold values are applied
I am new to d3 and working with line chart, where i want to view the chart between the threshold values Fiddler. The chart works fine with y.domain([min,max]), since i want to view the chart with my own threshold values the line runs off the chart, i've no idea why this is happening. Any help is much appreciated.

答:
The reason why you get a broken graph is that, the values after 26 April is less than 75 which is the minimum you have defined. So the graph is actually drawing, but you can't see the lines because it is below the svg area you defined.

Here is my 2 cents.

Just update the data with correct values. So that you can view the data at the end.

```<code>{
    date: "1-May-12",
    close: "90.13"
}
</code>```

or

Just update the min value to the minimum expected value.

```<code>var thresholdValues = {
    minValue: 50,
    maxValue: 100
};
</code>```

This is what I did and seems it works fine. Here is the fiddle link for the same http://jsfiddle.net/vxo1qsf9/1/

If you want to automatically find the minimum and maximum value from data, use d3's native function d3.extent(), which returns an array containing min and max value of that array or you can also try finding  min and max separately by using d3.min() and d3.max().

Here is the documentation link for d3 array methods.

Hope this helps! :)

Body:
The reason why you get a broken graph is that, the values after 26 April is less than 75 which is the minimum you have defined. So the graph is actually drawing, but you can't see the lines because it is below the svg area you defined.

Here is my 2 cents.

Just update the data with correct values. So that you can view the data at the end.

{
    date: "1-May-12",
    close: "90.13"
}

or

Just update the min value to the minimum expected value.

var thresholdValues = {
    minValue: 50,
    maxValue: 100
};

This is what I did and seems it works fine. Here is the fiddle link for the same http://jsfiddle.net/vxo1qsf9/1/

If you want to automatically find the minimum and maximum value from data, use d3's native function d3.extent(), which returns an array containing min and max value of that array or you can also try finding  min and max separately by using d3.min() and d3.max().

Here is the documentation link for d3 array methods.

Hope this helps! :)

ContentLicense: CC BY-SA 4.0


问:
wholesale replacement of options html string within select?
I would like to 'toggle' the list of options in a select box.

I have the two sets of options as strings (American states and Canadian Provinces). However, I notice that in the DOM, the select object has no 'innerhtml' property (at least not according to w3schools).

Do I have to go and remove and replace the options one by one? How do I do this?

答:
When you say they are held as strings - do you mean that each item is a seperate string or that the list items are one string (i.e. var variable = "
item 1

item 2
";)

If the latter, could you not include the <select> tag in the string and use the jQuery replaceWith function?

ContentLicense: CC BY-SA 2.5

Body:
When you say they are held as strings - do you mean that each item is a seperate string or that the list items are one string (i.e. var variable = "<li>item 1</li><li>item 2</li>";)

If the latter, could you not include the <select> tag in the string and use the jQuery replaceWith function?


答:
Put extra pass data one activity to another activity. If you want to access value to whole application label you can use global variable just like

create a class extend of application for storing value application label

```<code> public class GlobalVariable extends Application {

   private String message;

   public String getMessage() {
      return message;
   }

   public void setMessage(String message) {
      this.message = message;
   }
 }
</code>```

Add GlobalVariable to AndroidManifest.xml

```<code><application
  android:name=".GlobalVariable"
  android:icon="@mipmap/ic_launcher"
  android:label="@string/app_name">
  //........
</application>
</code>```

Set Value to global variable like

```<code>GlobalVariable globalVariable = ((GlobalVariable) getApplicationContext());
globalVariable.setMessage("Hello");
</code>```

Finally get value from Activity like

```<code>GlobalVariable globalVariable = ((GlobalVariable)getApplicationContext());
Stirng message = globalVariable.getMessage();
</code>```

Title: Static class to use in many activity?

Body:
Put extra pass data one activity to another activity. If you want to access value to whole application label you can use global variable just like

create a class extend of application for storing value application label

 public class GlobalVariable extends Application {

   private String message;

   public String getMessage() {
      return message;
   }

   public void setMessage(String message) {
      this.message = message;
   }
 }

Add GlobalVariable to AndroidManifest.xml

<application
  android:name=".GlobalVariable"
  android:icon="@mipmap/ic_launcher"
  android:label="@string/app_name">
  //........
</application>

Set Value to global variable like

GlobalVariable globalVariable = ((GlobalVariable) getApplicationContext());
globalVariable.setMessage("Hello");

Finally get value from Activity like

GlobalVariable globalVariable = ((GlobalVariable)getApplicationContext());
Stirng message = globalVariable.getMessage();


问:
Azure Automation script to request OMS
i wrote an Automation script in PowerShell which give me every morning a report about our azure subscriptions (Vm, Automation jobs, alerts, ...).
Now, i'm adding a new function wich works well from my computer but fails when run from Automation and i don't find how to make it works.

Works well from my computer (VS code / PS 5.1 / PS 4.0)

```<code>$omsRGname = "xxx"
$omsWorkspaceName = "xxx"
$omsQueryThreat = 'Type=ProtectionStatus ThreatStatusRank!=150 ThreatStatusRank!=470 | select Computer,Threat,ThreatStatus'
$ArrayThreat = New-Object System.Collections.ArrayList

function OmsRequest {
    Param(
        [parameter(Position = 0, Mandatory = $true)]
        $omsRG,
        [parameter(Position = 1, Mandatory = $true)]
        $omsWorkspace,
        [parameter(Position = 2, Mandatory = $true)]
        $omsQuery
    )
    Process {
        Import-Module AzureRm.OperationalInsights
        $error.clear()
        $Result.clear
        $script:Result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $omsRG -WorkspaceName $omsWorkspace -Query $omsQuery
        $reqIdParts = $Result.Id.Split("/")
        $reqId = $reqIdParts[$reqIdParts.Count - 1]
        $wait = Get-Date
        while ($Result.Metadata.Status -eq "Pending" -and $error.Count -eq 0) {
            $Result = Get-AzureRmOperationalInsightsSearchResults -WorkspaceName $omsWorkspace -ResourceGroupName $omsRG -Id $reqId
            #debug
            $elapsedTime = $(get-date) - $wait
            Write-Output "Elapsed: $elapsedTime -- Status: $($Result.Metadata.Status)"
            Write-Output "Count: $($Result.Count)"
        }
    }
}

OmsRequest $omsRGname $omsWorkspaceName $omsQueryThreat
#debug
Write-Output "VALUEOUT:" $Result.Value
#
$OMSComputers = $Result.Value | ConvertFrom-Json
if ($OMSComputers) {
    foreach ( $ThreatDetails in $OMSComputers) {
        <#write "$(get-date($ThreatDetails.__metadata.TimeGenerated) -format G) - $($ThreatDetails.Computer) - $($ThreatDetails.Threat) - $($ThreatDetails.ThreatStatus)"#>
        $ThDetails = [PSCustomObject] @{
            Date         = (get-date($ThreatDetails.__metadata.TimeGenerated) -format G);
            Computer     = $ThreatDetails.Computer;
            Threat       = $ThreatDetails.Threat;
            ThreatStatus = $ThreatDetails.ThreatStatus;
        }
        $ArrayThreat.Add($ThDetails) |Out-Null
    }
}
else {Write-Output "OK"}

$ArrayThreat
</code>```

from my local computer

```<code>Elapsed: 00:00:00.4270000 -- Status: Successful
Count: 1

Date                Computer      Threat                   ThreatStatus
----                --------      ------                   ------------
29/06/2017 12:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 11:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 10:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 09:55:38 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 08:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 08:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 07:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 07:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 06:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 06:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
</code>```

When i run my code from Automation, i get this error

```<code>ConvertFrom-Json : The input object cannot be bound to any parameters for the command either because the command does
not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:164 char:33
+ $OMSComputers = $Result.Value | ConvertFrom-Json
+                                 ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: ({
  "Computer"...ng": {}
  }
}:JObject) [ConvertFrom-Json], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
</code>```

Well, my error is here

```<code>$OMSComputers = $Result.Value | ConvertFrom-Json
</code>```

When i look into its value, i get this (just took one property from the list given by $Result.Value)

```<code>VALUEOUT:

Name                       : Computer
Type                       : Property
HasValues                  : True
First                      : {}
Last                       : {}
Count                      : 1
Parent                     : {Computer, Threat, ThreatStatus, __metadata}
Root                       : {Computer, Threat, ThreatStatus, __metadata}
Next                       : {}
Previous                   :
Path                       : Computer
LineNumber                 : 0
LinePosition               : 0
IsReadOnly                 : False
AllowNew                   : True
AllowEdit                  : True
AllowRemove                : True
SupportsChangeNotification : True
SupportsSearching          : False
SupportsSorting            : False
IsSorted                   : False
SortProperty               :
SortDirection              : Ascending
IsFixedSize                : False
SyncRoot                   : System.Object
IsSynchronized             : False
</code>```

isee this line

```<code>Keys                       : {Computer, Threat, ThreatStatus, __metadata}
</code>```

i've tried to parse it as a hashtable, but with no result.

Does anyone have any other creative ways to solve this?
Thanks

Edit:
I've only past my function here. But in the full script i'm well connected and the PS module is already there (if not the function fail telling me, the RG can not be found, but in spite of, i click and add the module from your Link).
If i look at the $result content i get the query result.

```<code>{
    "Computer": "xxx.local",
    "Threat": "Virus:ALisp/Bursted.DT",
    "ThreatStatus": "Quarantined",
    "__metadata": {
        "Type": "ProtectionStatus",
        "TimeGenerated": "2017-06-29T10:55:37.77Z",
        "highlighting": {}
    }
}
</code>```

when i ask for its type

```<code>Newtonsoft.Json.Linq.JObject
</code>```

So i import the Newtonsoft.Json module and try to convert from this kind of Json but it's failing too.

It's looks like my OMS query is working (i have a result in $Result) but when Automation try to convert with 'ConvertFrom-Json', it fails.

```<code>#debug
Write-Output "VALUEOUT:"
Write-Output "Get-variable RESULT"
Get-Variable Result -ValueOnly |format-list
$OMSComputers = $Result.Value | ConvertFrom-Json
</code>```

Output:

```<code>    VALUEOUT:
    Get-variable RESULT

    Id       : subscriptions/xxx/providers/Microsoft.Operatio
               nalInsights/workspaces/xxx/search/xxx|10.1.0.27|2017-07-05T14-33-52Z
    Metadata : Microsoft.Azure.Commands.OperationalInsights.Models.PSSearchMetadata
    Error    :
    Value    : {"Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T10:55:37.77Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T09:48:28.42Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T08:55:37.757Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T07:55:38.327Z",
                 "highlighting": {}
               }...}

ConvertFrom-Json : The input object cannot be bound to any parameters for the command either because the command does

not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

At line:65 char:33

+ $OMSComputers = $Result.Value | ConvertFrom-Json

+                                 ~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: ({

  "Computer"...ng": {}

  }

}:JObject) [ConvertFrom-Json], ParameterBindingException

    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
</code>```

I don't get why the ConvertFrom-Json fail :/

答:
In Azure automation account, it does not support import module by using Import-Module AzureRm.OperationalInsights. Your error root reason is $script:Result is null. You need import AzureRm.OperationalInsights to your Azure automation account. Please refer to this following steps:

1.Open the link.

2.Click Deploy to Azure Automation.

3.Delete Import-Module AzureRm.OperationalInsights in your runbook.

Note: When you execute Get-AzureRmOperationalInsightsSearchResults, you need login to Azure in the runbook, according to your runbook, it seems that you don't have the step. If you don't do it, please add it to your runbook.

The following runbook works for me.

```<code>$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName

    "Logging in to Azure..."
    Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

##
$omsRGname = "shuivm"
$omsWorkspaceName = "shuitest"
$omsQueryThreat = 'Type=ProtectionStatus ThreatStatusRank!=150 ThreatStatusRank!=470 | select Computer,Threat,ThreatStatus'
$ArrayThreat = New-Object System.Collections.ArrayList

function OmsRequest {
    Param(
        [parameter(Position = 0, Mandatory = $true)]
        $omsRG,
        [parameter(Position = 1, Mandatory = $true)]
        $omsWorkspace,
        [parameter(Position = 2, Mandatory = $true)]
        $omsQuery
    )
    Process {

        $error.clear()
        $Result.clear
        $script:Result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $omsRG -WorkspaceName $omsWorkspace -Query $omsQuery
        $reqIdParts = $Result.Id.Split("/")
        $reqId = $reqIdParts[$reqIdParts.Count - 1]
        $wait = Get-Date
        while ($Result.Metadata.Status -eq "Pending" -and $error.Count -eq 0) {
            $Result = Get-AzureRmOperationalInsightsSearchResults -WorkspaceName $omsWorkspace -ResourceGroupName $omsRG -Id $reqId
            #debug
            $elapsedTime = $(get-date) - $wait
            Write-Output "Elapsed: $elapsedTime -- Status: $($Result.Metadata.Status)"
            Write-Output "Count: $($Result.Count)"
        }
    }
}

OmsRequest $omsRGname $omsWorkspaceName $omsQueryThreat
#debug
Write-Output "VALUEOUT:" $Result.Value
#
$OMSComputers = $Result.Value | ConvertFrom-Json
if ($OMSComputers) {
    foreach ( $ThreatDetails in $OMSComputers) {
        <#write "$(get-date($ThreatDetails.__metadata.TimeGenerated) -format G) - $($ThreatDetails.Computer) - $($ThreatDetails.Threat) - $($ThreatDetails.ThreatStatus)"#>
        $ThDetails = [PSCustomObject] @{
            Date         = (get-date($ThreatDetails.__metadata.TimeGenerated) -format G);
            Computer     = $ThreatDetails.Computer;
            Threat       = $ThreatDetails.Threat;
            ThreatStatus = $ThreatDetails.ThreatStatus;
        }
        $ArrayThreat.Add($ThDetails) |Out-Null
    }
}
else {Write-Output "OK"}

$ArrayThreat
</code>```

Title: Azure Automation script to request OMS

Body:
i wrote an Automation script in PowerShell which give me every morning a report about our azure subscriptions (Vm, Automation jobs, alerts, ...).
Now, i'm adding a new function wich works well from my computer but fails when run from Automation and i don't find how to make it works.

Works well from my computer (VS code / PS 5.1 / PS 4.0)

$omsRGname = "xxx"
$omsWorkspaceName = "xxx"
$omsQueryThreat = 'Type=ProtectionStatus ThreatStatusRank!=150 ThreatStatusRank!=470 | select Computer,Threat,ThreatStatus'
$ArrayThreat = New-Object System.Collections.ArrayList

function OmsRequest {
    Param(
        [parameter(Position = 0, Mandatory = $true)]
        $omsRG,
        [parameter(Position = 1, Mandatory = $true)]
        $omsWorkspace,
        [parameter(Position = 2, Mandatory = $true)]
        $omsQuery
    )
    Process {
        Import-Module AzureRm.OperationalInsights
        $error.clear()
        $Result.clear
        $script:Result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $omsRG -WorkspaceName $omsWorkspace -Query $omsQuery
        $reqIdParts = $Result.Id.Split("/")
        $reqId = $reqIdParts[$reqIdParts.Count - 1]
        $wait = Get-Date
        while ($Result.Metadata.Status -eq "Pending" -and $error.Count -eq 0) {
            $Result = Get-AzureRmOperationalInsightsSearchResults -WorkspaceName $omsWorkspace -ResourceGroupName $omsRG -Id $reqId
            #debug
            $elapsedTime = $(get-date) - $wait
            Write-Output "Elapsed: $elapsedTime -- Status: $($Result.Metadata.Status)"
            Write-Output "Count: $($Result.Count)"
        }
    }
}

OmsRequest $omsRGname $omsWorkspaceName $omsQueryThreat
#debug
Write-Output "VALUEOUT:" $Result.Value
#
$OMSComputers = $Result.Value | ConvertFrom-Json
if ($OMSComputers) {
    foreach ( $ThreatDetails in $OMSComputers) {
        <#write "$(get-date($ThreatDetails.__metadata.TimeGenerated) -format G) - $($ThreatDetails.Computer) - $($ThreatDetails.Threat) - $($ThreatDetails.ThreatStatus)"#>
        $ThDetails = [PSCustomObject] @{
            Date         = (get-date($ThreatDetails.__metadata.TimeGenerated) -format G);
            Computer     = $ThreatDetails.Computer;
            Threat       = $ThreatDetails.Threat;
            ThreatStatus = $ThreatDetails.ThreatStatus;
        }
        $ArrayThreat.Add($ThDetails) |Out-Null
    }
}
else {Write-Output "OK"}

$ArrayThreat

from my local computer

Elapsed: 00:00:00.4270000 -- Status: Successful
Count: 1

Date                Computer      Threat                   ThreatStatus
----                --------      ------                   ------------
29/06/2017 12:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 11:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 10:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 09:55:38 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 08:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 08:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 07:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 07:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 06:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 06:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined

When i run my code from Automation, i get this error

ConvertFrom-Json : The input object cannot be bound to any parameters for the command either because the command does
not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:164 char:33
+ $OMSComputers = $Result.Value | ConvertFrom-Json
+                                 ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: ({
  "Computer"...ng": {}
  }
}:JObject) [ConvertFrom-Json], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

Well, my error is here

$OMSComputers = $Result.Value | ConvertFrom-Json

When i look into its value, i get this (just took one property from the list given by $Result.Value)

VALUEOUT:

Name                       : Computer
Type                       : Property
HasValues                  : True
First                      : {}
Last                       : {}
Count                      : 1
Parent                     : {Computer, Threat, ThreatStatus, __metadata}
Root                       : {Computer, Threat, ThreatStatus, __metadata}
Next                       : {}
Previous                   :
Path                       : Computer
LineNumber                 : 0
LinePosition               : 0
IsReadOnly                 : False
AllowNew                   : True
AllowEdit                  : True
AllowRemove                : True
SupportsChangeNotification : True
SupportsSearching          : False
SupportsSorting            : False
IsSorted                   : False
SortProperty               :
SortDirection              : Ascending
IsFixedSize                : False
SyncRoot                   : System.Object
IsSynchronized             : False

isee this line

Keys                       : {Computer, Threat, ThreatStatus, __metadata}

i've tried to parse it as a hashtable, but with no result.

Does anyone have any other creative ways to solve this?
Thanks

Edit:
I've only past my function here. But in the full script i'm well connected and the PS module is already there (if not the function fail telling me, the RG can not be found, but in spite of, i click and add the module from your Link).
If i look at the $result content i get the query result.

{
    "Computer": "xxx.local",
    "Threat": "Virus:ALisp/Bursted.DT",
    "ThreatStatus": "Quarantined",
    "__metadata": {
        "Type": "ProtectionStatus",
        "TimeGenerated": "2017-06-29T10:55:37.77Z",
        "highlighting": {}
    }
}

when i ask for its type

Newtonsoft.Json.Linq.JObject

So i import the Newtonsoft.Json module and try to convert from this kind of Json but it's failing too.

It's looks like my OMS query is working (i have a result in $Result) but when Automation try to convert with 'ConvertFrom-Json', it fails.

#debug
Write-Output "VALUEOUT:"
Write-Output "Get-variable RESULT"
Get-Variable Result -ValueOnly |format-list
$OMSComputers = $Result.Value | ConvertFrom-Json

Output:

    VALUEOUT:
    Get-variable RESULT

    Id       : subscriptions/xxx/providers/Microsoft.Operatio
               nalInsights/workspaces/xxx/search/xxx|10.1.0.27|2017-07-05T14-33-52Z
    Metadata : Microsoft.Azure.Commands.OperationalInsights.Models.PSSearchMetadata
    Error    :
    Value    : {"Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T10:55:37.77Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T09:48:28.42Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T08:55:37.757Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T07:55:38.327Z",
                 "highlighting": {}
               }...}

ConvertFrom-Json : The input object cannot be bound to any parameters for the command either because the command does

not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

At line:65 char:33

+ $OMSComputers = $Result.Value | ConvertFrom-Json

+                                 ~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: ({

  "Computer"...ng": {}

  }

}:JObject) [ConvertFrom-Json], ParameterBindingException

    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

I don't get why the ConvertFrom-Json fail :/

Body:
In Azure automation account, it does not support import module by using Import-Module AzureRm.OperationalInsights. Your error root reason is $script:Result is null. You need import AzureRm.OperationalInsights to your Azure automation account. Please refer to this following steps:

1.Open the link.

2.Click Deploy to Azure Automation.

3.Delete Import-Module AzureRm.OperationalInsights in your runbook.

Note: When you execute Get-AzureRmOperationalInsightsSearchResults, you need login to Azure in the runbook, according to your runbook, it seems that you don't have the step. If you don't do it, please add it to your runbook.

The following runbook works for me.

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName

    "Logging in to Azure..."
    Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

##
$omsRGname = "shuivm"
$omsWorkspaceName = "shuitest"
$omsQueryThreat = 'Type=ProtectionStatus ThreatStatusRank!=150 ThreatStatusRank!=470 | select Computer,Threat,ThreatStatus'
$ArrayThreat = New-Object System.Collections.ArrayList

function OmsRequest {
    Param(
        [parameter(Position = 0, Mandatory = $true)]
        $omsRG,
        [parameter(Position = 1, Mandatory = $true)]
        $omsWorkspace,
        [parameter(Position = 2, Mandatory = $true)]
        $omsQuery
    )
    Process {

        $error.clear()
        $Result.clear
        $script:Result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $omsRG -WorkspaceName $omsWorkspace -Query $omsQuery
        $reqIdParts = $Result.Id.Split("/")
        $reqId = $reqIdParts[$reqIdParts.Count - 1]
        $wait = Get-Date
        while ($Result.Metadata.Status -eq "Pending" -and $error.Count -eq 0) {
            $Result = Get-AzureRmOperationalInsightsSearchResults -WorkspaceName $omsWorkspace -ResourceGroupName $omsRG -Id $reqId
            #debug
            $elapsedTime = $(get-date) - $wait
            Write-Output "Elapsed: $elapsedTime -- Status: $($Result.Metadata.Status)"
            Write-Output "Count: $($Result.Count)"
        }
    }
}

OmsRequest $omsRGname $omsWorkspaceName $omsQueryThreat
#debug
Write-Output "VALUEOUT:" $Result.Value
#
$OMSComputers = $Result.Value | ConvertFrom-Json
if ($OMSComputers) {
    foreach ( $ThreatDetails in $OMSComputers) {
        <#write "$(get-date($ThreatDetails.__metadata.TimeGenerated) -format G) - $($ThreatDetails.Computer) - $($ThreatDetails.Threat) - $($ThreatDetails.ThreatStatus)"#>
        $ThDetails = [PSCustomObject] @{
            Date         = (get-date($ThreatDetails.__metadata.TimeGenerated) -format G);
            Computer     = $ThreatDetails.Computer;
            Threat       = $ThreatDetails.Threat;
            ThreatStatus = $ThreatDetails.ThreatStatus;
        }
        $ArrayThreat.Add($ThDetails) |Out-Null
    }
}
else {Write-Output "OK"}

$ArrayThreat


问:
How to show exact match (either word or sentence) result first and then others in elastic search?
Hi is any query in the elastic search which will display exact match (either word or sentence) results first and then partial match results.please help me into this?</p>

答: You can use multi-match queries and boost exact matches. Chech https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html</p>


问:
NameError while calling module, declaring default values in a class function
I'm trying to understand Public Key encryption so I wrote this little module using PyCryptodome and the RSA/PKCS1_OAEP module on Python 3 to help me along. However, I keep getting an error:

NameError: name 'aesenc' is not defined

This is a two part question:

In standalone code (outside a class) the arg = default_val code will work, but I'm pretty sure this code will throw an error (assuming I fix question #2). I also know I can't use self.default_val as that needs an object to be created first. How do I assign a default value (in this case, the private/public key of the object?)

With regard to the error message, a vgrep reveals that the suite has been declared before its been called but I still get the NameError. Can someone please take a look and let me know what I'm doing wrong?

Modules: (Breaking into parts as SO keeps jumbling the code)

```<code>from passlib.context import CryptContext
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Random import get_random_bytes
</code>```

The Class:

```<code>class statEnc:
    pubcipher = None
    privcipher = None
    pubkeystr = None
    privkeystr = None
    sessionkey = None

    def __init__(self, pubkeystr = None, privkeystr = None, sessionkey = None):
        self.pubkeystr = pubkeystr
        self.privkeystr = privkeystr
        self.sessionkey = sessionkey
        if pubkeystr == None or privkeystr == None:  #if blank, generate keys
            self.random_generator = Random.new().read
            self.keys = RSA.generate(1024, self.random_generator)
            self.pubkey = self.keys.publickey()
            self.pubkeystr = self.pubkey.exportKey(format='PEM',
                                            passphrase=None,
                                            pkcs=1)
            self.pubcipher = PKCS1_OAEP.new(self.pubkey)
            self.privcipher = PKCS1_OAEP.new(self.keys)
            self.privkeystr = self.keys.exportKey(format='PEM',
                                                passphrase=None,
                                                pkcs=1)
            self.privkey = self.keys.exportKey()
        else:  #import the keys
            self.pubkey = RSA.importKey(pubkeystr)
            self.pubcipher = PKCS1_OAEP.new(pubkey)
            self.privkey = RSA.importKey(privkeystr)
            self.pubcipher = PKCS1_OAEP.new(privkey)
            if sessionkey == None:
                sessionkey = get_random_bytes(16)
            else:
                self.sessionkey = sessionkey

    def encrypt_val(self, session_key, cipher = pubcipher):
        # a little ditty to hep encrypt the AES session key
        try:
            session_key = session_key.encode('utf8')
        except:
            pass
        ciphertext = cipher.encrypt(session_key)
        return ciphertext

    def decrypt_val(self, ciphertext, cipher = privcipher):
        # a little ditty to hep decrypt the AES session key
        session_key = cipher.decrypt(ciphertext)
        try:
            session_key = session_key.decode('utf8')
        except:
            pass
        return session_key

    def aesenc(self, data, *args):
        #encrypt the payload using AES
        key = ''
        if args:
            if 'str' in str(type(args[0])):
                try:
                    key = int(args[0])
                except:
                    key = get_random_bytes(16)
        else:
            key = get_random_bytes(16)
        try:
            data = data.encode('utf8')
        except:
            pass
        cipher = AES.new(key, AES.MODE_EAX)
        ciphertext, tag = cipher.encrypt_and_digest(data)
        aesencdict = {
        'ciphertext' : ciphertext,
        'tag' : tag,
        'nonce' : cipher.nonce ,
        'key' : key
        }
        return(aesencdict)

    def aesdec(self, aesdict):
        #decrypt the AES encrypted payload
        cipher = AES.new(aesdict['key'], AES.MODE_EAX, aesdict['nonce'])
        data = cipher.decrypt_and_verify(aesdict['ciphertext'], aesdict['tag'])
        try:
            data = data.decode('utf8')
        except:
            pass
        return data

    def end2enc(self, val, cipher = pubcipher):
        # a master function to first encrypt the payload
        val = str(val)
        encval = aesenc(val)
        # and then PK encrypt the key
        encval['key'] = encrypt_val(encval['key'], cipher)
        return encval

    def end2dec(self, encval, cipher = privcipher):
        encval['key'] = decrypt_val(encval['key'], cipher)
        outval = aesdec(encval['aesdict'], encval['key'])
        return outval
</code>```

Test function and main:

```<code>def test():
    val = { 'test' : "hello"}
    keypair = statEnc()
    print(str(type(keypair)))
    encval = keypair.end2enc(val, keypair.pubcipher)
    outval = keypair.end2dec(encval, keypair.privcipher)
    print(val, outval)
    if val == eval(outval):
        return(val)
    else:
        return False

if __name__ == '__main__':
    test()
</code>```

[UPDATE]
The Traceback is as follows:

```<code>[guha@katana stat]$ python statenc.py
<class '__main__.statEnc'>
Traceback (most recent call last):
  File "statenc.py", line 124, in <module>
    test()
  File "statenc.py", line 115, in test
    encval = keypair.end2enc(val, keypair.pubcipher)
  File "statenc.py", line 100, in end2enc
    encval = aesenc(val)
NameError: name 'aesenc' is not defined
</code>```

答:
Slept over my question and woke up with a fresh mind, and voila! the answer presented itself.

The answer to the second question is as follows:
2. putting a simple 'self.' solves the problem - i was calling 'aesenc(params)' instead of 'self.aesenc(params)'. Stupid of me, really.

Question 1 is answered in this SO question.

Body:
I'm trying to understand Public Key encryption so I wrote this little module using PyCryptodome and the RSA/PKCS1_OAEP module on Python 3 to help me along. However, I keep getting an error:

NameError: name 'aesenc' is not defined

This is a two part question:

In standalone code (outside a class) the arg = default_val code will work, but I'm pretty sure this code will throw an error (assuming I fix question #2). I also know I can't use self.default_val as that needs an object to be created first. How do I assign a default value (in this case, the private/public key of the object?)

With regard to the error message, a vgrep reveals that the suite has been declared before its been called but I still get the NameError. Can someone please take a look and let me know what I'm doing wrong?

Modules: (Breaking into parts as SO keeps jumbling the code)

from passlib.context import CryptContext
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Random import get_random_bytes

The Class:

class statEnc:
    pubcipher = None
    privcipher = None
    pubkeystr = None
    privkeystr = None
    sessionkey = None

    def __init__(self, pubkeystr = None, privkeystr = None, sessionkey = None):
        self.pubkeystr = pubkeystr
        self.privkeystr = privkeystr
        self.sessionkey = sessionkey
        if pubkeystr == None or privkeystr == None:  #if blank, generate keys
            self.random_generator = Random.new().read
            self.keys = RSA.generate(1024, self.random_generator)
            self.pubkey = self.keys.publickey()
            self.pubkeystr = self.pubkey.exportKey(format='PEM',
                                            passphrase=None,
                                            pkcs=1)
            self.pubcipher = PKCS1_OAEP.new(self.pubkey)
            self.privcipher = PKCS1_OAEP.new(self.keys)
            self.privkeystr = self.keys.exportKey(format='PEM',
                                                passphrase=None,
                                                pkcs=1)
            self.privkey = self.keys.exportKey()
        else:  #import the keys
            self.pubkey = RSA.importKey(pubkeystr)
            self.pubcipher = PKCS1_OAEP.new(pubkey)
            self.privkey = RSA.importKey(privkeystr)
            self.pubcipher = PKCS1_OAEP.new(privkey)
            if sessionkey == None:
                sessionkey = get_random_bytes(16)
            else:
                self.sessionkey = sessionkey

    def encrypt_val(self, session_key, cipher = pubcipher):
        # a little ditty to hep encrypt the AES session key
        try:
            session_key = session_key.encode('utf8')
        except:
            pass
        ciphertext = cipher.encrypt(session_key)
        return ciphertext

    def decrypt_val(self, ciphertext, cipher = privcipher):
        # a little ditty to hep decrypt the AES session key
        session_key = cipher.decrypt(ciphertext)
        try:
            session_key = session_key.decode('utf8')
        except:
            pass
        return session_key

    def aesenc(self, data, *args):
        #encrypt the payload using AES
        key = ''
        if args:
            if 'str' in str(type(args[0])):
                try:
                    key = int(args[0])
                except:
                    key = get_random_bytes(16)
        else:
            key = get_random_bytes(16)
        try:
            data = data.encode('utf8')
        except:
            pass
        cipher = AES.new(key, AES.MODE_EAX)
        ciphertext, tag = cipher.encrypt_and_digest(data)
        aesencdict = {
        'ciphertext' : ciphertext,
        'tag' : tag,
        'nonce' : cipher.nonce ,
        'key' : key
        }
        return(aesencdict)

    def aesdec(self, aesdict):
        #decrypt the AES encrypted payload
        cipher = AES.new(aesdict['key'], AES.MODE_EAX, aesdict['nonce'])
        data = cipher.decrypt_and_verify(aesdict['ciphertext'], aesdict['tag'])
        try:
            data = data.decode('utf8')
        except:
            pass
        return data

    def end2enc(self, val, cipher = pubcipher):
        # a master function to first encrypt the payload
        val = str(val)
        encval = aesenc(val)
        # and then PK encrypt the key
        encval['key'] = encrypt_val(encval['key'], cipher)
        return encval

    def end2dec(self, encval, cipher = privcipher):
        encval['key'] = decrypt_val(encval['key'], cipher)
        outval = aesdec(encval['aesdict'], encval['key'])
        return outval

Test function and main:

def test():
    val = { 'test' : "hello"}
    keypair = statEnc()
    print(str(type(keypair)))
    encval = keypair.end2enc(val, keypair.pubcipher)
    outval = keypair.end2dec(encval, keypair.privcipher)
    print(val, outval)
    if val == eval(outval):
        return(val)
    else:
        return False

if __name__ == '__main__':
    test()

[UPDATE]
The Traceback is as follows:

[guha@katana stat]$ python statenc.py
<class '__main__.statEnc'>
Traceback (most recent call last):
  File "statenc.py", line 124, in <module>
    test()
  File "statenc.py", line 115, in test
    encval = keypair.end2enc(val, keypair.pubcipher)
  File "statenc.py", line 100, in end2enc
    encval = aesenc(val)
NameError: name 'aesenc' is not defined


问:
How to fetch last row using distinct and group by same column
I want to retrieve balance of last row from table  using distinct accountid from last ledgerid

```<code>|---ledgerid---|--accountid--|--blance--|
|     1        |      1      |    500   |
|     2        |      1      |    800   |
</code>```

i want output as

```<code>|---ledgerid---|--accountid--|--blance--|
|     2        |      1      |    800   |
</code>```

答:
Try this:      -

select * from table_name where accountid=1 order by legerid desc limit 1

Body:
I want to retrieve balance of last row from table  using distinct accountid from last ledgerid

|---ledgerid---|--accountid--|--blance--|
|     1        |      1      |    500   |
|     2        |      1      |    800   |

i want output as

|---ledgerid---|--accountid--|--blance--|
|     2        |      1      |    800   |


问:
How to close/copy a specific git branch contents to a folder on another server using ssh
I have a repo on bitbucket and there are couple of branches in it. All the latest code is pushed to release branch after working locally. I have an instance of my website on another server which I connect using ssh. In that server there is a folder MyWebsite(/var/www/html/MyWebsite). I need to copy all the content from the release branch to folder MyWebsite so that the website functions as per the latest code.

After navigating into the MyWebsite folder using ssh, I tried using

```<code>git clone -b release <bit-bucket repo url>

git clone -b master  <bit-bucket repo url> release `In this case I thought the content in release branch is moved to master but I'm wrong`

git fetch -b release <bit-bucket repo url> =>  Not a git repository (or any of the parent directories): .git error
</code>```

Can someone help in solving this. TIA

答:
And in the server, I did git init, and then git add remote release <bit-bucket repo url> and then did git fetch release. But then I don't see any files in the folder

Yes, git fetch only fetches the history. It does not checkout any branch.

See all the branches with git branch -avv.

Try, on that server in your ssh session, a git checkout -b <branch> --track release/<branch>.

Note: if your remote is not called 'release', replace release with the name of your remote.

Indeed, the OP ASN added in the comments:

I created a new folder again, changed the names of remote and then I tried again.

  So now it was able to pull everything from release branch.

Body:
I have a repo on bitbucket and there are couple of branches in it. All the latest code is pushed to release branch after working locally. I have an instance of my website on another server which I connect using ssh. In that server there is a folder MyWebsite(/var/www/html/MyWebsite). I need to copy all the content from the release branch to folder MyWebsite so that the website functions as per the latest code.

After navigating into the MyWebsite folder using ssh, I tried using

git clone -b release <bit-bucket repo url>

git clone -b master  <bit-bucket repo url> release `In this case I thought the content in release branch is moved to master but I'm wrong`

git fetch -b release <bit-bucket repo url> =>  Not a git repository (or any of the parent directories): .git error

Can someone help in solving this. TIA


问:
No interactive elements in screenshot
I'm doing screenshot with this code:

```<code>from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = ('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36')
driver = webdriver.PhantomJS(desired_capabilities=dcap,service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any','--web-security=false'])
driver.set_window_size(1920, 1080)
driver.get("https://app.wisemapping.com/c/maps/579829/public")
driver.save_screenshot('screen.png')
driver.quit()
</code>```

And what i get is only this:
Screenshot

If you go to the website where i doing that, you can see there is mindmap.
I don't know what the problem, i tried chromedriver and everything is same, however, on other websites everything is fine.

答:
You need to add a webdriver wait so that the element appear on screen and than take screenshot

these are imports which you need

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
</code>```

add this line before taking screenshot

```<code>WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#workspace > g:nth-child(3) > rect:nth-child(2)")))
</code>```

Post that you will see correct screenshot

Title: No interactive elements in screenshot

Body:
I'm doing screenshot with this code:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = ('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36')
driver = webdriver.PhantomJS(desired_capabilities=dcap,service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any','--web-security=false'])
driver.set_window_size(1920, 1080)
driver.get("https://app.wisemapping.com/c/maps/579829/public")
driver.save_screenshot('screen.png')
driver.quit()

And what i get is only this:
Screenshot

If you go to the website where i doing that, you can see there is mindmap.
I don't know what the problem, i tried chromedriver and everything is same, however, on other websites everything is fine.

Body:
You need to add a webdriver wait so that the element appear on screen and than take screenshot

these are imports which you need

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

add this line before taking screenshot

WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#workspace > g:nth-child(3) > rect:nth-child(2)")))

Post that you will see correct screenshot


问:
Debug NodeJS + AngularJS 2
How can I debug the entire App NodeJS and ExpressJS?
I tried using 'ng build --prod' , then copying files in dist to my views folder .
I want that whenever I change codes , I refresh browser and its codes are also going to change. Thank you!</p>

答:
Use --inspect to debug ExpressJS

Enable inspector agent

Listen on default port (9229)

Disable minify or uglify for Angualar JS, so that you can debug on Chrome

For your reference
https://nodejs.org/en/docs/guides/debugging-getting-started/

For prod, by default it will get uglified

Title: Debug NodeJS + AngularJS 2


问:
Solve for value without using Solver
I currently have the following in excel for other users.

The Number column does not change. Users will input values in Multiplier 1 and Multiplier 2 columns and they will get a value in Outcome column.

Is there an automatically way where the user can also input a value in Outcome column and the Multiplier 1 column will change?

Currently Number and Outcome column are protected, will I need to unprotect the Outcome column?

答:
I recommend you use some VBA code using the Sub Worksheet_Change(ByVal Target as range) in the worksheet.

If the user enters a value in D2 it will put the formula "=D2/(A2*C2)" in B2
If the user enters a value in B2 it will put the formula "=A2*B2*C2" in D2

```<code>Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Target.Cells.Count > 1 Then Exit Sub
On Error GoTo LastLine
If Not Intersect(Target, Range("D2")) Is Nothing Then
    Range("B2").Formula = "=D2/(A2*C2)"
ElseIf Not Intersect(Target, Range("B2")) Is Nothing Then
    Range("D2").Formula = "=A2*B2*C2"
End If
LastLine:
Application.EnableEvents = True
End Sub
</code>```

Title: Solve for value without using Solver

Body:
I recommend you use some VBA code using the Sub Worksheet_Change(ByVal Target as range) in the worksheet.

If the user enters a value in D2 it will put the formula "=D2/(A2*C2)" in B2
If the user enters a value in B2 it will put the formula "=A2*B2*C2" in D2

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Target.Cells.Count > 1 Then Exit Sub
On Error GoTo LastLine
If Not Intersect(Target, Range("D2")) Is Nothing Then
    Range("B2").Formula = "=D2/(A2*C2)"
ElseIf Not Intersect(Target, Range("B2")) Is Nothing Then
    Range("D2").Formula = "=A2*B2*C2"
End If
LastLine:
Application.EnableEvents = True
End Sub


问:
Why does comparing strings using either '==' or 'is' sometimes produce a different result?
Two string variables are set to the same value. s1 == s2 always returns True, but s1 is s2 sometimes returns False.

If I open my Python interpreter and do the same is comparison, it succeeds:

```<code>>>> s1 = 'text'
>>> s2 = 'text'
>>> s1 is s2
True
</code>```

Why is this?

答:
The == operator tests value equivalence. The is operator tests object identity, and Python tests whether the two are really the same object (i.e., live at the same address in memory).

```<code>>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
</code>```

In this example, Python only created one string object, and both a and b refers to it. The reason is that Python internally caches and reuses some strings as an optimization. There really is just a string 'banana' in memory, shared by a and b. To trigger the normal behavior, you need to use longer strings:

```<code>>>> a = 'a longer banana'
>>> b = 'a longer banana'
>>> a == b, a is b
(True, False)
</code>```

When you create two lists, you get two objects:

```<code>>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
</code>```

In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.

If a refers to an object and you assign b = a, then both variables refer to the same object:

```<code>>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
</code>```

Reference: Think Python 2e by Allen B. Downey

Body:
Two string variables are set to the same value. s1 == s2 always returns True, but s1 is s2 sometimes returns False.

If I open my Python interpreter and do the same is comparison, it succeeds:

>>> s1 = 'text'
>>> s2 = 'text'
>>> s1 is s2
True

Why is this?

Body:
The == operator tests value equivalence. The is operator tests object identity, and Python tests whether the two are really the same object (i.e., live at the same address in memory).

>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True

In this example, Python only created one string object, and both a and b refers to it. The reason is that Python internally caches and reuses some strings as an optimization. There really is just a string 'banana' in memory, shared by a and b. To trigger the normal behavior, you need to use longer strings:

>>> a = 'a longer banana'
>>> b = 'a longer banana'
>>> a == b, a is b
(True, False)

When you create two lists, you get two objects:

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False

In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.

If a refers to an object and you assign b = a, then both variables refer to the same object:

>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True

Reference: Think Python 2e by Allen B. Downey


问:
Spring jpa onetomany returns only one element
I am trying to build a bidirectional one to many relationship with the spring data jpa but the list annotated with @onetomany always return one element.

Here is the code for my entities(setters and getters omitted):

```<code>@Entity
@Table(name = "sdk_sdk")
public class SDKEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

private String version;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "sdk")
@OrderBy("order ASC")
private List<SDKFileEntity> fileEntities;
}
</code>```

And the second entity:

```<code>@Entity
@Table(name = "sdk_file")
public class SDKFileEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String fileType;
private Integer sdkId;

public SDKFileEntity() {
}

@ManyToOne
@JoinColumn(name = "id", insertable = false, updatable = false)
private SDKEntity sdk;
</code>```

I am trying to have a manytoone mapping where the sdkId corresponds to the id from the SDKEntity class.
Whenever I try to get the sdkfiles from the sdkEntity using spring's repository, the size of the list is always 1.

So for example:

```<code>SDKEntity entity=repository.findOne(foo);
List<SDKFileEntity> files=entity.getFileEntities();
</code>```

here the size of files is 1, I have to delete the first element from the database to obtain the second element.

答:
This part of Code looks suspicious </p>

```<code>@ManyToOne
@JoinColumn(name = "id", insertable = false, updatable = false)
private SDKEntity sdk;
</code>```

<p>name = "id" it should be actual column name as written in database column name like this </p>

```<code>    @JoinColumn(name = "VISIT_ID", referencedColumnName = "ID")
    @ManyToOne
    private Visit visitId;
</code>```

Body:
I am trying to build a bidirectional one to many relationship with the spring data jpa but the list annotated with @onetomany always return one element.

Here is the code for my entities(setters and getters omitted):

@Entity
@Table(name = "sdk_sdk")
public class SDKEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

private String version;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "sdk")
@OrderBy("order ASC")
private List<SDKFileEntity> fileEntities;
}

And the second entity:

@Entity
@Table(name = "sdk_file")
public class SDKFileEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String fileType;
private Integer sdkId;

public SDKFileEntity() {
}

@ManyToOne
@JoinColumn(name = "id", insertable = false, updatable = false)
private SDKEntity sdk;

I am trying to have a manytoone mapping where the sdkId corresponds to the id from the SDKEntity class.
Whenever I try to get the sdkfiles from the sdkEntity using spring's repository, the size of the list is always 1.

So for example:

SDKEntity entity=repository.findOne(foo);
List<SDKFileEntity> files=entity.getFileEntities();

here the size of files is 1, I have to delete the first element from the database to obtain the second element.

Body:
This part of Code looks suspicious

@ManyToOne
@JoinColumn(name = "id", insertable = false, updatable = false)
private SDKEntity sdk;

name = "id" it should be actual column name as written in database column name like this

    @JoinColumn(name = "VISIT_ID", referencedColumnName = "ID")
    @ManyToOne
    private Visit visitId;


问:
How to Export Webcontrol table to excel in asp.net mvc
```<code>List<Table> t = (List<Table>)GenerateLayout(dtDPList, dtBOList, dpl);
</code>```

In the list i am getting the 3 Webcontrol table and i want to export those webconrol tables to excel.. so please help me..

答:
You can use the below generic method to convert datatable to excel :

```<code>using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelDemo
{
    public class ExcelUtility
    {
    public static void CreateExcel(DataSet ds, string excelPath)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        try
        {
            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                for (int j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
                {
                    xlWorkSheet.Cells[i + 1, j + 1] = ds.Tables[0].Rows[i].ItemArray[j].ToString();
                }
            }

            xlWorkBook.SaveAs(excelPath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlApp);
            releaseObject(xlWorkBook);
            releaseObject(xlWorkSheet);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private static void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch
        {
            obj = null;
        }
        finally
        {
            GC.Collect();
        }
    }
}
</code>```

}

You can directly apply the style properties to a cell as given below:

```<code>workSheet.Cells[2, 1].Font.Bold = true
</code>```

You can find more style tags using the link below:

http://csharp.net-informations.com/excel/csharp-format-excel.htm

Body:
List
 t = (List
)GenerateLayout(dtDPList, dtBOList, dpl);

In the list i am getting the 3 Webcontrol table and i want to export those webconrol tables to excel.. so please help me..

Body:
You can use the below generic method to convert datatable to excel :

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelDemo
{
    public class ExcelUtility
    {
    public static void CreateExcel(DataSet ds, string excelPath)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        try
        {
            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                for (int j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
                {
                    xlWorkSheet.Cells[i + 1, j + 1] = ds.Tables[0].Rows[i].ItemArray[j].ToString();
                }
            }

            xlWorkBook.SaveAs(excelPath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlApp);
            releaseObject(xlWorkBook);
            releaseObject(xlWorkSheet);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private static void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch
        {
            obj = null;
        }
        finally
        {
            GC.Collect();
        }
    }
}

}

You can directly apply the style properties to a cell as given below:

workSheet.Cells[2, 1].Font.Bold = true

You can find more style tags using the link below:

http://csharp.net-informations.com/excel/csharp-format-excel.htm


问:
why is my time/date picker formatting adding minutes?
I have both a time picker and a date picker in my template. The values store to my database together as one numeric string, so I have to do a few steps to parse them from one another in the right formats when I interpolate them to my template in the required places on a different page. First I call a formatting function to separate the values and then I run it through an angular-moment pipe to convert the military time to standard 12 hour time.

I noticed that consistently when I pick a time, say 7:00 or 12:00 on the time picker, it will interpolate to my template as 7:08 or 12:08. Why is it adding minutes?

THIS IS HOW I SAVE THE DATE AND TIME TO THE DATABASE

```<code>constructor(//controllers n stuff) {

//empty event object

      this.event = {
        hostName : "",
        hostId: "",
        hostPhoto : "",
        coverCharge: 0,
        drinkMin: false,
        reimburse: false,
        venue : "",
        guests : 0,
        date : "",
        time : "",
        city : "",
        eventTime : "",
        createdTime: "",
        volunteers : 0

      }
}//close constructor

addEvent(){

    let authData = OnymosAccess.getAuth(); //GET DATABASE AUTH
            this.event.hostName = authData.userName;
            this.event.hostId = authData.userId;
            this.event.hostPhoto = authData.userPhoto();
          **this.event.eventTime = new Date(this.event.date + " " + this.event.time).getTime();**
            this.event.createdTime = Date.now();

            let that = this;

                OnymosUtil.addData( //SEND TO DATABASE

        '/events/' + this.event.city + '/' + this.event.createdTime,
                        this.event,

        function optionalSuccessCallback (statusMessage) {
                            console.log(statusMessage);

                            that.saveStatus = "successfully saved";
                         },

            function optionalFailureCallback (error) {

                            that.saveStatus = "failed saving" + error;
                        });
}//end addEvent
</code>```

HTML TEMPLATE

```<code><ion-row>
                <ion-col>
                    <ion-icon name="calendar"></ion-icon>
                    <BR>
                    **{{getFormattedTime(event.eventTime, 'MM-dd-yyyy')}}**
                </ion-col>
                <ion-col>
                    <ion-icon name="clock"></ion-icon>
                    <BR>
                    **{{ getFormattedTime(event.eventTime,'HH:MM' ) | amParse:'HH:mm' | amDateFormat:'hh:mm A' }}**

                </ion-col>
</code>```

THE GET FORMATTED TIME FUNCTION I RUN THE TIME THROUGH BEFORE I USE MOMENT.

```<code>getFormattedTime (time, format) {
        var t = new Date(time);
        var tf = function (i) { return (i < 10 ? '0' : '') + i };
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
            switch (a) {
                case 'yyyy':
                    return tf(t.getFullYear());

                case 'MM':
                    return tf(t.getMonth() + 1);

                case 'mm':
                    return tf(t.getMinutes());

                case 'dd':
                    return tf(t.getDate());

                case 'HH':
                    return tf(t.getHours());

                case 'ss':
                    return tf(t.getSeconds());

            }
        })
    } // end of getFormattedTime
</code>```

答:
I used your code and try it here. You can check below code snippet. You are using new Date(this.event.date + " " + this.event.time).getTime() in code. It working fine. And you can do it new Date(this.event.date + " " + this.event.time) directly without .getTime() as well.

It seems that you did 'HH:MM', instead of 'HH:mm'. Correct it in code and try it.

function getFormattedTime (time, format) {
        var t = new Date(time);
        var tf = function (i) { return (i < 10 ? '0' : '') + i };
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
            switch (a) {
                case 'yyyy':
                    return tf(t.getFullYear());

                case 'MM':
                    return tf(t.getMonth() + 1);

                case 'mm':
                    return tf(t.getMinutes());

                case 'dd':
                    return tf(t.getDate());

                case 'HH':
                    return tf(t.getHours());

                case 'ss':
                    return tf(t.getSeconds());

            }
        })
    }

    var time=new Date("2017-07-05 07:00").getTime();
    console.log(time);
    console.log( getFormattedTime(time, 'MM-dd-yyyy'));
    console.log(getFormattedTime(time,'HH:mm' ));```

Body:
I have both a time picker and a date picker in my template. The values store to my database together as one numeric string, so I have to do a few steps to parse them from one another in the right formats when I interpolate them to my template in the required places on a different page. First I call a formatting function to separate the values and then I run it through an angular-moment pipe to convert the military time to standard 12 hour time.

I noticed that consistently when I pick a time, say 7:00 or 12:00 on the time picker, it will interpolate to my template as 7:08 or 12:08. Why is it adding minutes?

THIS IS HOW I SAVE THE DATE AND TIME TO THE DATABASE

constructor(//controllers n stuff) {

//empty event object

      this.event = {
        hostName : "",
        hostId: "",
        hostPhoto : "",
        coverCharge: 0,
        drinkMin: false,
        reimburse: false,
        venue : "",
        guests : 0,
        date : "",
        time : "",
        city : "",
        eventTime : "",
        createdTime: "",
        volunteers : 0

      }
}//close constructor

addEvent(){

    let authData = OnymosAccess.getAuth(); //GET DATABASE AUTH
            this.event.hostName = authData.userName;
            this.event.hostId = authData.userId;
            this.event.hostPhoto = authData.userPhoto();
          **this.event.eventTime = new Date(this.event.date + " " + this.event.time).getTime();**
            this.event.createdTime = Date.now();

            let that = this;

                OnymosUtil.addData( //SEND TO DATABASE

        '/events/' + this.event.city + '/' + this.event.createdTime,
                        this.event,

        function optionalSuccessCallback (statusMessage) {
                            console.log(statusMessage);

                            that.saveStatus = "successfully saved";
                         },

            function optionalFailureCallback (error) {

                            that.saveStatus = "failed saving" + error;
                        });
}//end addEvent

HTML TEMPLATE

<ion-row>
                <ion-col>
                    <ion-icon name="calendar"></ion-icon>

                    **{{getFormattedTime(event.eventTime, 'MM-dd-yyyy')}}**
                </ion-col>
                <ion-col>
                    <ion-icon name="clock"></ion-icon>

                    **{{ getFormattedTime(event.eventTime,'HH:MM' ) | amParse:'HH:mm' | amDateFormat:'hh:mm A' }}**

                </ion-col>

THE GET FORMATTED TIME FUNCTION I RUN THE TIME THROUGH BEFORE I USE MOMENT.

getFormattedTime (time, format) {
        var t = new Date(time);
        var tf = function (i) { return (i < 10 ? '0' : '') + i };
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
            switch (a) {
                case 'yyyy':
                    return tf(t.getFullYear());

                case 'MM':
                    return tf(t.getMonth() + 1);

                case 'mm':
                    return tf(t.getMinutes());

                case 'dd':
                    return tf(t.getDate());

                case 'HH':
                    return tf(t.getHours());

                case 'ss':
                    return tf(t.getSeconds());

            }
        })
    } // end of getFormattedTime


问:
GET Requests vs JavaScript
Alright, I have a JavaScript doing HTTP Requests to a PHP file onto the same directory. Then it's returning it's output.

Let's say there are over 50+ people doing this request simultaneously ... will it slow down anything? Yes, this may seem like a dumb question - but sorry. :|

Thank you.

答:
Factors as to why this can't be answered

Hardware Limitations - what kind of server? how much memory? how much free resources (eg any other demanding applications running at the time)

Network Limitations - what kind of connection? how saturated is the network?

Application Limitations - what is riddle.php doing? how is the db query constructed? what does the JavaScript do with the returned result?

Database Limitations - how many concurrent connections are allowed? how many can be supported? how is the db optimized?

Ways to approach

Cache the php as much as you can

Cache previous queries as much as you can

Create a database connection pool (a large percentage of the time is spent in opening new connections)

Title: GET Requests vs JavaScript


问:
how to select not null values column dynamically?
I created a table like below. I want to select only NOT NULL column dynamically like(NO, NAME,SAL_1). No need to select SAL,SAL_2.

Note: Initially I don't know the columns values.

```<code>create table sample(no integer,name varchar(20),sal integer,sal_1 integer,sal_2 integer);
insert into sample(name,sal_1) values('aaa',10);
insert into sample(no,name,sal_1) values(20,'',20);
insert into sample(sal_1) values(30);

select * from sample;
</code>```

data like below

```<code>NO        NAME    SAL   SAL_1 SAL_2
20       (null)   (null)  20  (null)
(null)    (null)  (null)  30  (null)
(null)    aaa     (null)  10  (null)
</code>```

Expected op:

```<code>NO       NAME   SAL_1
20      (null)  20
(null)  (null)  30
(null)  aaa     10
</code>```

答:
Try This,

select * from sample where nvl(NO,0)> 0 and nvl(length(NAME),0)>0 and nvl(SAL_1,0)>0

Body:
I created a table like below. I want to select only NOT NULL column dynamically like(NO, NAME,SAL_1). No need to select SAL,SAL_2.

Note: Initially I don't know the columns values.

create table sample(no integer,name varchar(20),sal integer,sal_1 integer,sal_2 integer);
insert into sample(name,sal_1) values('aaa',10);
insert into sample(no,name,sal_1) values(20,'',20);
insert into sample(sal_1) values(30);

select * from sample;

data like below

NO        NAME    SAL   SAL_1 SAL_2
20       (null)   (null)  20  (null)
(null)    (null)  (null)  30  (null)
(null)    aaa     (null)  10  (null)

Expected op:

NO       NAME   SAL_1
20      (null)  20
(null)  (null)  30
(null)  aaa     10


答:
Its a timing issue. The screen shot is taken before the elements are loaded and become visible. Use explicit wait to wait for them</p>

```<code>from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

driver.get("https://app.wisemapping.com/c/maps/579829/public")

WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "#workspaceContainer > svg > [preserveAspectRatio]")))

driver.save_screenshot('screen.png')
</code>```

Title: No interactive elements in screenshot

Body:
Its a timing issue. The screen shot is taken before the elements are loaded and become visible. Use explicit wait to wait for them

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

driver.get("https://app.wisemapping.com/c/maps/579829/public")

WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "#workspaceContainer > svg > [preserveAspectRatio]")))

driver.save_screenshot('screen.png')


问:
How to place gradient effect above the image in android?
Here i have attached the screenshot of my requirement.Background color can be changed. Can anyone give some idea to achieve this.

Thanks in advance.

答:
try this in your imageview

```<code>android:background="@drawable/custom_background"
android:src="@drawable/profile"
</code>```

create a drawable file like this in res/drawable

```<code> <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<gradient
    android:angle="90"
    android:endColor="@color/colorPrimary"
    android:startColor="@color/colorPrimaryDark"
    android:centerColor="@color/colorAccent" />

<corners android:radius="0dp" />
</shape>
</code>```

Body:
try this in your imageview

android:background="@drawable/custom_background"
android:src="@drawable/profile"

create a drawable file like this in res/drawable

 <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<gradient
    android:angle="90"
    android:endColor="@color/colorPrimary"
    android:startColor="@color/colorPrimaryDark"
    android:centerColor="@color/colorAccent" />

<corners android:radius="0dp" />
</shape>


问:
How to flip the images on x and y axis with swipe gesture in swift?
Can anybody please help me, how to flip images using swipe gesture in both x and y axis with animation in swift.I found some answers but they were not upto my requirements. Thank you in advance.</p>

答:
```<code>    //MARK: - Image flipping operations performed here.

        func flipImageOnHorizontalAxis(theImage: UIImage,imageView:UIImageView) -> UIImage {

            var orient: UIImageOrientation!
            let imgOrientation = theImage.imageOrientation

            UIView.transition(with: imageView, duration: 0.4, options: .transitionCrossDissolve, animations: {() -> Void in

                switch imgOrientation {

                case .left:
                    orient = .rightMirrored

                case .right:
                    orient = .leftMirrored

                case .up:
                    orient = .upMirrored

                case .down:
                    orient = .downMirrored

                case .upMirrored
                    :
                    orient = .up

                case .downMirrored:
                    orient = .down

                case .leftMirrored:
                    orient = .right

                case .rightMirrored:
                    orient = .left
                }

            }, completion: { _ in })

            let mirroredImage = UIImage(cgImage: theImage.cgImage!, scale: 1.0, orientation: orient)
            return mirroredImage
        }

        func flipImageOnVerticalAxis(theImage: UIImage,imageView:UIImageView) -> UIImage {

            var orient: UIImageOrientation!
            let imgOrientation = theImage.imageOrientation

            UIView.transition(with: imageView, duration: 0.4, options: .transitionCrossDissolve, animations: {() -> Void in

                switch imgOrientation {

                case .left:
                    orient = .leftMirrored

                case .right:
                    orient = .rightMirrored

                case .up:
                    orient = .downMirrored

                case .down:
                    orient = .upMirrored

                case .upMirrored:
                    orient = .down

                case .downMirrored:
                    orient = .up

                case .leftMirrored:
                    orient = .left

                case .rightMirrored:
                    orient = .right
                }

            }, completion: { _ in })
            let mirroredImage = UIImage(cgImage: theImage.cgImage!, scale: 1.0, orientation: orient)
            //let mirroredImage = UIImage(CGImage: theImage.CGImage!, scale: 1.0, orientation: orient)
            return mirroredImage
        }

//MARK: To call the above function this can be done like this:

flipImageOnHorizontalAxis(theImage: imageView.image!, imageView: imageView)

or

flipImageOnVerticalAxis(theImage: imageView.image!, imageView: imageView)
</code>```


问:
Drupal 7 DrupalExp Layer Slider dont let me add a slide
I have a drupal site with DrupalExp Layer Slider but when i want to add a new slide does not work.

and only show me this error on console, any idea?

答:
Add this script to your theme page tpl or via drupal add js or via any preprocess page hook in template.php</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</code>```

Body:
Add this script to your theme page tpl or via drupal add js or via any preprocess page hook in template.php

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>


问:
Dynamic view binding using DataTemplate
<DataTemplate DataType="{Binding GetViewModel}"  Resources="{Binding GetView}">

        </DataTemplate>

I am trying to bind view dynamically in code of MainViewModel linked to above MainView's code.
How can I bind datatype and vw:SomeView dynamically?

答:
The DataTemplate.DataType property is not a dependency property so you cannot bind to its values:

http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.datatype.aspx

Typically you will have multiple DataTemplate instances define in your XAML which describe how your UI renders each view model. The framework then takes care of using these DataTemplates when a control tries to render a view model of that type.

Title: Dynamic view binding using DataTemplate


问:
Print XML in PHP 7
Hi I want print a string xml (title) in php

I have tried that:

```<code><?php
$xml = "<tracks>
<radioname>Radio</radioname>
<track>
<uniqueid>400000</uniqueid>
<title>Mask Off</title>
<artists>Future</artists>
</track>
</tracks>";

$xml = simplexml_load_string($xml);
echo $xml->tracks->track->title;

?>
</code>```

答:
You should try this:

```<code>$xml = '<?xml version="1.0" encoding="UTF-8"?><tracks>
<radioname>Radio</radioname>
<track>
<uniqueid>400000</uniqueid>
<title>Mask Off</title>
<artists>Future</artists>
</track>
</tracks>';

$xmlcont = new SimpleXMLElement($xml);

echo $xmlcont->track->title;
</code>```

Output will be:

```<code>Mask Off
</code>```

Title: Print XML in PHP 7

Body:
Hi I want print a string xml (title) in php

I have tried that:

<?php
$xml = "<tracks>
<radioname>Radio</radioname>
<track>
<uniqueid>400000</uniqueid>
<title>Mask Off</title>
<artists>Future</artists>
</track>
</tracks>";

$xml = simplexml_load_string($xml);
echo $xml->tracks->track->title;

?>

Body:
You should try this:

$xml = '<?xml version="1.0" encoding="UTF-8"?><tracks>
<radioname>Radio</radioname>
<track>
<uniqueid>400000</uniqueid>
<title>Mask Off</title>
<artists>Future</artists>
</track>
</tracks>';

$xmlcont = new SimpleXMLElement($xml);

echo $xmlcont->track->title;

Output will be:

Mask Off


答:
There is problem no x and y column in df_aviris.

So need for outer join:

```<code>DFinal = pd.merge(df_aviris,df_geomap,how='outer',left_on=[3,4], right_on=['x','y'])
</code>```

```<code>#default outer join, join='outer' can be omit
DFinal = pd.concat([df_aviris.set_index([3,4]),
                    df_geomap.set_index(['x','y'])],axis=1)
           .reset_index()
</code>```

and for inner join:

```<code>#default inner join, how='inner' can be omit
DFinal = pd.merge(df_aviris,df_geomap,left_on=[3,4], right_on=['x','y'])
</code>```

```<code>DFinal = pd.concat([df_aviris.set_index([3,4]),
                    df_geomap.set_index(['x','y'])],join='inner',axis=1)
           .reset_index()
</code>```

EDIT:

I cannot simulate:

TypeError: an integer is required

maybe helps upgrade pandas.

Or if there are only one number after floating point is possible use a little hack - multiple by 10 and convert to int and after merge divide by 10:

```<code>df_aviris1 = df_aviris.mul(10).astype(int)
df_geomap1 = df_geomap.mul(10).astype(int)

#choose method what need
DFinal = pd.merge(df_aviris1,df_geomap1,how='outer',left_on=[3,4], right_on=['x','y'])

DFinal = DFinal.div(10)
</code>```

Title: TypeError: an integer is required in pd.merge python

Body:
I'm trying to combine two panda dataframes as shown below

df_aviris

            0    1    2         3          4
0         0.0  0.0  0.0  482636.5  4155009.5
1         0.0  0.0  0.0  482637.5  4155009.5
2         0.0  0.0  0.0  482638.5  4155009.5
3         0.0  0.0  0.0  482639.5  4155009.5
4         0.0  0.0  0.0  482640.5  4155009.5
5         0.0  0.0  0.0  482641.5  4155009.5
6         0.0  0.0  0.0  482642.5  4155009.5
7         0.0  0.0  0.0  482643.5  4155009.5
8         0.0  0.0  0.0  482644.5  4155009.5
       ...  ...  ...       ...        ...

16730996  0.0  0.0  0.0  485932.5  4149940.5
16730997  0.0  0.0  0.0  485933.5  4149940.5
16730998  0.0  0.0  0.0  485934.5  4149940.5
16730999  0.0  0.0  0.0  485935.5  4149940.5
[16731000 rows x 5 columns]

df_geomap

              0      1      2         x          y
0         255.0  255.0  255.0  477642.5  4158373.5
1         255.0  255.0  255.0  477643.5  4158373.5
2         255.0  255.0  255.0  477644.5  4158373.5
3         255.0  255.0  255.0  477645.5  4158373.5
4         255.0  255.0  255.0  477646.5  4158373.5
5         255.0  255.0  255.0  477647.5  4158373.5
6         255.0  255.0  255.0  477648.5  4158373.5
         ...    ...    ...       ...        ...

79026747  255.0  255.0  255.0  487218.5  4150124.5
79026748  255.0  255.0  255.0  487219.5  4150124.5
79026749  255.0  255.0  255.0  487220.5  4150124.5
[79026750 rows x 5 columns]

I tried to merge these two based on x and y.

DFinal = pd.merge(df_aviris,df_geomap,how='outer',on=['x','y'],left_index=False,right_index=False,copy=False)

and using concat also

DFinal = pd.concat([df_aviris.set_index(['x','y']),df_geomap.set_index(['x','y'])],join='inner',axis=1)

But getting the error as below

Traceback (most recent call last):
  File "pandas/index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas/index.c:4279)
  File "pandas/src/hashtable_class_helper.pxi", line 404, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:8543)
TypeError: an integer is required
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/indexes/base.py", line 2134, in get_loc
    return self._engine.get_loc(key)
  File "pandas/index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas/index.c:4433)
  File "pandas/index.pyx", line 156, in pandas.index.IndexEngine.get_loc (pandas/index.c:4363)
KeyError: 'x'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "pandas/index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas/index.c:4279)
  File "pandas/src/hashtable_class_helper.pxi", line 404, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:8543)
TypeError: an integer is required
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-38-0a4bfba1b1f4>", line 1, in <module>
    DFinal = pd.concat([df_aviris.set_index(['x','y']),df_geomap.set_index(['x','y'])],join='inner',axis=1)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2917, in set_index
    level = frame[col]._values
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2059, in __getitem__
    return self._getitem_column(key)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2066, in _getitem_column
    return self._get_item_cache(key)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/generic.py", line 1386, in _get_item_cache
    values = self._data.get(item)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/internals.py", line 3543, in get
    loc = self.items.get_loc(item)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/indexes/base.py", line 2136, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas/index.c:4433)
  File "pandas/index.pyx", line 156, in pandas.index.IndexEngine.get_loc (pandas/index.c:4363)
KeyError: 'x'

I'm using python 3.6.1

Body:
There is problem no x and y column in df_aviris.

So need for outer join:

DFinal = pd.merge(df_aviris,df_geomap,how='outer',left_on=[3,4], right_on=['x','y'])

#default outer join, join='outer' can be omit
DFinal = pd.concat([df_aviris.set_index([3,4]),
                    df_geomap.set_index(['x','y'])],axis=1)
           .reset_index()

and for inner join:

#default inner join, how='inner' can be omit
DFinal = pd.merge(df_aviris,df_geomap,left_on=[3,4], right_on=['x','y'])

DFinal = pd.concat([df_aviris.set_index([3,4]),
                    df_geomap.set_index(['x','y'])],join='inner',axis=1)
           .reset_index()

EDIT:

I cannot simulate:

TypeError: an integer is required

maybe helps upgrade pandas.

Or if there are only one number after floating point is possible use a little hack - multiple by 10 and convert to int and after merge divide by 10:

df_aviris1 = df_aviris.mul(10).astype(int)
df_geomap1 = df_geomap.mul(10).astype(int)

#choose method what need
DFinal = pd.merge(df_aviris1,df_geomap1,how='outer',left_on=[3,4], right_on=['x','y'])

DFinal = DFinal.div(10)