问:
Conditionally adding a define to a configuration .h file with CMake
I know that you can generate config.h files with CMake processing a template, where whenever you write

```<code>#define FOO ${SOME_VARIABLE}
</code>```

and in CMake you set SOME_VARIABLE to, say, 123, then you'll get

```<code>#define FOO 123
</code>```

And that's great. But no I want BAR to be defined only conditionally, i.e. sometimes config.h will have

```<code>#define BAR
</code>```

and sometimes it won't, not even to a null/default value. How can I do this with CMake?

答:
The way to achieve this is with:

```<code>#cmakedefine BOO
</code>```

in the configure.h file template. This will be replaced with either

```<code>#define BAR whatever_it_is_defined_to_goes_here
</code>```

or

```<code>/* #undef BAR */
</code>```

depending on whether VAR is set in CMake to any value not considered a false constant by the if() command.

Cf. the CMake documentation page on the configure_file() command.

Body:
I know that you can generate config.h files with CMake processing a template, where whenever you write

#define FOO ${SOME_VARIABLE}

and in CMake you set SOME_VARIABLE to, say, 123, then you'll get

#define FOO 123

And that's great. But no I want BAR to be defined only conditionally, i.e. sometimes config.h will have

#define BAR

and sometimes it won't, not even to a null/default value. How can I do this with CMake?

Body:
The way to achieve this is with:

#cmakedefine BOO

in the configure.h file template. This will be replaced with either

#define BAR whatever_it_is_defined_to_goes_here

or

/* #undef BAR */

depending on whether VAR is set in CMake to any value not considered a false constant by the if() command.

Cf. the CMake documentation page on the configure_file() command.


来源: stackexchange

问:
Fill SQL database from a CSV File
I need to create a database using a CSV file with SSIS. The CSV file includes four columns:

I need to use the information of that table to populate the three tables I created in SQL below.

I have realized that what I need is to use one column of the Employee Table, EmployeeNumber, and Group Table, GroupID, to populate the EmployeeGroup table. For that, I thought that a Join Merge table is what I needed, but I created the Data Flow Task in SSIS, and the results are the same, no data displayed.

The middle table is the one used to relate the other tables.

I created the package in SSIS and the Employee and Group Tables are populated, but the  EmployeeGroup table is not. EmployeeGroup will only show the EmployeeNumber and Group ID columns with no data.

I am new using SSIS, and I really do not know what else to do. I will really appreciate your help.

答:
Overview

Solutions using SSIS

Using 3 Data Flow Tasks

Using 2 Data Flow Tasks

Solutions Using T-SQL

Using Microsoft.Ace.OLEDB

Using Microsoft Text Driver

Solutions Using PowerShell

1st Solution - SSIS

Using 3 Data Flow Tasks

This can be done using only 2 Data Flow Task, but according to what the OP mentioned in the question I am new using SSIS, and I really do not know what else to do, i will provide easiest solution which is 3 DataFlow Task to avoid using more components like MultiCast.

Solution Overview

Because you want to build a relational database and extract relations from the csv, you have to read the csv 3 times -consider it as 3 seperated files -.

First you have to import Employees and Groups Data, Then you have to import the relation table between them.

Each Import step can be done in a seperate Data Flow Task

Detailed Solution

Add a Flat File connection Manager (Csv File)

Add An OLEDB connection Manager (SQL Destination)

Add 3 DataFlow Task like the image below

First Data Flow Task

Add a Flat File Source , a Script Component , OLEDB destination like shown in the image below

In the Script Component choose Group Name column as Input

Select the Output Buffer and change SynchronousInputID Property to None And add an output column OutGroupname with type DT_STR

In the Script section write the following Code:

```<code> Imports System.Collections.Generic

 Private m_List As New List(Of String)
 Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

If Not Row.GroupName_IsNull AndAlso
        Not String.IsNullOrEmpty(Row.GroupName.Trim) Then

    If Not m_List.Contains(Row.GroupName.Trim) Then

        m_List.Add(Row.GroupName.Trim)

        CreateOutputRows(Row.GroupName.Trim)

    End If

End If
End Sub

Public Sub CreateOutputRows(ByVal strValue As String)

Output0Buffer.AddRow()
Output0Buffer.OutGroupName = strValue
End Sub
</code>```

On the OLEDB Destination map OutGroupName to GroupName Column

Second Data Flow Task : Import Employees Data

Repeat the same steps done with Groupname Column : with a single difference that is you have to choose the EmployeeID, Employee Name, LoginName columns as Input in the Script Component and Use the ID Column instead of Groupname column in the comparaison

Third Data Flow Task : Import Employees_Group Data

You have to add a Flat File Source , Look Up transformation , OLEDB Destination

In The LookUp Transformation Component select Groups Table as a Lookup table

Map GroupName Columns and Get Group ID as output

Choose Ignore Failure in the Error Output Configuration

In Oledb Destination map columns as following

Note: GroupID must be an Identity (set it in sql server)

Using 2 Data Flow Tasks

You have to do the same steps as the 3 Data Flow Tasks solution, but instead of adding 2 Data Flow Tasks to Group and Employee, just add one Data Flow Task, and after the Flat File Source add a MultiCast component to duplicate the Flow. Then for the first flow use the same Script Component and OLEDB Destination used in the Employee Data Flow Task, and for the second flow use the Script Component and OLEDB Destination related to Group.

2nd Solution - Using TSQL

There are many method to import Flat file to SQL via T-SQL commands

OPENROWSET with Microsoft ACE OLEDB provider

Assuming that the installed version of Microsoft ACE OLEDB is Microsoft.ACE.OLEDB.12.0 and that the csv file location is C:\abc.csv

First Import data into Employee and Group Table

```<code>INSERT INTO [GROUP]
    ([Group Name])
SELECT
    [Group Name]
FROM
    OPENROWSET
        (
            'Microsoft.ACE.OLEDB.12.0','Text;Database=C:\;IMEX=1;','SELECT * FROM abc.csv'
        ) t

INSERT INTO [Employee]
    ([Employee Number],[Employee Name],[LoginName])
SELECT
    [Employee Number],[Employee Name],[LoginName]
FROM
    OPENROWSET
        (
            'Microsoft.ACE.OLEDB.12.0','Text;Database=C:\;IMEX=1;','SELECT * FROM abc.csv'
        ) t
</code>```

Import the Employee_Group Data

```<code>INSERT INTO [EmployeeGroup]
    ([Employee Number],[GroupID])
SELECT
    t1.[Employee Number],t2.[GroupID]
FROM
    OPENROWSET
        (
            'Microsoft.ACE.OLEDB.12.0','Text;Database=C:\;IMEX=1;','SELECT * FROM abc.csv'
        ) t1 INNER JOIN GROUP t2 ON t1.[Group Name] = T2.[Group Name]
</code>```

OPENROWSET with Microsoft Text Driver

First Import data into Employee and Group Table

```<code>INSERT INTO [GROUP]
    ([Group Name])
SELECT
    [Group Name]
FROM
    OPENROWSET
        (
            'MSDASQL',
            'Driver={Microsoft Text Driver (*.txt; *.csv)};
            DefaultDir=C:\;',
            'SELECT * FROM abc.csv'
        ) t

INSERT INTO [Employee]
    ([Employee Number],[Employee Name],[LoginName])
SELECT
    [Employee Number],[Employee Name],[LoginName]
FROM
    OPENROWSET
        (
            'MSDASQL',
            'Driver={Microsoft Text Driver (*.txt; *.csv)};
            DefaultDir=C:\;',
            'SELECT * FROM abc.csv'
        ) t
</code>```

Import the Employee_Group Data

```<code>INSERT INTO [EmployeeGroup]
    ([Employee Number],[GroupID])
SELECT
    t1.[Employee Number],t2.[GroupID]
FROM
    OPENROWSET
        (
            'MSDASQL',
            'Driver={Microsoft Text Driver (*.txt; *.csv)};
            DefaultDir=C:\;',
            'SELECT * FROM abc.csv'
        ) t1 INNER JOIN GROUP t2 ON t1.[Group Name] = T2.[Group Name]
</code>```

Note: You can Import Data to a staging table, then query this table, to avoid connecting many times to the csv File

Solutions Using PowerShell

There are many method to import csv files to SQL server, you can check the following links for additional informations.

Four Easy Ways to Import CSV Files to SQL Server with PowerShell

How to import data from .csv in SQL Server using PowerShell?

References

OPENROWSET (Transact-SQL)

T-SQL – Read CSV files using OpenRowSet

Import error using Openrowset

ContentLicense: CC BY-SA 3.0

Title: Fill SQL database from a CSV File

Body:
Overview

Solutions using SSIS

Using 3 Data Flow Tasks

Using 2 Data Flow Tasks

Solutions Using T-SQL

Using Microsoft.Ace.OLEDB

Using Microsoft Text Driver

Solutions Using PowerShell

1st Solution - SSIS

Using 3 Data Flow Tasks

This can be done using only 2 Data Flow Task, but according to what the OP mentioned in the question I am new using SSIS, and I really do not know what else to do, i will provide easiest solution which is 3 DataFlow Task to avoid using more components like MultiCast.

Solution Overview

Because you want to build a relational database and extract relations from the csv, you have to read the csv 3 times -consider it as 3 seperated files -.

First you have to import Employees and Groups Data, Then you have to import the relation table between them.

Each Import step can be done in a seperate Data Flow Task

Detailed Solution

Add a Flat File connection Manager (Csv File)

Add An OLEDB connection Manager (SQL Destination)

Add 3 DataFlow Task like the image below

First Data Flow Task

Add a Flat File Source , a Script Component , OLEDB destination like shown in the image below

In the Script Component choose Group Name column as Input

Select the Output Buffer and change SynchronousInputID Property to None And add an output column OutGroupname with type DT_STR

In the Script section write the following Code:

 Imports System.Collections.Generic

 Private m_List As New List(Of String)
 Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

If Not Row.GroupName_IsNull AndAlso
        Not String.IsNullOrEmpty(Row.GroupName.Trim) Then

    If Not m_List.Contains(Row.GroupName.Trim) Then

        m_List.Add(Row.GroupName.Trim)

        CreateOutputRows(Row.GroupName.Trim)

    End If

End If
End Sub

Public Sub CreateOutputRows(ByVal strValue As String)

Output0Buffer.AddRow()
Output0Buffer.OutGroupName = strValue
End Sub

On the OLEDB Destination map OutGroupName to GroupName Column

Second Data Flow Task : Import Employees Data

Repeat the same steps done with Groupname Column : with a single difference that is you have to choose the EmployeeID, Employee Name, LoginName columns as Input in the Script Component and Use the ID Column instead of Groupname column in the comparaison

Third Data Flow Task : Import Employees_Group Data

You have to add a Flat File Source , Look Up transformation , OLEDB Destination

In The LookUp Transformation Component select Groups Table as a Lookup table

Map GroupName Columns and Get Group ID as output

Choose Ignore Failure in the Error Output Configuration

In Oledb Destination map columns as following

Note: GroupID must be an Identity (set it in sql server)

Using 2 Data Flow Tasks

You have to do the same steps as the 3 Data Flow Tasks solution, but instead of adding 2 Data Flow Tasks to Group and Employee, just add one Data Flow Task, and after the Flat File Source add a MultiCast component to duplicate the Flow. Then for the first flow use the same Script Component and OLEDB Destination used in the Employee Data Flow Task, and for the second flow use the Script Component and OLEDB Destination related to Group.

2nd Solution - Using TSQL

There are many method to import Flat file to SQL via T-SQL commands

OPENROWSET with Microsoft ACE OLEDB provider

Assuming that the installed version of Microsoft ACE OLEDB is Microsoft.ACE.OLEDB.12.0 and that the csv file location is C:\abc.csv

First Import data into Employee and Group Table

INSERT INTO [GROUP]
    ([Group Name])
SELECT
    [Group Name]
FROM
    OPENROWSET
        (
            'Microsoft.ACE.OLEDB.12.0','Text;Database=C:\;IMEX=1;','SELECT * FROM abc.csv'
        ) t

INSERT INTO [Employee]
    ([Employee Number],[Employee Name],[LoginName])
SELECT
    [Employee Number],[Employee Name],[LoginName]
FROM
    OPENROWSET
        (
            'Microsoft.ACE.OLEDB.12.0','Text;Database=C:\;IMEX=1;','SELECT * FROM abc.csv'
        ) t

Import the Employee_Group Data

INSERT INTO [EmployeeGroup]
    ([Employee Number],[GroupID])
SELECT
    t1.[Employee Number],t2.[GroupID]
FROM
    OPENROWSET
        (
            'Microsoft.ACE.OLEDB.12.0','Text;Database=C:\;IMEX=1;','SELECT * FROM abc.csv'
        ) t1 INNER JOIN GROUP t2 ON t1.[Group Name] = T2.[Group Name]

OPENROWSET with Microsoft Text Driver

First Import data into Employee and Group Table

INSERT INTO [GROUP]
    ([Group Name])
SELECT
    [Group Name]
FROM
    OPENROWSET
        (
            'MSDASQL',
            'Driver={Microsoft Text Driver (*.txt; *.csv)};
            DefaultDir=C:\;',
            'SELECT * FROM abc.csv'
        ) t

INSERT INTO [Employee]
    ([Employee Number],[Employee Name],[LoginName])
SELECT
    [Employee Number],[Employee Name],[LoginName]
FROM
    OPENROWSET
        (
            'MSDASQL',
            'Driver={Microsoft Text Driver (*.txt; *.csv)};
            DefaultDir=C:\;',
            'SELECT * FROM abc.csv'
        ) t

Import the Employee_Group Data

INSERT INTO [EmployeeGroup]
    ([Employee Number],[GroupID])
SELECT
    t1.[Employee Number],t2.[GroupID]
FROM
    OPENROWSET
        (
            'MSDASQL',
            'Driver={Microsoft Text Driver (*.txt; *.csv)};
            DefaultDir=C:\;',
            'SELECT * FROM abc.csv'
        ) t1 INNER JOIN GROUP t2 ON t1.[Group Name] = T2.[Group Name]

Note: You can Import Data to a staging table, then query this table, to avoid connecting many times to the csv File

Solutions Using PowerShell

There are many method to import csv files to SQL server, you can check the following links for additional informations.

Four Easy Ways to Import CSV Files to SQL Server with PowerShell

How to import data from .csv in SQL Server using PowerShell?

References

OPENROWSET (Transact-SQL)

T-SQL – Read CSV files using OpenRowSet

Import error using Openrowset


问:
How to change the underline color of md-input-container in angular4?
I have been reading the docs for this (https://material.angular.io/components/input/overview) There is a section that says how to change the color of the line at the bottom of the md-input-container. But it is not clear to me what an attribute is nor is there a code example to refer to. It says the underline color can be changed using the color attribute of the md-input-container. In addition what I mean by underline is the animated underline that expands out as visible in the provided link. Could somebody explain more clearly what the attribute of md-input-container is, or provide some code. I have tried adding a directive called color, changing the color of md-input-container in css, amongst other things and I am not succeeding at this. If somebody could explain/show some code that demonstrates this, that would be very helpful. Thanks!

Here is some code, which I feel should work, based on the wording of that text. But it does not.

```<code>  <md-input-container
    color="yellow"
    class="input-half-width">
    <input
      [(ngModel)]="driftInfo.title"
      name="title"
      mdInput
      placeholder="Ange rubrik"
    >
  </md-input-container>
</code>```

答:
You can use this

```<code>::ng-deep .mat-input-underline{
    border-bottom: 1px solid red;
}
</code>```

or what I do is give the angular material element a class and add it to styles.css or scss whichever extension you're using.  So it would look like this in styles (which is a global style sheet)

```<code>.mat-input-underline .<custom class name> {
    put your info you want to change here.
}
</code>```

Body:
I have been reading the docs for this (https://material.angular.io/components/input/overview) There is a section that says how to change the color of the line at the bottom of the md-input-container. But it is not clear to me what an attribute is nor is there a code example to refer to. It says the underline color can be changed using the color attribute of the md-input-container. In addition what I mean by underline is the animated underline that expands out as visible in the provided link. Could somebody explain more clearly what the attribute of md-input-container is, or provide some code. I have tried adding a directive called color, changing the color of md-input-container in css, amongst other things and I am not succeeding at this. If somebody could explain/show some code that demonstrates this, that would be very helpful. Thanks!

Here is some code, which I feel should work, based on the wording of that text. But it does not.

  <md-input-container
    color="yellow"
    class="input-half-width">
    <input
      [(ngModel)]="driftInfo.title"
      name="title"
      mdInput
      placeholder="Ange rubrik"
    >
  </md-input-container>

Body:
You can use this

::ng-deep .mat-input-underline{
    border-bottom: 1px solid red;
}

or what I do is give the angular material element a class and add it to styles.css or scss whichever extension you're using.  So it would look like this in styles (which is a global style sheet)

.mat-input-underline .<custom class name> {
    put your info you want to change here.
}


问:
String Filtering .. Any one..Contains only either of the selected characters or both
I have a array from 0 to 10000.
problem
And i need to filter only the numbers containing either 3 or 4 or both and none other than that...
eg., 3,4,33,44,333,444,343,434,334

I tried the do while technique but I have made some mistake in the code..\
I'm not getting the output still..:(
the improved code is

```<code>import java.util.*;
</code>```

import static java.lang.System.*;
public class numb {

```<code>public static void main(String[] args) {
    int num,c,cum;
    int i;
     Scanner in = new Scanner(System.in);
     out.println(3/10);

    out.println("How many elements u need to put in this array?");
    num=in.nextInt();
    int[] ray1 = new int[num];
    List<String> l1 = new LinkedList<String>();
    for (c=0;c<num;c++)
    {

        ray1[c]=c;
    }

            for(i=1;i<num;i++)
            {
         boolean baabu=true;
                do {
                    cum=ray1[i];
                    int lastdig = cum%10;
                    if(lastdig!=3||lastdig!=4)
                    {
                        baabu=false;
                    }
                    cum=cum/10;
                }
                while(cum>0&&baabu);
                if(baabu)
                {
                    String ad = String.valueOf(ray1[i]);
                    l1.add(ad);
                }

            }
            printme(l1);

}

public static void print (int[] array)
{
    for(int xc:array)
        out.println(xc);
}
public static void printme (List<String> l1)
{
    for(String yc:l1)
        out.println(yc);
}
</code>```

}

答:
Check if the last digit is a 3 or a 4: if it is, divide the number by 10 and check the next digit; otherwise, discard the number.</p>

```<code>boolean add = true;
do {
  int lastDigit = num % 10;
  if (lastDigit != 3 && lastDigit != 4) {
    add = false;
  }
  num /= 10;
} while (add && num > 0);

if (add) {
  // Add to list.
}
</code>```

Body:
I have a array from 0 to 10000.
problem
And i need to filter only the numbers containing either 3 or 4 or both and none other than that...
eg., 3,4,33,44,333,444,343,434,334

I tried the do while technique but I have made some mistake in the code..\
I'm not getting the output still..:(
the improved code is

import java.util.*;

import static java.lang.System.*;
public class numb {

public static void main(String[] args) {
    int num,c,cum;
    int i;
     Scanner in = new Scanner(System.in);
     out.println(3/10);

    out.println("How many elements u need to put in this array?");
    num=in.nextInt();
    int[] ray1 = new int[num];
    List<String> l1 = new LinkedList<String>();
    for (c=0;c<num;c++)
    {

        ray1[c]=c;
    }

            for(i=1;i<num;i++)
            {
         boolean baabu=true;
                do {
                    cum=ray1[i];
                    int lastdig = cum%10;
                    if(lastdig!=3||lastdig!=4)
                    {
                        baabu=false;
                    }
                    cum=cum/10;
                }
                while(cum>0&&baabu);
                if(baabu)
                {
                    String ad = String.valueOf(ray1[i]);
                    l1.add(ad);
                }

            }
            printme(l1);

}

public static void print (int[] array)
{
    for(int xc:array)
        out.println(xc);
}
public static void printme (List<String> l1)
{
    for(String yc:l1)
        out.println(yc);
}

}

Body:
Check if the last digit is a 3 or a 4: if it is, divide the number by 10 and check the next digit; otherwise, discard the number.

boolean add = true;
do {
  int lastDigit = num % 10;
  if (lastDigit != 3 && lastDigit != 4) {
    add = false;
  }
  num /= 10;
} while (add && num > 0);

if (add) {
  // Add to list.
}


问:
How do I get the Ubuntu source code?
Where can I find the source code for the latest Ubuntu release?

Also, how would I view the code? Would it just be lots of .cpp and .h files I could view in Visual Studio?

答:
archive.ubuntu.com

Most of them are .c and .h files (not sure about C++), but certainly not all (some perl, some Python, etc). There will also be a lot of documentation files that aren't saved with .txt, just like README and LICENSE.

Title: How do I get the Ubuntu source code?

ContentLicense: CC BY-SA 2.5


问:
Can i check in-App purchase in the ios simulator?
can i check in-App purchase in the simulator ? because i don’t have iPhone real device so,i couldn’t able to create provisioning profile certificate so what is the way to check in-App purchase in the simulator</p>

答:
with Xcode 9.1 now and previous, I can't really finalize transaction, but made that

id <SKPaymentTransactionObserver> observer = self;
[[SKPaymentQueue defaultQueue] addTransactionObserver:observer];

in the appDelegate falls into SKPaymentTransactionStateFailed. That's still nice.

Using #if TARGET_IPHONE_SIMULATOR(from TargetConditionals.h) here and there you can implement a very lot of code and check it, of course your UIs, including sending payment requests to Apple. At the last time you must have a Device. By the way it's an error to publish anything on the App Store without having success in tests on at least one Device.


问:
how to set date value in frontend with ngoninit in angular 5
i have an <input type="date"> which i want to be filled when the user enters the route. By visiting the site the input field should already be the actual date.
So i think ngOnInit() should be what i need. But what do i have to do to have the actual date filled in as a value to the input field, when the user enters the route?

I already tried to achive this by searching the web but only found some old solutions for angularjs although i'm using angular 5 which is not compareable with angularjs. The postings i found all pointed to the scope which is no longer existent.

The Documentation for ngOnInit also does not help me :/

HTML

```<code><div class="form-group">
    <label>Eingangsdatum</label>
    <input type="date" [(ngModel)]="dateArrival" id="dateArrivalPicker" value="" name="dateArrival" class="form-control">
</div>
</code>```

Compontent

```<code>@Component({
  selector: 'app-terminals-create',
  templateUrl: './terminals-create.component.html',
  styleUrls: ['./terminals-create.component.css']
})
export class TerminalsCreateComponent implements OnInit {

  type: String;
  serial: String;
  layout: String;
  dateArrival: Date;
  activated: Boolean;
  setup: String;
  firmware: String;
  installedAt: String;
  createdBy: String;
  createdDate: Date;
  lastModified: Date;
  lastModifiedBy: String;
  notes: String;
  macAddress: String;

  constructor(
    private validateService: ValidateService,
    private flashMessage: FlashMessagesService,
    private authService: AuthService,
    private router: Router
  ) { }

  ngOnInit() {}

}
</code>```

If i do like briosheje wrote in his comments it works, his answer doesn't :/. And there is one more thing... by using his comment i get two big errors inside my console:

```<code>Error: If ngModel is used within a form tag, either the name attribute must be set or the form
      control must be defined as 'standalone' in ngModelOptions.

      Example 1: <input [(ngModel)]="person.firstName" name="first">
      Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
</code>```

If i now give a name to my <input type="date" [ngModel]="todaysDate | date:'dd-MM-yyyy'" (ngModelChange)="todaysDate = $event" [value]="todaysDate | date:'yyyy-MM-dd'">
the function of filling this field with the acutal date is gone and only TT.MM.YYYY stands there. What can i do?

答:
It should be enough to add:

```<code>ngOnInit() {
   this.dateArrival = new Date();
}
</code>```

and change your HTML so that it will handle by itself the date to string and vice-versa, like suggested in this plunker (taken from another SO post): plnkr.co/edit/s5OMg2olU2yHI246nJOG?p=preview

```<code><input type="date" [ngModel] ="dateArrival | date:'yyyy-MM-dd'" (ngModelChange)="dateArrival = $event">
</code>```

the ngModelChange will trigger the change automatically and will handle the date convertion aswell. The NgModel, instead, will directly display the date through the date pipe

Body:
i have an <input type="date"> which i want to be filled when the user enters the route. By visiting the site the input field should already be the actual date.
So i think ngOnInit() should be what i need. But what do i have to do to have the actual date filled in as a value to the input field, when the user enters the route?

I already tried to achive this by searching the web but only found some old solutions for angularjs although i'm using angular 5 which is not compareable with angularjs. The postings i found all pointed to the scope which is no longer existent.

The Documentation for ngOnInit also does not help me :/

HTML

    Eingangsdatum
    <input type="date" [(ngModel)]="dateArrival" id="dateArrivalPicker" value="" name="dateArrival" class="form-control">

Compontent

@Component({
  selector: 'app-terminals-create',
  templateUrl: './terminals-create.component.html',
  styleUrls: ['./terminals-create.component.css']
})
export class TerminalsCreateComponent implements OnInit {

  type: String;
  serial: String;
  layout: String;
  dateArrival: Date;
  activated: Boolean;
  setup: String;
  firmware: String;
  installedAt: String;
  createdBy: String;
  createdDate: Date;
  lastModified: Date;
  lastModifiedBy: String;
  notes: String;
  macAddress: String;

  constructor(
    private validateService: ValidateService,
    private flashMessage: FlashMessagesService,
    private authService: AuthService,
    private router: Router
  ) { }

  ngOnInit() {}

}

If i do like briosheje wrote in his comments it works, his answer doesn't :/. And there is one more thing... by using his comment i get two big errors inside my console:

Error: If ngModel is used within a form tag, either the name attribute must be set or the form
      control must be defined as 'standalone' in ngModelOptions.

      Example 1: <input [(ngModel)]="person.firstName" name="first">
      Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

If i now give a name to my <input type="date" [ngModel]="todaysDate | date:'dd-MM-yyyy'" (ngModelChange)="todaysDate = $event" [value]="todaysDate | date:'yyyy-MM-dd'">
the function of filling this field with the acutal date is gone and only TT.MM.YYYY stands there. What can i do?

Body:
It should be enough to add:

ngOnInit() {
   this.dateArrival = new Date();
}

and change your HTML so that it will handle by itself the date to string and vice-versa, like suggested in this plunker (taken from another SO post): plnkr.co/edit/s5OMg2olU2yHI246nJOG?p=preview

<input type="date" [ngModel] ="dateArrival | date:'yyyy-MM-dd'" (ngModelChange)="dateArrival = $event">

the ngModelChange will trigger the change automatically and will handle the date convertion aswell. The NgModel, instead, will directly display the date through the date pipe


问:
Removing html tags what is the difference between `*?` and `*`?
I need to replace all html tags from a string in JavaScript,

I would like to know what is the difference between

using *? or only *

Question: Is the *? in the expression is equivalent to *.

A)
  text.replace(/<(?:.|\n)*?>/gm, '')

B)
    text.replace(/<(?:.|\n)*>/gm, '')

答:
Question: Is the *? in the expression is equivalent to *.

No. The latter is the greedy quantifier that matches as much characters as possible. cf. http://www.regular-expressions.info/refrepeat.html


答: Think of the string as a list of characters, eg 3435 is 3,4,3,5 and 39 is 3,9. You need to iterate over the characters in the string and check that each one is a 3 or 4. Your code checks for specific combinations of 3 and 4 but cannot handle all possible enumerations.

Title: String Filtering .. Any one..Contains only either of the selected characters or both


问:
Wrong date is getting printed
I am trying to simply pass a date and parse it using simpledateformat. But instead of printing the correct value, it's printing wrong date.

```<code>public static void main(String[] args) {
    getAge("29-02-2016");
}

public static void getAge(String dob1) {
    DateFormat format = new SimpleDateFormat("dd-mm-yyyy");
    try {
        Date dob = format.parse(dob1);
        System.out.println(dob);
        Calendar realDob = Calendar.getInstance();
        realDob.setTime(dob);
        System.out.println(realDob.get(Calendar.YEAR));
        Calendar today = Calendar.getInstance();

        int age = today.get(Calendar.YEAR) - realDob.get(Calendar.YEAR);
        if(age >=18) {
            System.out.println("18 years");
        } else {
            System.out.println("Underage");
        }

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

its printing : Fri Jan 29 00:02:00 IST 2016 but it should be February

答: mm is for minutes, use MM: DateFormat format = new SimpleDateFormat("dd-MM-yyyy");

ContentLicense: CC BY-SA 4.0

Title: Wrong date is getting printed

Body:
I am trying to simply pass a date and parse it using simpledateformat. But instead of printing the correct value, it's printing wrong date.

public static void main(String[] args) {
    getAge("29-02-2016");
}

public static void getAge(String dob1) {
    DateFormat format = new SimpleDateFormat("dd-mm-yyyy");
    try {
        Date dob = format.parse(dob1);
        System.out.println(dob);
        Calendar realDob = Calendar.getInstance();
        realDob.setTime(dob);
        System.out.println(realDob.get(Calendar.YEAR));
        Calendar today = Calendar.getInstance();

        int age = today.get(Calendar.YEAR) - realDob.get(Calendar.YEAR);
        if(age >=18) {
            System.out.println("18 years");
        } else {
            System.out.println("Underage");
        }

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

its printing : Fri Jan 29 00:02:00 IST 2016 but it should be February


问:
Attempting push on git and receiving "could not read Username for 'https://github.com': terminal prompts disabled"
I'm using Visual Studio, and the GitHub Extension. I am able to sign in, then clone my team's repository, and then pull changes successfully.

When it comes time to push my changes back to remote, I get a blank command prompt appear on the screen briefly, and then the following errors in the output window:

Error encountered while pushing to the remote repository: Git failed with a fatal error.

fatal: AggregateException encountered. One or more errors occurred.

error: cannot spawn askpass: No such file or directory

fatal: could not read Username for 'https://github.com': terminal prompts disabled

EDIT: pushing via the command line works, as does pushing via the GitHub desktop application, just not within this extension.

Any ideas why this might be happening? I can't see why it needs the Username given that I have signed into the extension.

答: What worked for me was to disconnect from all the existing connections in Visual Studio, remove them one-by-one and connect from scratch. Then immediatelly I was able to clone the repository again.</p>


问:
How can I find dependancies in my data in R? (A + B + C -> D)
I want to reduce my data by sorting out dependent variables. E.g. A + B + C -> D so I can leave out D without loosing any information.

```<code>d <- data.frame(A = c( 1, 2, 3, 4, 5),
                B = c( 2, 4, 6, 4, 2),
                C = c( 3, 4, 2, 1, 0),
                D = c( 6, 10, 11, 9, 9))
</code>```

The last value of D is wrong, that is because the data can be inaccurate.

How can I identify these dependencies with R and how can I influence the accuracy of the correlation? (e.g., use a cutoff of 80 or 90 percent)

Example findCorrelation only considers pair-wise correlations. Is there a function for multiple correlations?

答:
Although correlation matrices are helpful and perfectly legitimate, one way I find particularly useful is to look at the variance inflation factor.  Wikipedia's article describing the VIF is quite good.

A few reasons why I like to use the VIF:

Instead of looking at rows or columns of a correlation matrix, to try and divine which variables are more collinear than others with the other covariates multiply instead of singly, you get a single number which describes an aspect of a given predictor's relationship to all others in the model.

It's easy to use the VIF in a stepwise fashion to, in most cases, eliminate collinearity within your predictor space.

It's easy to obtain, either through using the vif() function in the car package, or by writing your own function to calculate.

VIF essentially works by regressing all the covariates/predictors in your model against each predictor you've included in turn.  It obtains the R^2 value and takes the ratio: 1/(1-R^2).  This gives you a number vif >= 1.  If you think of R^2 as the amount of variation in your response space explained by your selected covariate model, then if one of your covariates gets a high R^2 of, say 0.80, then your vif is 5.

You choose what your threshold of comfort is.  The wikipedia article suggests a vif of 10 indicates a predictor should go.  I was taught that 5 is a good threshold.  Often, I've found it's easy to get the vif down to less than 2 for all of my predictors without a big impact to my final models adjusted-R^2.

I feel like even a vif of 5, meaning a predictor can be modeled by its companion predictors with an R^2 of 0.80 means that that predictors marginal information contribution is quite low and not worth it.  I try to take a strategy of minimizing all of my vifs for a given model without a huge (say, > 0.1 reduction in R^2) impact to my main model.  That sort of an impact gives me a sense that even if the vif is higher than I'd like, the predictor still holds a lot of information.

There are other approaches.  You might look into Lawson's paper on an alias-matrix-guided variable selection method as well - I feel it's particularly clever, though harder to implement than what I've discussed above.

Body:
I want to reduce my data by sorting out dependent variables. E.g. A + B + C -> D so I can leave out D without loosing any information.

d <- data.frame(A = c( 1, 2, 3, 4, 5),
                B = c( 2, 4, 6, 4, 2),
                C = c( 3, 4, 2, 1, 0),
                D = c( 6, 10, 11, 9, 9))

The last value of D is wrong, that is because the data can be inaccurate.

How can I identify these dependencies with R and how can I influence the accuracy of the correlation? (e.g., use a cutoff of 80 or 90 percent)

Example findCorrelation only considers pair-wise correlations. Is there a function for multiple correlations?


问:
Twitter OAuth - Incorrect signature errors - what have I missed?
I have read the page on implementing OAuth that Twitter have written. I've registered my app, it will only access my account, so I skip all the request token stuff. I have, from the "Your apps" page:

consumer token

consumer token secret

access token

access token secret

I write some ruby code and test its output against Beginner’s Guide to OAuth (suggested reading in the Twitter docs). I get the same output, i.e. the signature, the base string and the Authorization headers are identical.

However, when I connect to the Twitter Rest API and try the verify credentials command the response is invariably "Incorrect signature".

I try using different code (very similar to mine) from a gist by erikeldridge on github but it doesn't work either. Instead of connecting via cURL (using the curb library) I use Net/Http - same error response is returned.

I change over to using the OAuth gem. It uses Net/Http to connect. Same error response comes back.

Verify credentials isn't the only command I've tried to use in the API, but they all give the same error, whether it's GET or POST, requires extra params or not. I've been using the Search API successfully using the curb library without problems so I don't think it's the connection method.

What might I do to fix this?

Ruby 1.9.2; cURL 7.21.2; oauth 0.4.4; curb 0.7.8; json 1.4.6; OSX 10.6.5;

答:
Even though your application is only accessing your data, you can't simply 'skip the request token stuff'. The request token is integral to the OAuthentication process.

Summarised, the 3 main parts of the OAuth process are as follows:

Get Request Token Key and Request Token Secret

Use Request Token to authorise application to access your data. This will provided the user(you) with a PIN

Use the PIN to exchange the Request Token and Secret for an Access Token and Secret.

A more detailed OAuthentication flow can be found here.


问:
Mask from max values in numpy array, specific axis
Input example:

I have a numpy array, e.g.

a=np.array([[0,1], [2, 1], [4, 8]])

Desired output:

I would like to produce a mask array with the max value along a given axis, in my case axis 1, being True and all others being False. e.g. in this case

mask = np.array([[False, True], [True, False], [False, True]])

Attempt:

I have tried approaches using np.amax but this returns the max values in a flattened list:

```<code>>>> np.amax(a, axis=1)
array([1, 2, 8])
</code>```

and np.argmax similarly returns the indices of the max values along that axis.

```<code>>>> np.argmax(a, axis=1)
array([1, 0, 1])
</code>```

I could iterate over this in some way but once these arrays become bigger I want the solution to remain something native in numpy.

答:
Create an identity matrix and select from its rows using argmax on your array:

```<code>np.identity(a.shape[1], bool)[a.argmax(axis=1)]
# array([[False,  True],
#        [ True, False],
#        [False,  True]], dtype=bool)
</code>```

Please note that this ignores ties, it just goes with the value returned by argmax.

Body:
Input example:

I have a numpy array, e.g.

a=np.array([[0,1], [2, 1], [4, 8]])

Desired output:

I would like to produce a mask array with the max value along a given axis, in my case axis 1, being True and all others being False. e.g. in this case

mask = np.array([[False, True], [True, False], [False, True]])

Attempt:

I have tried approaches using np.amax but this returns the max values in a flattened list:

>>> np.amax(a, axis=1)
array([1, 2, 8])

and np.argmax similarly returns the indices of the max values along that axis.

>>> np.argmax(a, axis=1)
array([1, 0, 1])

I could iterate over this in some way but once these arrays become bigger I want the solution to remain something native in numpy.

Body:
Create an identity matrix and select from its rows using argmax on your array:

np.identity(a.shape[1], bool)[a.argmax(axis=1)]
# array([[False,  True],
#        [ True, False],
#        [False,  True]], dtype=bool)

Please note that this ignores ties, it just goes with the value returned by argmax.


问:
DNN Appplication_start in global.asax not firing
I have configured some methods to be called in Application_start but Application_start does not seem to be firing at all. Any Info would be greatly appreciated.

I am using DNN 9

Thanks in advance!

答:
have you recently done any renaming in your solution?

"clean solution" and "rebuild" doesn't delete assemblies

check Global.asax Inherits="" attribute

something old may be referenced.


问:
How to re-execute a specific task in ansible playbook?
I am writing a playbook to compile an Apache-2.4 from source. I would like to have the flow of playbook as follows:

Download source package in /usr/src

Extract it in the same folder.

Now, start compiling it. Run configure, make and make install.

In case, the last process fails due to dependency issues - like apr or apr-util. Call handler and download them, keep them in /usr/src/http-source/srclib/apr and /usr/src/http-source/srclib/apr-util.

After 3rd step, i would like to retry or re-execute 3rd step. How we can do this without writing a new step again? Any ideas??

This is what i have tried:-

[root@system1 myansible]# cat apache_compile_simple.yml.
---
- hosts: system2*
  tasks:
   - name: Download the Apache source file
     get_url:
         url: http://www-us.apache.org/dist//httpd/httpd-2.4.29.tar.gz
         dest: /usr/src/
     tags: download_source
   - name: Extract the source file
     unarchive:
         src: /usr/src/httpd-2.4.29.tar.gz
         dest: /usr/src/
         remote_src: yes
     tags: extract_source
   - name: Change the working directory
     command: chdir=/usr/src/httpd-2.4.29/ ./configure --prefix=/usr/local --with-included-apr
     register: proc_status
     ignore_errors: true
     changed_when: false
     tags: configure
   - name: check for depencies
     debug: msg=""
     notify:
       - apr
       - apr-util
     changed_when: "proc_status.rc != 0"
     tags: check_dep

  handlers:
   - name: Install_dependencies
     get_url: url={{ item }} dest=/usr/src/
     with_items:
      - http://www-eu.apache.org/dist//apr/apr-1.6.3.tar.gz
      - http://www-eu.apache.org/dist//apr/apr-util-1.6.1.tar.gz
     listen: "apr"
   - name: ex_apr_dir_exist
     file:
      path: /usr/src/httpd-2.4.29/srclib/apr
      mode: 755
      state: directory
      listen: "apr"
   - name: Unarchive the apr build
     unarchive:
        src: /usr/src/apr-1.6.3.tar.gz
        dest: /usr/src/httpd-2.4.29/srclib/apr
        remote_src: yes
     listen: "apr"
   - name: Make apr-util directory
     file:
      path: /usr/src/httpd-2.4.29/srclib/apr-util
      mode: 755
      state: directory
     listen: "apr-util"
   - name: Unarchive the apr-utils build
     unarchive:
       src: /usr/src/apr-util-1.6.1.tar.gz
       dest: /usr/src/httpd-2.4.29/srclib/apr-util
       remote_src: yes
     listen: "apr-util"```

I would like to get ideas on how to re-execute "configure apache" task, after the handler is done.

答:
Take a look at Ansible's docs on reusable playbooks.  To answer your question directly you could create a separate file with the "cofigure apache" task and use include_tasks to reuse the same task in your main playbook and handlers.

However, I think it would make more sense to check for dependencies and install them first before installing apache.  Handlers are intended for when something on the system has changed and a subsequent action is required (i.e. - config for service x has been changed, restart service x).

Body:
I am writing a playbook to compile an Apache-2.4 from source. I would like to have the flow of playbook as follows:

Download source package in /usr/src

Extract it in the same folder.

Now, start compiling it. Run configure, make and make install.

In case, the last process fails due to dependency issues - like apr or apr-util. Call handler and download them, keep them in /usr/src/http-source/srclib/apr and /usr/src/http-source/srclib/apr-util.

After 3rd step, i would like to retry or re-execute 3rd step. How we can do this without writing a new step again? Any ideas??

This is what i have tried:-

[root@system1 myansible]# cat apache_compile_simple.yml.
---
- hosts: system2*
  tasks:
   - name: Download the Apache source file
     get_url:
         url: http://www-us.apache.org/dist//httpd/httpd-2.4.29.tar.gz
         dest: /usr/src/
     tags: download_source
   - name: Extract the source file
     unarchive:
         src: /usr/src/httpd-2.4.29.tar.gz
         dest: /usr/src/
         remote_src: yes
     tags: extract_source
   - name: Change the working directory
     command: chdir=/usr/src/httpd-2.4.29/ ./configure --prefix=/usr/local --with-included-apr
     register: proc_status
     ignore_errors: true
     changed_when: false
     tags: configure
   - name: check for depencies
     debug: msg=""
     notify:
       - apr
       - apr-util
     changed_when: "proc_status.rc != 0"
     tags: check_dep

  handlers:
   - name: Install_dependencies
     get_url: url={{ item }} dest=/usr/src/
     with_items:
      - http://www-eu.apache.org/dist//apr/apr-1.6.3.tar.gz
      - http://www-eu.apache.org/dist//apr/apr-util-1.6.1.tar.gz
     listen: "apr"
   - name: ex_apr_dir_exist
     file:
      path: /usr/src/httpd-2.4.29/srclib/apr
      mode: 755
      state: directory
      listen: "apr"
   - name: Unarchive the apr build
     unarchive:
        src: /usr/src/apr-1.6.3.tar.gz
        dest: /usr/src/httpd-2.4.29/srclib/apr
        remote_src: yes
     listen: "apr"
   - name: Make apr-util directory
     file:
      path: /usr/src/httpd-2.4.29/srclib/apr-util
      mode: 755
      state: directory
     listen: "apr-util"
   - name: Unarchive the apr-utils build
     unarchive:
       src: /usr/src/apr-util-1.6.1.tar.gz
       dest: /usr/src/httpd-2.4.29/srclib/apr-util
       remote_src: yes
     listen: "apr-util"

I would like to get ideas on how to re-execute "configure apache" task, after the handler is done.


问:
failing to run simple webdriver on pycharm - mac
I installed pycharm(python3.6) + selenium(3.8) on my mac.

Trying to run:

```<code>from selenium import webdriver
driver=webdriver.Firefox()
</code>```

I get error:

```<code>/Users/ronavaida/PycharmProjects/untitled/venv/bin/python /Users/ronavaida/PycharmProjects/untitled/testselenium.py
Traceback (most recent call last):
  File "/Users/ronavaida/PycharmProjects/untitled/testselenium.py", line 3, in <module>
    driver=webdriver.Firefox()
  File "/Users/ronavaida/PycharmProjects/untitled/venv/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 158, in __init__
    keep_alive=True)
  File "/Users/ronavaida/PycharmProjects/untitled/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "/Users/ronavaida/PycharmProjects/untitled/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/Users/ronavaida/PycharmProjects/untitled/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 311, in execute
    self.error_handler.check_response(response)
  File "/Users/ronavaida/PycharmProjects/untitled/venv/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 237, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities
</code>```

Please advise, thanks!

答:
The error you are seeing says it all :

```<code>SessionNotCreatedException: Message: Unable to find a matching set of capabilities
</code>```

You need to download the latest geckodriver binary from this linkand save it in your system and provide the absolute path of the geckodriver binary while initializing the WebDriver and Browser instance as follows :

```<code>from selenium import webdriver

driver = webdriver.Firefox(executable_path=r'C:\path\to\geckodriver.exe')
driver.get('https://www.google.co.in')
driver.quit()
</code>```

Body:
I installed pycharm(python3.6) + selenium(3.8) on my mac.

Trying to run:

from selenium import webdriver
driver=webdriver.Firefox()

I get error:

/Users/ronavaida/PycharmProjects/untitled/venv/bin/python /Users/ronavaida/PycharmProjects/untitled/testselenium.py
Traceback (most recent call last):
  File "/Users/ronavaida/PycharmProjects/untitled/testselenium.py", line 3, in <module>
    driver=webdriver.Firefox()
  File "/Users/ronavaida/PycharmProjects/untitled/venv/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 158, in __init__
    keep_alive=True)
  File "/Users/ronavaida/PycharmProjects/untitled/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "/Users/ronavaida/PycharmProjects/untitled/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/Users/ronavaida/PycharmProjects/untitled/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 311, in execute
    self.error_handler.check_response(response)
  File "/Users/ronavaida/PycharmProjects/untitled/venv/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 237, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities

Please advise, thanks!

Body:
The error you are seeing says it all :

SessionNotCreatedException: Message: Unable to find a matching set of capabilities

You need to download the latest geckodriver binary from this linkand save it in your system and provide the absolute path of the geckodriver binary while initializing the WebDriver and Browser instance as follows :

from selenium import webdriver

driver = webdriver.Firefox(executable_path=r'C:\path\to\geckodriver.exe')
driver.get('https://www.google.co.in')
driver.quit()


问:
query editor not visible in azure SQL DB in azure portal
I have created an SQL database in azure portal. But there is no tools section in the overview of my DB, so as there is no query editor for me to use.

Instead i have connect with option where only visual studio is shown and not the query editor. Kindly give me a solution why no tools section and how can i get Query Editor.

I had enable(ON) the allow access to all services in the Firewall settings also.

答: There is a Query Editor available on Azure Portal. You can find this experience by navigating to your SQL database and clicking the Tools command and then clicking Query Editor (preview), as shown on this Blog post.</p>


问:
How to sha256 each line in a file?
I'm using a macOS Sierra and want to sha256 each line in a file.

File:

```<code>test
example
sample
</code>```

Intended output:

```<code>9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08
50D858E0985ECC7F60418AAF0CC5AB587F42C2570A884095A9E8CCACD0F6545C
AF2BDBE1AA9B6EC1E2ADE1D694F41FC71A831D0268E9891562113D8A62ADD1BF
</code>```

I've found a few ways to do this on Ubuntu, but Mac doesn't seem to have sha256 installed on it.  From what is sounds like, you have to use something similar to shasum 256 but nothing seems to be working.

答:
openssl dgst is available out-of-the-box on MacOS (and pretty much everywhere else as well), and can be easily combined with BashFAQ #1 practices for iterating line-by-line:

```<code>### INEFFICIENT SOLUTION
hashlines() {
  while IFS= read -r line; do
    printf '%s' "$line" \
      | openssl dgst -sha256 \
      | tr '[[:lower:]]' '[[:upper:]]' \
      | sed -Ee 's/.*=[[:space:]]//'
  done
}
</code>```

That said, this is quite wildly inefficient when run on large files. If you need something that performs well, I'd write this in Python instead. Wrapped in the same shell function, with the same calling convention, that might look like:

```<code>### FAST SOLUTION
hashlines() {
  python -c '
import sys, hashlib
for line in sys.stdin:
    print(hashlib.sha256(line.rstrip("\n")).hexdigest().upper())'
}
</code>```

In either case, usage is just hashlines < filename or hashlines <<< $'line one\nline two'.

Title: How to sha256 each line in a file?

Body:
I'm using a macOS Sierra and want to sha256 each line in a file.

File:

test
example
sample

Intended output:

9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08
50D858E0985ECC7F60418AAF0CC5AB587F42C2570A884095A9E8CCACD0F6545C
AF2BDBE1AA9B6EC1E2ADE1D694F41FC71A831D0268E9891562113D8A62ADD1BF

I've found a few ways to do this on Ubuntu, but Mac doesn't seem to have sha256 installed on it.  From what is sounds like, you have to use something similar to shasum 256 but nothing seems to be working.

Body:
openssl dgst is available out-of-the-box on MacOS (and pretty much everywhere else as well), and can be easily combined with BashFAQ #1 practices for iterating line-by-line:

### INEFFICIENT SOLUTION
hashlines() {
  while IFS= read -r line; do
    printf '%s' "$line" \
      | openssl dgst -sha256 \
      | tr '[[:lower:]]' '[[:upper:]]' \
      | sed -Ee 's/.*=[[:space:]]//'
  done
}

That said, this is quite wildly inefficient when run on large files. If you need something that performs well, I'd write this in Python instead. Wrapped in the same shell function, with the same calling convention, that might look like:

### FAST SOLUTION
hashlines() {
  python -c '
import sys, hashlib
for line in sys.stdin:
    print(hashlib.sha256(line.rstrip("\n")).hexdigest().upper())'
}

In either case, usage is just hashlines < filename or hashlines <<< $'line one\nline two'.


问:
What tool should I use to create my buildmachine?
I am working on my free time on a multiplatform/multi-architecture library written in C++.

Before every release, I have to boot up several computers (One on Windows, one on Linux, another one on Mac OS, ...) just to make sure the code compiles and runs fine on every platform.

So I decided to create my own buildmachine but I really don't know what tools exist to do this. I'd like my buildmachine to run on Linux but any other solution will be accepted.

Ideally, I would just have to click on a "Build all" button, and it would compile my library for the different platforms/architectures, generate archives from the result and/or report potential errors.

My project "constraints" are:

It is written in C++

It compiles on Windows using SConstruct/MinGW and Visual Studio 2010

It compile on Linux and Mac OS using SConstruct/g++

The sources are stored into Subversion (svn)

Do you know any tool/set of tools that could help me achieving my goal ?

Thank you very much.

答:
I would setup 3 VMs (VirtualBox is free), one for each platform.

Install TeamCity (or Hudson) on Linux and agents on the other VMs and then it's just a matter of configuring the build system.

At the very basic level you should have 2 tasks: one to checkout the sources from Subversion and another to invoke scons.

I'm not too familiar with Hudson but TeamCity is certainly capable of generating reports of a build, display progress etc.


问:
Spring MVC. Tomcat. HTTP Status 404 – Not Found
I need to configure Spring Mvc without web.xml. Use only java config

My WebConfig

```<code>@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "controllers.web")
@Import({PersistenceJPAConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

@Bean
public ViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/view/jsp");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
    }
}
</code>```

My WebInitializer

```<code>public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(WebConfig.class);
    servletContext.addListener(new ContextLoaderListener(ctx));
    ctx.setServletContext(servletContext);
    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.setLoadOnStartup(1);
    servlet.addMapping("/");
}
}
</code>```

My controller

```<code>@Controller
@RequestMapping("/")

public class MainController {

@Autowired
BusRepository busRepository;

@RequestMapping(method = RequestMethod.GET)
public String index(ModelMap model) {
    StringBuilder sb = new StringBuilder("<br>");
    busRepository.findAll().forEach(it->sb.append(it.toString()).append("<br>"));
    model.put("msg", sb.toString());
    return "index";
}
}
</code>```

My index.jsp

```<code>    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring MVC</title>
</head>
<body>
    <h4>Spring MVC</h4>
    <span class="blue">${msg}</span>
</body>
</html>
</code>```

My pom.xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.intexsoft.training.manager</groupId>
    <artifactId>managers</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>managers</name>
    <url>http://localhost:8080/managers</url>
    <build>
        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>view.Runner</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>hibernate.cfg.xml</directory>
            </resource>
        </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
</project>
</code>```

I checked server's working through power shell (it works).
And when I launch server through application, I get "HTTP Status 404 – Not Found"
I tried other url.
War file was assemble.
How can I solve this problem?

thanks in advance

答:
Change this:

viewResolver.setPrefix("/WEB-INF/view/jsp");

To: (added a forward slash after jsp)

viewResolver.setPrefix("/WEB-INF/view/jsp/");

Body:
I need to configure Spring Mvc without web.xml. Use only java config

My WebConfig

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "controllers.web")
@Import({PersistenceJPAConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

@Bean
public ViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/view/jsp");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
    }
}

My WebInitializer

public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(WebConfig.class);
    servletContext.addListener(new ContextLoaderListener(ctx));
    ctx.setServletContext(servletContext);
    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.setLoadOnStartup(1);
    servlet.addMapping("/");
}
}

My controller

@Controller
@RequestMapping("/")

public class MainController {

@Autowired
BusRepository busRepository;

@RequestMapping(method = RequestMethod.GET)
public String index(ModelMap model) {
    StringBuilder sb = new StringBuilder("
");
    busRepository.findAll().forEach(it->sb.append(it.toString()).append("
"));
    model.put("msg", sb.toString());
    return "index";
}
}

My index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring MVC</title>

Spring MVC

    ${msg}

My pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.intexsoft.training.manager</groupId>
    <artifactId>managers</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>managers</name>
    <url>http://localhost:8080/managers</url>
    <build>
        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>view.Runner</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>hibernate.cfg.xml</directory>
            </resource>
        </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
</project>

I checked server's working through power shell (it works).
And when I launch server through application, I get "HTTP Status 404 – Not Found"
I tried other url.
War file was assemble.
How can I solve this problem?

thanks in advance


问:
No packages at OpenMDAO binstar channel for Anaconda install
It seems that the OpenMDAO packages have been removed from binstar? I have tried the following:

```<code>conda search -c https://conda.binstar.org/OpenMDAO openmdao
</code>```

and

```<code>conda install -c openmdao openmdao
</code>```

both resulting in the following:

```<code>PackageNotFoundError: Packages missing in current channels:

  - openmdao

We have searched for the packages in the following channels:

  - https://conda.anaconda.org/openmdao/win-64
  - https://conda.anaconda.org/openmdao/noarch
</code>```

Was OpenMDAO Anaconda support removed or am I missing something?

Edit: Is this an incompatibility with win64 vs win32?

Edit 2: Yes that is the issue as outlined in their blog post:

Caveat: Thanks to a bug in Traits (we’ve put in a bug report and await a new version), we can’t currently support an Anaconda install on a Windows2012_64bit installation unless you’re using a 32-bit Anaconda installed on the 64-bit architecture.  We will announce when that problem is resolved for our 64-bit Windows users.

答:
As per Edit2. There is no update on 64-bit support that I can find.

Caveat: Thanks to a bug in Traits (we’ve put in a bug report and await a new version), we can’t currently support an Anaconda install on a Windows2012_64bit installation unless you’re using a 32-bit Anaconda installed on the 64-bit architecture. We will announce when that problem is resolved for our 64-bit Windows users.

Body:
It seems that the OpenMDAO packages have been removed from binstar? I have tried the following:

conda search -c https://conda.binstar.org/OpenMDAO openmdao

and

conda install -c openmdao openmdao

both resulting in the following:

PackageNotFoundError: Packages missing in current channels:

  - openmdao

We have searched for the packages in the following channels:

  - https://conda.anaconda.org/openmdao/win-64
  - https://conda.anaconda.org/openmdao/noarch

Was OpenMDAO Anaconda support removed or am I missing something?

Edit: Is this an incompatibility with win64 vs win32?

Edit 2: Yes that is the issue as outlined in their blog post:

Caveat: Thanks to a bug in Traits (we’ve put in a bug report and await a new version), we can’t currently support an Anaconda install on a Windows2012_64bit installation unless you’re using a 32-bit Anaconda installed on the 64-bit architecture.  We will announce when that problem is resolved for our 64-bit Windows users.


问:
Reorder Umbraco to have Articles/Year/Month/Article map structure
I have a website that's been running for over a year. The overview is getting lost in the Articles doctype and I've been asked to change the file structure from Articles/Article to Articles/Year/Month/Article.

In short, the admin opens Umbraco and sees the Articles and clicks the arrow to see all the articles. It then takes a couple of minutes since the are all loaded. Instead I want a map structure that devides the articles into year and month published.

Since i'm talking about 5k articles, I can't really do this manually.

Any advice?

答:
You could do 2 things:

Create a simple script which moves all articles into a year/month folder structure. Should be pretty simple to make.

Add a List View content type on your "Articles" template. It will give a searchable list with all 5K articles. It will prevent the loadtime in Umbraco UI. You can see how the list view works here: http://www.robertgray.net.au/posts/a-first-look-at-umbraco-container-content-types


问:
How to upload imageDataBase64 image using appery.io and API?
Currently I'm developing an app that's able to snap photos and upload to a server and return true and photo name using appery.io. Now I'm able to snap the photo and get the image in imageDataBase64 format, but I don't know how to upload it to my database. I have followed the example available online but I still can't upload the image, I get:

Request-URI Too Large The requested URLs length exceeds the capacity
  limit for this server.

Below are the images that I created in appery.io and the API that I use to upload my photo.

```<code>$data = $_POST['data'];
$servername = "localhost";
$username = "kipkad_mage154";
$password = "momoko123";
$dbname = "kipkad_demo_kipcard";
$conn = new mysqli($servername, $username, $password, $dbname);
$file_path = realpath("../media/rewardreceipt/");
$base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
$data = base64_decode($base64img);
$file = $file_path . uniqid() . '.jpeg';
$success = file_put_contents($file, $data);
if (move_uploaded_file($success, $file_path) {
    $arr = array('result' =>$file);
    echo json_encode($arr);
} else{
    $arr = array('result' =>'false');
    echo json_encode($arr);
}
</code>```

答: Check out this sample app: https://docs.appery.io/docs/samples-picture-upload-app -- it shows how to take a picture and upload it to the database using JavaScript API and also Cordova File API> </p>

Body:
Currently I'm developing an app that's able to snap photos and upload to a server and return true and photo name using appery.io. Now I'm able to snap the photo and get the image in imageDataBase64 format, but I don't know how to upload it to my database. I have followed the example available online but I still can't upload the image, I get:

Request-URI Too Large The requested URLs length exceeds the capacity
  limit for this server.

Below are the images that I created in appery.io and the API that I use to upload my photo.

$data = $_POST['data'];
$servername = "localhost";
$username = "kipkad_mage154";
$password = "momoko123";
$dbname = "kipkad_demo_kipcard";
$conn = new mysqli($servername, $username, $password, $dbname);
$file_path = realpath("../media/rewardreceipt/");
$base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
$data = base64_decode($base64img);
$file = $file_path . uniqid() . '.jpeg';
$success = file_put_contents($file, $data);
if (move_uploaded_file($success, $file_path) {
    $arr = array('result' =>$file);
    echo json_encode($arr);
} else{
    $arr = array('result' =>'false');
    echo json_encode($arr);
}


问:
Picker Not Showing?
When I drag PickerView on my window as my program runs, it's not showing any PickerView? Please guide me. Sorry for my poor English.

答:
I assume you are new to iPhone programming so, a million of things could be happening.
Just some guesses/advices:

Make sure the view you are seeing when you run the program and when editing it in Interface Builder is the same.(If you are not sure, change the background color of the view so you will know, etc.)

Make sure you did save the file (in interface builder) before compiling.

In Xcode, Clear all and Build again ;)

Title: Picker Not Showing?


问:
Redirect to default in Web Api Authorize
My problem: When a session expires user still can perform an action (search). Action results are some garbage (controller is not visited). I don't know why; I just want to redirect a user to login page.

My plan is to make custom Authorize and override HandleUnauthorizedRequest(HttpActionContext) and redirect a user to index.
I have no idea how to redirect to my default page.

Sample code:

```<code>public class SessionTimeoutAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        base.HandleUnauthorizedRequest(actionContext);
        //redirect here
    }
}
</code>```

答:
You're looking to set Response of actionContext to Unauthorized http response. Here's a sample how to do so.

```<code>public class SessionTimeoutAttribute: AuthorizeAttribute {
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) {

        base.HandleUnauthorizedRequest(actionContext);
        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);

    }
}
</code>```

This should hopefully redirect user to the page you (hopefully) defined in CookieAuthenticationOptions.

Edit: To be honest, this kind of defined the purpose of Web API if you let users access it in the same way as you would enter a normal page. You should on the client determine if response from the web api endpoint was success, unathorized etc. You should be returning that instead of direct redirect from the web api.

If you really wanted to redirect, you might try the following...

```<code>var response = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);
response.Headers.Location = new Uri("https://www.stackoverflow.com");
actionContext.Response = response;
</code>```

Again, I don't see the point in redirecting from Web API. It should only return the requested data/errors. You should be processing it else where.

Body:
My problem: When a session expires user still can perform an action (search). Action results are some garbage (controller is not visited). I don't know why; I just want to redirect a user to login page.

My plan is to make custom Authorize and override HandleUnauthorizedRequest(HttpActionContext) and redirect a user to index.
I have no idea how to redirect to my default page.

Sample code:

public class SessionTimeoutAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        base.HandleUnauthorizedRequest(actionContext);
        //redirect here
    }
}

Body:
You're looking to set Response of actionContext to Unauthorized http response. Here's a sample how to do so.

public class SessionTimeoutAttribute: AuthorizeAttribute {
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) {

        base.HandleUnauthorizedRequest(actionContext);
        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);

    }
}

This should hopefully redirect user to the page you (hopefully) defined in CookieAuthenticationOptions.

Edit: To be honest, this kind of defined the purpose of Web API if you let users access it in the same way as you would enter a normal page. You should on the client determine if response from the web api endpoint was success, unathorized etc. You should be returning that instead of direct redirect from the web api.

If you really wanted to redirect, you might try the following...

var response = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);
response.Headers.Location = new Uri("https://www.stackoverflow.com");
actionContext.Response = response;

Again, I don't see the point in redirecting from Web API. It should only return the requested data/errors. You should be processing it else where.


问:
Java define Generic Class param with a const or static method
I'd like to improve my code especially my way to use Generic classes.
In my project I have about 30 classes like folowing :

```<code>GenericEntity<T extends Serializable>{

    protected T id;
    public T getId(){ return id;};
...
}

public class A extends GenericEntity<Integer>{
    ...
}

public interface IService<T extends GenericEntity, T extends Serializable>{
...
}

public class AService extends IService<A,Integer>{
...
}
</code>```

I would like to specify the class of my entity Id only one time instead of one in GenericEntity and one in Service like that.

```<code>public class A extends GenericEntity<getIdType()>{
    public final static Class getIdType(){
        return Integer.class;
    }
}

public class AService extends IService<A,A.getIdType()>{
...
}
</code>```

I'm aware it doesn't work like that but I'm hoping there is a way to do it.
Thanks for your help.

答:
Instead of:

```<code>class GenericEntity<T extends Serializable>{
    protected T id;
    public T getId(){ return id;};
}

// THESE ARE UNNECESSARY as far as I can tell
class A extends GenericEntity<Integer>{ }
class B extends GenericEntity<Long>{ }

// where U matches the generic type of GenericEntity<?>
interface IService<T extends GenericEntity<?>, U extends Serializable>{ }

class AService extends IService<A, Integer>{ }
class BService extends IService<B, Long>{ }
</code>```

You could do this:

```<code>class GenericEntity<T extends Serializable> {
    protected T id;
    public T getIdFromEntity() { return id; }
}

// 'IService' can/should only know of 'id' as some type that extends 'Serializeable'
// So if something implements 'IService' then everything knows it will have
// a method with the signature 'T getGenericEntity(Serializable id);'
interface IService<T extends GenericEntity<?>> {
    public T getGenericEntity(Serializable id);
}

// 'AService' knows that 'id' will be an 'Integer'
class AService implements IService<GenericEntity<Integer>> {

    Map<Serializable, GenericEntity<Integer>> entityMap = new HashMap<>();

    void someMethod() {
        GenericEntity<Integer> entity = this.getGenericEntity(Integer.valueOf(1));
        Integer i1 = entity.getIdFromEntity();
        // ... do stuff
    }

    // even though 'AService' knows that 'id' will be an 'Integer'
    // the 'IService' interface defines this as taking a 'Serializable'
    // so it must keep that method signature.
    @Override public GenericEntity<Integer> getGenericEntity(Serializable id) {
        return entityMap.get(id);
    }
}

class BService implements IService<GenericEntity<Long>> {
    @Override public GenericEntity<Long> getGenericEntity(Serializable id) { return null; }
    // ... similar to AService ...
}
</code>```

This would cut out all your excess class X extends GenericEntity<SOME_TYPE> classes.

You would only need the one generic GenericEntity<T extends Serializable> and the one interface IService<T extends GenericEntity<?>>. Also, since they aren't generic AService and BService know the actual type that extends Serializeable (Integer and Long), so they don't need the extra info passed to them in generics.

Since IService is generic for any T extends GenericEntity<?> it shouldn't know a concrete type for genericEntity.getId() (and you probably shouldn't want it to).  Also you should avoid making it concrete because it's an Interface.

The type of id as far as IService cares is Serializable, since IService<GenericEntity<?>> implies that the wildcard ? extends Serializeable since class GenericEntity<T extends Serializeable> requires it to.

Body:
I'd like to improve my code especially my way to use Generic classes.
In my project I have about 30 classes like folowing :

GenericEntity<T extends Serializable>{

    protected T id;
    public T getId(){ return id;};
...
}

public class A extends GenericEntity<Integer>{
    ...
}

public interface IService<T extends GenericEntity, T extends Serializable>{
...
}

public class AService extends IService{
...
}

I would like to specify the class of my entity Id only one time instead of one in GenericEntity and one in Service like that.

public class A extends GenericEntity<getIdType()>{
    public final static Class getIdType(){
        return Integer.class;
    }
}

public class AService extends IService{
...
}

I'm aware it doesn't work like that but I'm hoping there is a way to do it.
Thanks for your help.

Body:
Instead of:

class GenericEntity<T extends Serializable>{
    protected T id;
    public T getId(){ return id;};
}

// THESE ARE UNNECESSARY as far as I can tell
class A extends GenericEntity<Integer>{ }
class B extends GenericEntity<Long>{ }

// where U matches the generic type of GenericEntity<?>
interface IService<T extends GenericEntity<?>, U extends Serializable>{ }

class AService extends IService<A, Integer>{ }
class BService extends IService<B, Long>{ }

You could do this:

class GenericEntity<T extends Serializable> {
    protected T id;
    public T getIdFromEntity() { return id; }
}

// 'IService' can/should only know of 'id' as some type that extends 'Serializeable'
// So if something implements 'IService' then everything knows it will have
// a method with the signature 'T getGenericEntity(Serializable id);'
interface IService<T extends GenericEntity<?>> {
    public T getGenericEntity(Serializable id);
}

// 'AService' knows that 'id' will be an 'Integer'
class AService implements IService<GenericEntity<Integer>> {

    Map<Serializable, GenericEntity<Integer>> entityMap = new HashMap<>();

    void someMethod() {
        GenericEntity<Integer> entity = this.getGenericEntity(Integer.valueOf(1));
        Integer i1 = entity.getIdFromEntity();
        // ... do stuff
    }

    // even though 'AService' knows that 'id' will be an 'Integer'
    // the 'IService' interface defines this as taking a 'Serializable'
    // so it must keep that method signature.
    @Override public GenericEntity<Integer> getGenericEntity(Serializable id) {
        return entityMap.get(id);
    }
}

class BService implements IService<GenericEntity<Long>> {
    @Override public GenericEntity<Long> getGenericEntity(Serializable id) { return null; }
    // ... similar to AService ...
}

This would cut out all your excess class X extends GenericEntity<SOME_TYPE> classes.

You would only need the one generic GenericEntity<T extends Serializable> and the one interface IService<T extends GenericEntity<?>>. Also, since they aren't generic AService and BService know the actual type that extends Serializeable (Integer and Long), so they don't need the extra info passed to them in generics.

Since IService is generic for any T extends GenericEntity<?> it shouldn't know a concrete type for genericEntity.getId() (and you probably shouldn't want it to).  Also you should avoid making it concrete because it's an Interface.

The type of id as far as IService cares is Serializable, since IService<GenericEntity<?>> implies that the wildcard ? extends Serializeable since class GenericEntity<T extends Serializeable> requires it to.


问:
Python automate user tasks in kvm-qemu/remote-viewer
I'm working on a simple script to automate a repetitive task of starting a virtual machine, finding it's spice tcp port and starting remote-viewer to interact with the virtual machine. The commands in sequence are:

```<code>virsh -c qemu:///system start test_machine
virsh -c qemu:///system domdisplay test_machine
</code>```

This outputs something like: spice://127.0.0.1:5903. The third command is:

```<code>remote-viewer spice://127.0.0.1:5903
</code>```

In python 2.7.5 on RHEL 7 I have the script:

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

import subprocess
import pipes

machine_name = 'test_machine'

return_code = subprocess.check_output(['virsh', '-c', 'qemu:///system', 'start', machine_name])
return_code = subprocess.check_output(['virsh', '-c', 'qemu:///system', 'domdisplay', machine_name])
print str(return_code)
esc_return_code = pipes.quote(return_code)
print "remote-viewer {}".format(return_code)
#proc = subprocess.check_output(["remote-viewer {}".format(esc_return_code)]) #, return_code])
</code>```

The first two of my commands work as expected--it's the third command with remote-viewer that throws an error.

I've tried a few different things thinking it was special characters causing a problem but now that I see the first two commands working just fine I'm not convinced. I also tried the same format as the first two commands like this:

```<code>subprocess.check_output(['remote-viewer', return_code])
</code>```

Running the script as is gives the output:

```<code>spice://127.0.0.1:5903

remote-viewer spice://127.0.0.1:5903

Traceback (most recent call last):
  File "/mnt/data/Scripts/runvm.py", line 13, in <module>
    proc = subprocess.check_output(["remote-viewer {}".format(esc_return_code)]) #, return_code])
  File "/usr/lib64/python2.7/subprocess.py", line 568, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
</code>```

If I hard code the values (no variables) it works. Like this:

```<code>subprocess.check_output(['remote-viewer spice://127.0.0.1:5903'])
</code>```

What am I missing?

答:
You can use Popen and shell=True to run the command</p>

```<code>From subprocess import Popen
output='spice://127.0.0.1:5903'
Command='remote-viewer'+' '+output
#Proc=Popen(Command,shell=True)
Proc=Popen(Command)
</code>```

Body:
I'm working on a simple script to automate a repetitive task of starting a virtual machine, finding it's spice tcp port and starting remote-viewer to interact with the virtual machine. The commands in sequence are:

virsh -c qemu:///system start test_machine
virsh -c qemu:///system domdisplay test_machine

This outputs something like: spice://127.0.0.1:5903. The third command is:

remote-viewer spice://127.0.0.1:5903

In python 2.7.5 on RHEL 7 I have the script:

#!/usr/bin/python

import subprocess
import pipes

machine_name = 'test_machine'

return_code = subprocess.check_output(['virsh', '-c', 'qemu:///system', 'start', machine_name])
return_code = subprocess.check_output(['virsh', '-c', 'qemu:///system', 'domdisplay', machine_name])
print str(return_code)
esc_return_code = pipes.quote(return_code)
print "remote-viewer {}".format(return_code)
#proc = subprocess.check_output(["remote-viewer {}".format(esc_return_code)]) #, return_code])

The first two of my commands work as expected--it's the third command with remote-viewer that throws an error.

I've tried a few different things thinking it was special characters causing a problem but now that I see the first two commands working just fine I'm not convinced. I also tried the same format as the first two commands like this:

subprocess.check_output(['remote-viewer', return_code])

Running the script as is gives the output:

spice://127.0.0.1:5903

remote-viewer spice://127.0.0.1:5903

Traceback (most recent call last):
  File "/mnt/data/Scripts/runvm.py", line 13, in <module>
    proc = subprocess.check_output(["remote-viewer {}".format(esc_return_code)]) #, return_code])
  File "/usr/lib64/python2.7/subprocess.py", line 568, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

If I hard code the values (no variables) it works. Like this:

subprocess.check_output(['remote-viewer spice://127.0.0.1:5903'])

What am I missing?

Body:
You can use Popen and shell=True to run the command

From subprocess import Popen
output='spice://127.0.0.1:5903'
Command='remote-viewer'+' '+output
#Proc=Popen(Command,shell=True)
Proc=Popen(Command)


问:
CSS animations on
I am trying to apply a CSS animation to a  element and I just can't get it to work. I can't find any resource that says whether animations can be applied to  elements. So, is it me that is making an error, or are spans animation immune?

Edit: Code

```<code>Inf<span class="inf_o">o</span>rmation
    <br>
do<span class="don_n">n</span>e
    <br>
we<span class="dbl_l">ll</span>
</code>```

and css:

```<code>/* animations */
.inf_o
{
  -webkit-animation-name: lower_head;
  -webkit-animation-duration: 3s;
  -webkit-animation-timing-function:ease-in;
  -webkit-animation-delay: 1s;
  -webkit-animation-play-state: active;
}

@-webkit-keyframes lower_head
{
  from {margin-top:0px;}
  to {margin-top:10px;}
}
</code>```

答:
I had a hard time getting my span animation to work.  In my case, the page loads with the span's display set to none.  I tried many work-arounds but the one that worked in the end (unfortunately) was removing the display: none from css and hiding it when the page loads.

In case it matters, I am using jQuery to hide/show the span.

Title: CSS animations on <span>

Body:
I am trying to apply a CSS animation to a  element and I just can't get it to work. I can't find any resource that says whether animations can be applied to  elements. So, is it me that is making an error, or are spans animation immune?

Edit: Code

Information

done

well

and css:

/* animations */
.inf_o
{
  -webkit-animation-name: lower_head;
  -webkit-animation-duration: 3s;
  -webkit-animation-timing-function:ease-in;
  -webkit-animation-delay: 1s;
  -webkit-animation-play-state: active;
}

@-webkit-keyframes lower_head
{
  from {margin-top:0px;}
  to {margin-top:10px;}
}


问:
Drag borderless windows form by mouse

Possible Duplicate:

  C# - Make a borderless form movable?

I have made a form without border in C#, by setting

this.FormBorderStyle = FormBorderStyle.None;

Now, problem is how can I drag it by mouse?

答: You have to register for the MouseDown, MouseUp and MouseMove events and move the form according to the movement of the mouse.</p>

Title: Drag borderless windows form by mouse


问:
Disable attribute doesn't work with Azure Functions
I'm trying to disable a Function app, by using the Disable attribute with an app setting:

```<code>[Disable("Disable")]
[FunctionName("MyFunction")]
public static void Run([TimerTrigger("0 0 8 * * *")]TimerInfo myTimer)
</code>```

When compiling this function, the function.json looks like this:

```<code>{
    ...
    "disabled": "Disable",
    ...
}
</code>```

On my function app on Azure, I've defined the following app setting:

But when looking at the functions in the function app, the function is still disabled:

I was expecting the function not to be disabled, since the value of the app setting is 0. I guess the function app is disabled if the value of the disabled field in json is true if not set to false?

答:
This looks like portal UI issue to me. I created a Timer Function and followed your scenario. The function is shown as disabled in the portal, but it still runs on schedule.

If I change the setting from 0 to 1, it's still shown as disabled, but also doesn't run anymore.

Update (thanks to @ahmelsayed):
See github issue (and related). UI only handles truthy values for that property, which should be fixed.

Body:
I'm trying to disable a Function app, by using the Disable attribute with an app setting:

[Disable("Disable")]
[FunctionName("MyFunction")]
public static void Run([TimerTrigger("0 0 8 * * *")]TimerInfo myTimer)

When compiling this function, the function.json looks like this:

{
    ...
    "disabled": "Disable",
    ...
}

On my function app on Azure, I've defined the following app setting:

But when looking at the functions in the function app, the function is still disabled:

I was expecting the function not to be disabled, since the value of the app setting is 0. I guess the function app is disabled if the value of the disabled field in json is true if not set to false?


问:
Spotify: embed player with multiple playlists
I would like to embed a Spotify player with 3 or 4 Spotify playlists, not just one. How?

Any feedback highly appreciated. Thanks!

答: I assume you're using Spotify Widgets - this isn't possible at the moment. You can either build your own widget using the Spotify Web API or embed multiple widgets on your page, one per playlist.</p>


问:
Mask from max values in numpy array, specific axis
Input example:

I have a numpy array, e.g.

a=np.array([[0,1], [2, 1], [4, 8]])

Desired output:

I would like to produce a mask array with the max value along a given axis, in my case axis 1, being True and all others being False. e.g. in this case

mask = np.array([[False, True], [True, False], [False, True]])

Attempt:

I have tried approaches using np.amax but this returns the max values in a flattened list:

```<code>>>> np.amax(a, axis=1)
array([1, 2, 8])
</code>```

and np.argmax similarly returns the indices of the max values along that axis.

```<code>>>> np.argmax(a, axis=1)
array([1, 0, 1])
</code>```

I could iterate over this in some way but once these arrays become bigger I want the solution to remain something native in numpy.

答:
You're already halfway in the answer. Once you compute the max along an axis, you can compare it with the input array and you'll have the required binary mask!

```<code>In [7]: maxx = np.amax(a, axis=1)

In [8]: maxx
Out[8]: array([1, 2, 8])

In [12]: a >= maxx[:, None]
Out[12]:
array([[False,  True],
       [ True, False],
       [False,  True]], dtype=bool)
</code>```

Note: This uses NumPy broadcasting when doing the comparison between a and maxx

Body:
Input example:

I have a numpy array, e.g.

a=np.array([[0,1], [2, 1], [4, 8]])

Desired output:

I would like to produce a mask array with the max value along a given axis, in my case axis 1, being True and all others being False. e.g. in this case

mask = np.array([[False, True], [True, False], [False, True]])

Attempt:

I have tried approaches using np.amax but this returns the max values in a flattened list:

>>> np.amax(a, axis=1)
array([1, 2, 8])

and np.argmax similarly returns the indices of the max values along that axis.

>>> np.argmax(a, axis=1)
array([1, 0, 1])

I could iterate over this in some way but once these arrays become bigger I want the solution to remain something native in numpy.

Body:
You're already halfway in the answer. Once you compute the max along an axis, you can compare it with the input array and you'll have the required binary mask!

In [7]: maxx = np.amax(a, axis=1)

In [8]: maxx
Out[8]: array([1, 2, 8])

In [12]: a >= maxx[:, None]
Out[12]:
array([[False,  True],
       [ True, False],
       [False,  True]], dtype=bool)

Note: This uses NumPy broadcasting when doing the comparison between a and maxx