问:
access value for dictionary key in swift
I am having a problem with accessing the value of the key alert in [AnyHashable("aps")]. I am trying to store the notification alert into a string so I can do further actions, but I was not able to access the alert value. Do you guys know what I am doing wrong?

I am new to swift and trying to get my hands dirty through building my own app. I appreciate your help guys!

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
                              withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    print(userInfo)

    completionHandler([.sound, .alert])
}
</code>```

actual output:

```<code>[
    AnyHashable("gcm.message_id"): 0:1559231429586204%16146ddd16146ddd,
    AnyHashable("google.c.a.ts"): 1559231429,
    AnyHashable("aps"): {
        alert = "BBQ event on 6/15";
        sound = enabled;
    },
    AnyHashable("gcm.n.e"): 1,
    AnyHashable("google.c.a.udt"): 0,
    AnyHashable("gcm.notification.sound2"): enabled,
    AnyHashable("google.c.a.e"): 1,
    AnyHashable("google.c.a.c_id"): 5464147931275974726
]
</code>```

expected output:

```<code>"BBQ event on 6/15"
</code>```

答:
You need to first fetch value of aps as Dictionary of type [AnyHashable:Any]. Then get the value of alert from apsDict, i.e.

```<code>if let apsDict = userInfo["aps"] as? [AnyHashable:Any] {
    if let alert = apsDict["alert"] {
        print("Alert: \(alert)")
    }
}
</code>```

Body:
I am having a problem with accessing the value of the key alert in [AnyHashable("aps")]. I am trying to store the notification alert into a string so I can do further actions, but I was not able to access the alert value. Do you guys know what I am doing wrong?

I am new to swift and trying to get my hands dirty through building my own app. I appreciate your help guys!

func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
                              withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    print(userInfo)

    completionHandler([.sound, .alert])
}

actual output:

[
    AnyHashable("gcm.message_id"): 0:1559231429586204%16146ddd16146ddd,
    AnyHashable("google.c.a.ts"): 1559231429,
    AnyHashable("aps"): {
        alert = "BBQ event on 6/15";
        sound = enabled;
    },
    AnyHashable("gcm.n.e"): 1,
    AnyHashable("google.c.a.udt"): 0,
    AnyHashable("gcm.notification.sound2"): enabled,
    AnyHashable("google.c.a.e"): 1,
    AnyHashable("google.c.a.c_id"): 5464147931275974726
]

expected output:

"BBQ event on 6/15"

Body:
You need to first fetch value of aps as Dictionary of type [AnyHashable:Any]. Then get the value of alert from apsDict, i.e.

if let apsDict = userInfo["aps"] as? [AnyHashable:Any] {
    if let alert = apsDict["alert"] {
        print("Alert: \(alert)")
    }
}


来源: stackexchange

问:
Search Bar AutoComplete by Address and Place Name - Swift 4

Goal

I want to make my search box auto-complete detecting place name and address.

Currently, my search box auto-complete detecting only the address.

I used this one in my iOS app. Result is looking good for addresses but not place name.

```<code>https://github.com/shmidt/GooglePlacesSearchController
</code>```

I want it to detect places, like B&H Photo in NYC and so on ?

Example what I'm trying to do

Is it a paid service that I need to enable on Google API Console Library ?

Can someone sheds some lights on this ?

答:
Just change your GooglePlacesSearchController initialization parameter placeType to .noFilter

```<code>let controller = GooglePlacesSearchController(
    delegate: self, apiKey: GoogleMapsAPIServerKey, placeType: .noFilter)
</code>```

For anyone with the same question but different implementation , just add a filter to your GMSAutocompleteViewController

```<code>let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self

// Specify a filter.
let filter = GMSAutocompleteFilter()
filter.type = .noFilter
autocompleteController.autocompleteFilter = filter
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Goal

I want to make my search box auto-complete detecting place name and address.

Currently, my search box auto-complete detecting only the address.

I used this one in my iOS app. Result is looking good for addresses but not place name.

https://github.com/shmidt/GooglePlacesSearchController

I want it to detect places, like B&H Photo in NYC and so on ?

Example what I'm trying to do

Is it a paid service that I need to enable on Google API Console Library ?

Can someone sheds some lights on this ?

Body:
Just change your GooglePlacesSearchController initialization parameter placeType to .noFilter

let controller = GooglePlacesSearchController(
    delegate: self, apiKey: GoogleMapsAPIServerKey, placeType: .noFilter)

For anyone with the same question but different implementation , just add a filter to your GMSAutocompleteViewController

let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self

// Specify a filter.
let filter = GMSAutocompleteFilter()
filter.type = .noFilter
autocompleteController.autocompleteFilter = filter


问:
Performance impact of adding unique constraint to existing postgres index
We have a fairly large table in a postgres and during some refactoring process we realized there was an Index on an existing UUID column but it was lacking a unique constraint.

Does anyone have any experience applying an ALTER TABLE ... ADD CONSTRAINT ala https://www.postgresql.org/docs/9.4/indexes-unique.html and what the runtime impact is?

Trying to evaluate the runtime impact of doing this live vs. taking downtime. We've tested it on db copies but it difficult to simulate production traffic load and just looking for something to check if anybody had experience.

答:
To do it without downtime, you should do it in two steps:

```<code> CREATE UNIQUE INDEX CONCURRENTLY index_name ON table_name (id);
</code>```

```<code> ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE
 USING INDEX index_name;
</code>```

Body:
To do it without downtime, you should do it in two steps:

 CREATE UNIQUE INDEX CONCURRENTLY index_name ON table_name (id);

 ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE
 USING INDEX index_name;


问:
Error passing a comma separated String to Add-UnifiedGroupLinks resuling in a "Couldn't find object" error
I am trying to bulk-load an Office 365 Group using Add-UnifiedGroupLinks which works if only passing one value as a string but the command supports a comma separated list. However, when passing it a comma separated string it returns "Couldn't find object "user1@domain.com,user2@domain.com"

I can get it to work by running only one user at a time but it is MUCH slower and based on the large number of users doesn't really suite my needs. I can take the string that I build and copy and paste from that and run the same line of code manually and it works without issue. I also tried with only 3 or 5 users at a time but same issue.

```<code>$sb = New-Object System.Text.StringBuilder
$i = 1
Import-CSV "myCSV.csv" | ForEach-Object {
    [void]$sb.Append($_.UserPrincipalName + ',')
    if($i -eq 20) {
        $sb.Length--
        Add-UnifiedGroupLinks –Identity "MyGroupName" –LinkType Members –Links $sb.ToString()
        Write-Host $sb.ToString()
        $sb.Clear()
        $i = 1
        }
        Else {$i++}
    }
</code>```

Note: I have additional code to handle the remainder after the loop runs but not relevant to the issue at hand.

It returns Couldn't find object "user1@domain.com,user2@domain.com".
However if I manually run this line, it works:

Add-UnifiedGroupLinks –Identity "MyGroupName" –LinkType Members –Links user1@domain.com,user2@domain.com

Or if I do one at a time it works:

```<code>Import-CSV "myCSV.csv" | ForEach-Object {
Add-UnifiedGroupLinks –Identity "MyGroupName" –LinkType Members –Links $_.UserPrincipalName
}
</code>```

but performance is awful with the last option when doing over 20K users it is averaging about 400 an hour (one every 9 seconds or so).

答:
Instead of using String builder, I should have used an Array of Strings and passed that in:</p>

```<code>$strArr = New-Object System.Collections.ArrayList
Import-CSV "myCSV.csv" | ForEach-Object {
    $strArr.Add($_.UserPrincipalName) > $null
    if($strArr.Count -eq 100) {
        Add-UnifiedGroupLinks –Identity "MyGroupName" –LinkType Members –Links $strArr
        $strArr.Clear()
        }
    }
Add-UnifiedGroupLinks –Identity "MyGroupName" –LinkType Members –Links $strArr
</code>```

Body:
I am trying to bulk-load an Office 365 Group using Add-UnifiedGroupLinks which works if only passing one value as a string but the command supports a comma separated list. However, when passing it a comma separated string it returns "Couldn't find object "user1@domain.com,user2@domain.com"

I can get it to work by running only one user at a time but it is MUCH slower and based on the large number of users doesn't really suite my needs. I can take the string that I build and copy and paste from that and run the same line of code manually and it works without issue. I also tried with only 3 or 5 users at a time but same issue.

$sb = New-Object System.Text.StringBuilder
$i = 1
Import-CSV "myCSV.csv" | ForEach-Object {
    [void]$sb.Append($_.UserPrincipalName + ',')
    if($i -eq 20) {
        $sb.Length--
        Add-UnifiedGroupLinks –Identity "MyGroupName" –LinkType Members –Links $sb.ToString()
        Write-Host $sb.ToString()
        $sb.Clear()
        $i = 1
        }
        Else {$i++}
    }

Note: I have additional code to handle the remainder after the loop runs but not relevant to the issue at hand.

It returns Couldn't find object "user1@domain.com,user2@domain.com".
However if I manually run this line, it works:

Add-UnifiedGroupLinks –Identity "MyGroupName" –LinkType Members –Links user1@domain.com,user2@domain.com

Or if I do one at a time it works:

Import-CSV "myCSV.csv" | ForEach-Object {
Add-UnifiedGroupLinks –Identity "MyGroupName" –LinkType Members –Links $_.UserPrincipalName
}

but performance is awful with the last option when doing over 20K users it is averaging about 400 an hour (one every 9 seconds or so).

Body:
Instead of using String builder, I should have used an Array of Strings and passed that in:

$strArr = New-Object System.Collections.ArrayList
Import-CSV "myCSV.csv" | ForEach-Object {
    $strArr.Add($_.UserPrincipalName) > $null
    if($strArr.Count -eq 100) {
        Add-UnifiedGroupLinks –Identity "MyGroupName" –LinkType Members –Links $strArr
        $strArr.Clear()
        }
    }
Add-UnifiedGroupLinks –Identity "MyGroupName" –LinkType Members –Links $strArr


问:
Where should I put my .js files in my Angular app? angular.json(angular-cli.json) or assets/dist folder?
I saw that some js are defined in angular.json(angular-cli.json) and some of thems are put to assets/dist folder and referenced from index.html.

Which one is true or has they other purposes?

答:
angular.json at the root level of an Angular workspace provides
  workspace-wide and project-specific configuration defaults for build
  and development tools provided by the Angular CLI. Path values given
  in the configuration are relative to the root workspace folder.

```<code>"my-app": {
  "root": "",
  "sourceRoot": "src",
  "projectType": "application",
  "prefix": "app",
  "schematics": {},
  "architect": {
    "build": {},
    "serve": {},
    "e2e": {},
    "test": {},
    "lint": {},
    "extract-i18n": {},
    "server": {},
    "app-shell": {}
  }
}
</code>```

Workspace configuration files

All projects within a workspace share a CLI configuration context. The
  top level of the workspace contains workspace-wide configuration
  files, configuration files for the root-level application, and
  subfolders for the root-level application source and test files.

Application source files

Files at the top level of src/ support testing and running your
  application. Subfolders contain the application source and
  application-specific configuration.

Inside the src/ folder, the app/ folder contains your project's logic and data. Angular components, templates, and styles go here.

The dist folder

The build command also creates a new folder called dist for
  distribution. These are the files we can host on a server and our
  Angular app will load up.

Body:
angular.json at the root level of an Angular workspace provides
  workspace-wide and project-specific configuration defaults for build
  and development tools provided by the Angular CLI. Path values given
  in the configuration are relative to the root workspace folder.

"my-app": {
  "root": "",
  "sourceRoot": "src",
  "projectType": "application",
  "prefix": "app",
  "schematics": {},
  "architect": {
    "build": {},
    "serve": {},
    "e2e": {},
    "test": {},
    "lint": {},
    "extract-i18n": {},
    "server": {},
    "app-shell": {}
  }
}

Workspace configuration files

All projects within a workspace share a CLI configuration context. The
  top level of the workspace contains workspace-wide configuration
  files, configuration files for the root-level application, and
  subfolders for the root-level application source and test files.

Application source files

Files at the top level of src/ support testing and running your
  application. Subfolders contain the application source and
  application-specific configuration.

Inside the src/ folder, the app/ folder contains your project's logic and data. Angular components, templates, and styles go here.

The dist folder

The build command also creates a new folder called dist for
  distribution. These are the files we can host on a server and our
  Angular app will load up.


问:
Avoiding copying large objects in R - does get() function make copy?
I have an inherited some R code that uses an idiom to avoid copying of large data frames. When a function that builds the data frame finishes, it does not return the data frame, but instead stores it in the global environment context:

```<code>assign(df_name, df, envir = globalenv())
</code>```

After the function finishes, the calling code retrieves the data frame with this:

```<code>df <- get(df_name, envir = globalenv())
</code>```

My question is this: does the get() function itself actually make a copy when it returns a value, thus creating the very copy that this idiom was meant to avoid? If so, is there a better way of doing this?

答:
As far as I know, returning something doesn't actually copy it from one memory location to another.
A couple of tests:

```<code>trace_return <- function() {
  df <- data.frame(a = 1:10, b = letters[1:10])
  print(tracemem(df))
  df
}

ans <- trace_return()
# "<00000188C114D578>"
ans$a[1L] <- 0L # copy triggered on modify
# tracemem[0x00000188c114d578 -> 0x00000188c10ab098]:
# tracemem[0x00000188c10ab098 -> 0x00000188c10ab258]: $<-.data.frame $<-
# tracemem[0x00000188c10ab258 -> 0x00000188c10ab358]: $<-.data.frame $<-
</code>```

And:

```<code>e <- new.env()
e$ans <- trace_return()
# "<00000188C13F8EF8>"
ans <- e$ans # no copy here
ans$b <- NULL
# tracemem[0x00000188c13f8ef8 -> 0x00000188c14293f8]:
# tracemem[0x00000188c14293f8 -> 0x00000188c1429378]: $<-.data.frame $<-
# tracemem[0x00000188c1429378 -> 0x00000188c1429278]: $<-.data.frame $<-
</code>```

Body:
I have an inherited some R code that uses an idiom to avoid copying of large data frames. When a function that builds the data frame finishes, it does not return the data frame, but instead stores it in the global environment context:

assign(df_name, df, envir = globalenv())

After the function finishes, the calling code retrieves the data frame with this:

df <- get(df_name, envir = globalenv())

My question is this: does the get() function itself actually make a copy when it returns a value, thus creating the very copy that this idiom was meant to avoid? If so, is there a better way of doing this?

Body:
As far as I know, returning something doesn't actually copy it from one memory location to another.
A couple of tests:

trace_return <- function() {
  df <- data.frame(a = 1:10, b = letters[1:10])
  print(tracemem(df))
  df
}

ans <- trace_return()
# "<00000188C114D578>"
ans$a[1L] <- 0L # copy triggered on modify
# tracemem[0x00000188c114d578 -> 0x00000188c10ab098]:
# tracemem[0x00000188c10ab098 -> 0x00000188c10ab258]: $<-.data.frame $<-
# tracemem[0x00000188c10ab258 -> 0x00000188c10ab358]: $<-.data.frame $<-

And:

e <- new.env()
e$ans <- trace_return()
# "<00000188C13F8EF8>"
ans <- e$ans # no copy here
ans$b <- NULL
# tracemem[0x00000188c13f8ef8 -> 0x00000188c14293f8]:
# tracemem[0x00000188c14293f8 -> 0x00000188c1429378]: $<-.data.frame $<-
# tracemem[0x00000188c1429378 -> 0x00000188c1429278]: $<-.data.frame $<-


问:
Splitting rows that contain a list of postcode prefixes into multiple rows, based on postcode area
I have a table with several columns of data, one of which contains a list of different combined postcode prefixes on the same row.

Here's an example of the table layout:

```<code>+------+-----------------------------+
| Col1 |            Col2             |
+------+-----------------------------+
| a    | AB10; AB11;  DD10; DD9      |
| b    | S5; SS7; AA1; AA4           |
| c    | AB33; AB34; AB36; GG10; GS9 |
+------+-----------------------------+
</code>```

I'm looking to split the postcode prefixes into multiple rows, based on the area of the postcode, as below:

```<code>+------+------------------+
| Col1 |       Col2       |
+------+------------------+
| a    | AB10; AB11       |
| a    | DD10; DD9        |
| b    | S5               |
| b    | SS7              |
| b    | AA1; AA4         |
| c    | AB33; AB34; AB36 |
| c    | GG10             |
| c    | GS9              |
+------+------------------+
</code>```

I've found a VBA solution that splits, using the semicolon as a delimiter, but not how I need it done.

Sub splitByColB()
    Dim r As Range, i As Long, ar
    Set r = Worksheets("Sheet1").Range("B4").End(xlUp)
    Do While r.Row > 1
        ar = Split(r.Value, ";")
        If UBound(ar) >= 0 Then r.Value = ar(0)
        For i = UBound(ar) To 1 Step -1
            r.EntireRow.Copy
            r.Offset(1).EntireRow.Insert
            r.Offset(1).Value = ar(i)
        Next
        Set r = r.Offset(-1)
    Loop
End Sub
```

I could import the table in SQLExpress, so an SQL solution would also be welcome.

答:
The SQL solution I put together uses a T-SQL function called DelimitedSplit8K which works like the VB SPLIT function you are using.

```<code>-- Sample Data
DECLARE @table TABLE (Col1 CHAR(1) UNIQUE, Col2 CHAR(200));
INSERT @table (Col1,Col2) VALUES ('a','AB10; AB11;  DD10; DD9'),
  ('b','S5; SS7; AA1; AA4'),('c','AB33; AB34; AB36; GG10; GS9');

WITH xx(Col1,i,Pre) AS
(
  SELECT      t2.Col1, ss.Item+'', f.Pre
  FROM        @table AS t2
  CROSS APPLY dbo.DelimitedSplit8K(t2.Col2,';')                          AS s
  CROSS APPLY (VALUES(RTRIM(LTRIM(s.item))))                             AS ss(Item)
  CROSS APPLY (VALUES(SUBSTRING(ss.Item,0,PATINDEX('%[0-9]%',ss.Item)))) AS f(Pre)
)
SELECT   xx.col1, col2 = STUFF((SELECT '; '+i
                                FROM    xx AS x2
                                WHERE   x2.Col1 = xx.Col1 AND x2.Pre = xx.Pre
                                FOR XML PATH('')),1,2,'')
FROM     xx
GROUP BY col1, xx.Pre;
</code>```

Returns:

```<code>col1 Col2
---- ----------------------
a    AB10; AB11
a    DD10; DD9
b    AA1; AA4
b    S5
b    SS7
c    AB33; AB34; AB36
c    GG10
c    GS9
</code>```

I also put together a solution that works with SQL Server 2017 which is cleaner (in case you upgrade or others or using 2017.)

```<code>-- Sample Data
DECLARE @table TABLE (Col1 CHAR(1) UNIQUE, Col2 CHAR(200));
INSERT @table (Col1,Col2) VALUES ('a','AB10; AB11;  DD10; DD9'),
  ('b','S5; SS7; AA1; AA4'),('c','AB33; AB34; AB36; GG10; GS9');

SELECT t.Col1, split.item
FROM @table AS t
CROSS APPLY
(
  SELECT      STRING_AGG(ss.Item,'; ') WITHIN GROUP (ORDER BY ss.Item)
  FROM        @table AS t2
  CROSS APPLY STRING_SPLIT(t2.Col2,';') AS s
  CROSS APPLY (VALUES(TRIM(s.[value]))) AS ss(Item)
  WHERE       t.Col1 = t2.col1
  GROUP BY    SUBSTRING(ss.Item,0,PATINDEX('%[0-9]%',ss.Item))
) AS split(item);
</code>```

Body:
I have a table with several columns of data, one of which contains a list of different combined postcode prefixes on the same row.

Here's an example of the table layout:

+------+-----------------------------+
| Col1 |            Col2             |
+------+-----------------------------+
| a    | AB10; AB11;  DD10; DD9      |
| b    | S5; SS7; AA1; AA4           |
| c    | AB33; AB34; AB36; GG10; GS9 |
+------+-----------------------------+

I'm looking to split the postcode prefixes into multiple rows, based on the area of the postcode, as below:

+------+------------------+
| Col1 |       Col2       |
+------+------------------+
| a    | AB10; AB11       |
| a    | DD10; DD9        |
| b    | S5               |
| b    | SS7              |
| b    | AA1; AA4         |
| c    | AB33; AB34; AB36 |
| c    | GG10             |
| c    | GS9              |
+------+------------------+

I've found a VBA solution that splits, using the semicolon as a delimiter, but not how I need it done.

Sub splitByColB()
    Dim r As Range, i As Long, ar
    Set r = Worksheets("Sheet1").Range("B4").End(xlUp)
    Do While r.Row > 1
        ar = Split(r.Value, ";")
        If UBound(ar) >= 0 Then r.Value = ar(0)
        For i = UBound(ar) To 1 Step -1
            r.EntireRow.Copy
            r.Offset(1).EntireRow.Insert
            r.Offset(1).Value = ar(i)
        Next
        Set r = r.Offset(-1)
    Loop
End Sub

I could import the table in SQLExpress, so an SQL solution would also be welcome.

Body:
The SQL solution I put together uses a T-SQL function called DelimitedSplit8K which works like the VB SPLIT function you are using.

-- Sample Data
DECLARE @table TABLE (Col1 CHAR(1) UNIQUE, Col2 CHAR(200));
INSERT @table (Col1,Col2) VALUES ('a','AB10; AB11;  DD10; DD9'),
  ('b','S5; SS7; AA1; AA4'),('c','AB33; AB34; AB36; GG10; GS9');

WITH xx(Col1,i,Pre) AS
(
  SELECT      t2.Col1, ss.Item+'', f.Pre
  FROM        @table AS t2
  CROSS APPLY dbo.DelimitedSplit8K(t2.Col2,';')                          AS s
  CROSS APPLY (VALUES(RTRIM(LTRIM(s.item))))                             AS ss(Item)
  CROSS APPLY (VALUES(SUBSTRING(ss.Item,0,PATINDEX('%[0-9]%',ss.Item)))) AS f(Pre)
)
SELECT   xx.col1, col2 = STUFF((SELECT '; '+i
                                FROM    xx AS x2
                                WHERE   x2.Col1 = xx.Col1 AND x2.Pre = xx.Pre
                                FOR XML PATH('')),1,2,'')
FROM     xx
GROUP BY col1, xx.Pre;

Returns:

col1 Col2
---- ----------------------
a    AB10; AB11
a    DD10; DD9
b    AA1; AA4
b    S5
b    SS7
c    AB33; AB34; AB36
c    GG10
c    GS9

I also put together a solution that works with SQL Server 2017 which is cleaner (in case you upgrade or others or using 2017.)

-- Sample Data
DECLARE @table TABLE (Col1 CHAR(1) UNIQUE, Col2 CHAR(200));
INSERT @table (Col1,Col2) VALUES ('a','AB10; AB11;  DD10; DD9'),
  ('b','S5; SS7; AA1; AA4'),('c','AB33; AB34; AB36; GG10; GS9');

SELECT t.Col1, split.item
FROM @table AS t
CROSS APPLY
(
  SELECT      STRING_AGG(ss.Item,'; ') WITHIN GROUP (ORDER BY ss.Item)
  FROM        @table AS t2
  CROSS APPLY STRING_SPLIT(t2.Col2,';') AS s
  CROSS APPLY (VALUES(TRIM(s.[value]))) AS ss(Item)
  WHERE       t.Col1 = t2.col1
  GROUP BY    SUBSTRING(ss.Item,0,PATINDEX('%[0-9]%',ss.Item))
) AS split(item);


问:
Input Date value Property django
I'm trying to display the value of a date field from the database in my HTML but the field still shows blank text

I've tried using the Django pipe when setting the value of the date. When I even use the same exact code in the label it works well but doesn't just work in the date field

This is my views.py file

```<code>def all(request):
    employees = Employee.objects.all().order_by('last_name')
    departments = Department.objects.all()
    table = EmployeeTable(employees)
    RequestConfig(request).configure(table)
    context =  {
        'table':table,
        'employees':employees,
        'departments':departments
    }
    if request.method == "POST":
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        name = last_name +' '+first_name
        employee_id = request.POST['employee_id']
        email = request.POST['email']
        department = Department.objects.get(dept_name = request.POST['department'])
        address = request.POST['address']
        employment_type = request.POST['employment_type']
        employment_status = request.POST['employment_status']
        role = request.POST['role']
        marital_status = request.POST['marital_status']
        gender = request.POST['gender']
        join_date = request.POST['join_date']
        end_date = None if len(request.POST['end_date']) ==0 else request.POST['end_date']
        location = request.POST['location']
        credentials = request.POST['credentials']
        passport = request.POST['passport']
        hod = request.POST['hod']
        phone_number = request.POST['phone_number']
        date_of_birth = request.POST['date_of_birth']
        date_added = datetime.now()

</code>```

This my HTML code

```<code><div class="col-sm-6">
  <div class="form-group">
     <label for='date_of_birth' class="control-label">Date of Birth
       {{employee.date_of_birth|date:'Y/m/d'}}
       {{employee.date_of_birth|date:'m-d-Y'}}
       {{employee.date_of_birth|date:'SHORT_DATE_FORMAT'}} <span class="text-
       danger">*</span>
     </label>
     <input name='date_of_birth' type="date"  class="form-control" value = "
     {{employee.date_of_birth|date:'m/d/Y'}} " >
   </div>
</div>

</code>```

答:
The format of the value=... attribute for an <input type="date"> [mozilla-doc] is:

A DOMString representing a date in YYYY-MM-DD format, or empty.

So your <input> element should be:

```<code><input type="date" <b>value="{{employee.date_of_birth|date:'Y-m-d'}}"</b> name="date_of_birth" class="form-control"></code>```

Title: Input Date value Property django

Body:
I'm trying to display the value of a date field from the database in my HTML but the field still shows blank text

I've tried using the Django pipe when setting the value of the date. When I even use the same exact code in the label it works well but doesn't just work in the date field

This is my views.py file

def all(request):
    employees = Employee.objects.all().order_by('last_name')
    departments = Department.objects.all()
    table = EmployeeTable(employees)
    RequestConfig(request).configure(table)
    context =  {
        'table':table,
        'employees':employees,
        'departments':departments
    }
    if request.method == "POST":
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        name = last_name +' '+first_name
        employee_id = request.POST['employee_id']
        email = request.POST['email']
        department = Department.objects.get(dept_name = request.POST['department'])
        address = request.POST['address']
        employment_type = request.POST['employment_type']
        employment_status = request.POST['employment_status']
        role = request.POST['role']
        marital_status = request.POST['marital_status']
        gender = request.POST['gender']
        join_date = request.POST['join_date']
        end_date = None if len(request.POST['end_date']) ==0 else request.POST['end_date']
        location = request.POST['location']
        credentials = request.POST['credentials']
        passport = request.POST['passport']
        hod = request.POST['hod']
        phone_number = request.POST['phone_number']
        date_of_birth = request.POST['date_of_birth']
        date_added = datetime.now()

This my HTML code

     Date of Birth
       {{employee.date_of_birth|date:'Y/m/d'}}
       {{employee.date_of_birth|date:'m-d-Y'}}
       {{employee.date_of_birth|date:'SHORT_DATE_FORMAT'}} *

     <input name='date_of_birth' type="date"  class="form-control" value = "
     {{employee.date_of_birth|date:'m/d/Y'}} " >

Body:
The format of the value=... attribute for an <input type="date"> [mozilla-doc] is:

A DOMString representing a date in YYYY-MM-DD format, or empty.

So your <input> element should be:

<input type="date" value="{{employee.date_of_birth|date:'Y-m-d'}}" name="date_of_birth" class="form-control">


问:
Laravel strange date formatting
I inherited a Laravel project and am running into a strange issue with date formatting.

I get the following error:

InvalidArgumentException in Carbon.php line 582

Unexpected data found.

Unexpected data found.

The separation symbol could not be found

Unexpected data found

Trailing data

The stack track shows the problem has to do with a date time conversion:

at Carbon::createFromFormat('Y-m-d H:i:s.u', 'Oct 10 2017 02:31:04:493PM') in Model.php line 3003

I can see that there is a weird date format with 02:31:04:493PM as the time. I don't know where that format is coming from and I've spent literally all day trying.

All of the date formats in the application code are of the 'Y-m-d H:i:s.u' or 'Y-m-d H:i:s' format. I don't know where this invalid one with the : before microseconds is coming from and I can't seem to find it anywhere in the code.

I've checked in Model.php, Carbon.php, all of the app Models that inherit from Model, etc. When I run the project on localhost environment, everything loads fine, but when I try on the dev environment, this error happens.

The leads me to believe it is something environment specific, but I don't know enough about Apache/PHP/SQL Server to know where the formatting is coming from. The data in the database appears just fine as normal datetime values.

Any ideas or suggestions on where to look?

答:
The issue was resolved by migrating our PHP server from FreeBSD to IIS.

Our environment did not have the appropriate PDO SQLSRV drivers to communicate to our SQL Server database properly and Microsoft doesn't provide pre-compiled versions for FreeBSD.

Our organization did not need to use FreeBSD and so we moved to IIS because it was easier for our new members to manage.  With IIS, we were able to download the Microsoft PDO SQLSRV drivers that are compiled for IIS/Windows and this made the DB queries yield the correct date formats.

ContentLicense: CC BY-SA 3.0

Title: Laravel strange date formatting


问:
How to get php vars to display in html
I am executing a php script which collects some variables from a form, then displays a page from a MySQL table. The page is displayed fine, but the echoed variable are not.

```<code>    <h4>Conference Registration</h4>
    <p><strong>
        <?php echo $confName $confDate; ?>
    </strong></p>
</code>```

The expected result is that the two variable are displayed.
I tested that the variable were available by inserting an echo command at the top of the page.

The actual result is that the variable are not displayed.

When displaying the page source in the browser and hovering over the <?php line displayed in red, the following is displayed:

Saw "<p". Probable cause: Attempt to use an XML processing
  instruction in HTML. (XML procesing instructions are not supported in
  HTML.)

答:
You cannot just place two variables next to each other and expect the echo command to display them. You need to use two echo commands, or place a comma between the variables:

```<code>echo $confName;
echo $confDate;

// or use comma;
echo $confName, $confDate;
</code>```

Or alternatively, learn how to concatenate the variables:

```<code>echo $confName." - ".$confDate;
</code>```

Title: How to get php vars to display in html

Body:
I am executing a php script which collects some variables from a form, then displays a page from a MySQL table. The page is displayed fine, but the echoed variable are not.

Conference Registration

        <?php echo $confName $confDate; ?>

The expected result is that the two variable are displayed.
I tested that the variable were available by inserting an echo command at the top of the page.

The actual result is that the variable are not displayed.

When displaying the page source in the browser and hovering over the <?php line displayed in red, the following is displayed:

Saw "<p". Probable cause: Attempt to use an XML processing
  instruction in HTML. (XML procesing instructions are not supported in
  HTML.)

Body:
You cannot just place two variables next to each other and expect the echo command to display them. You need to use two echo commands, or place a comma between the variables:

echo $confName;
echo $confDate;

// or use comma;
echo $confName, $confDate;

Or alternatively, learn how to concatenate the variables:

echo $confName." - ".$confDate;


问:
var output = 1 + 2 + 3 + "4" + 5 + "90"; Output : 64590;; Just want to know why?
Need to know the logical reason behind the stated output

```<code>var output = 1 + 2 + 3 + "4" + 5 + "90";
</code>```

Output : "64590"

答:
Because expressions are evaluated from left to right, and all of the operators in this expression have the same order of precedence.  So let's take them one at a time...

```<code>1 + 2 = 3
3 + 3 = 6
6 + "4" = "64"
"64" + 5 = "645"
"645" + "90" = "64590"
</code>```

When you use + on two integers the result is an integer, summing the two

When you use + on two strings the result is a string, concatenating the two

When you use + on a string and an integer (or anything, I suspect) the result is a string, implicitly converting the integer to a string (likely by invoking .ToString() on it in the compiled code) and then concatenating the two

Any time the result of a multi-part expression is unexpected, a good debugging step is to split it into individual operations and store the results in observable variables.  Then step through each operation in a debugger and observe the result of each.  If a specific operation produces an unexpected result, your next step is to identify what result you expected and why.

Body:
Need to know the logical reason behind the stated output

var output = 1 + 2 + 3 + "4" + 5 + "90";

Output : "64590"

Body:
Because expressions are evaluated from left to right, and all of the operators in this expression have the same order of precedence.  So let's take them one at a time...

1 + 2 = 3
3 + 3 = 6
6 + "4" = "64"
"64" + 5 = "645"
"645" + "90" = "64590"

When you use + on two integers the result is an integer, summing the two

When you use + on two strings the result is a string, concatenating the two

When you use + on a string and an integer (or anything, I suspect) the result is a string, implicitly converting the integer to a string (likely by invoking .ToString() on it in the compiled code) and then concatenating the two

Any time the result of a multi-part expression is unexpected, a good debugging step is to split it into individual operations and store the results in observable variables.  Then step through each operation in a debugger and observe the result of each.  If a specific operation produces an unexpected result, your next step is to identify what result you expected and why.


问:
How do I support Internet Explorer in an Angular 8 application?
When I generate a project with Angular CLI (8.0.0), I run ng serve, open the application up in Internet Explorer and I am presented with a blank screen.

I had a look at the polyfills.ts files and I uncommented the following lines:

```<code>    import 'classlist.js';
    import 'web-animations-js';
</code>```

I've also removed all core.js imports as Angular 8 supports core.js 3.0 directly.

I've also ran npm i.

package.json:

```<code>"dependencies": {
    "@angular/animations": "~8.0.0",
    "@angular/common": "~8.0.0",
    "@angular/compiler": "~8.0.0",
    "@angular/core": "~8.0.0",
    "@angular/forms": "~8.0.0",
    "@angular/platform-browser": "~8.0.0",
    "@angular/platform-browser-dynamic": "~8.0.0",
    "@angular/router": "~8.0.0",
    "classlist.js": "^1.1.20150312",
    "rxjs": "~6.4.0",
    "tslib": "^1.9.0",
    "web-animations-js": "^2.3.1",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.0",
    "@angular/cli": "~8.0.0",
    "@angular/compiler-cli": "~8.0.0",
    "@angular/language-service": "~8.0.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.4.3"
  }
</code>```

tsconfig.json:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}
</code>```

EDIT:

browserlists:

```<code># This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries

# You can see what browsers were selected by your queries by running:
#   npx browserslist

> 0.5%
last 2 versions
Firefox ESR
not dead
IE 9-11 # For IE 9-11 support, remove 'not'.
</code>```

EDIT 2:

The console in Internet Explorer (11) shows the following errors:

polyfills.js:
Syntax error (3168, 5)
(line 3168 beginning) -> class Zone {

vendor.js:
Syntax error (156, 1)
(line 156 beginning) -> class PlatformLocation {

main.ts:
Syntax error (95, 20)
(points to the AppComponent)

What else do I need to do?

答:
To support IE fully we had to pull in a special set of polyfills from the mdn-polyfills library.

To install them use

```<code>npm i -s mdn-polyfills
</code>```

next add them to the polyfills.ts file like this

```<code>import 'mdn-polyfills/Object.assign';
import 'mdn-polyfills/Object.create';
import 'mdn-polyfills/Object.entries';
import 'mdn-polyfills/Array.from';
import 'mdn-polyfills/Array.of';
import 'mdn-polyfills/Array.prototype.find';
import 'mdn-polyfills/Array.prototype.forEach';
import 'mdn-polyfills/Array.prototype.filter';
import 'mdn-polyfills/Array.prototype.findIndex';
import 'mdn-polyfills/Array.prototype.includes';
import 'mdn-polyfills/String.prototype.includes';
import 'mdn-polyfills/String.prototype.repeat';
import 'mdn-polyfills/String.prototype.startsWith';
import 'mdn-polyfills/String.prototype.endsWith';
import 'mdn-polyfills/String.prototype.padStart';
import 'mdn-polyfills/String.prototype.padEnd';
import 'mdn-polyfills/Function.prototype.bind';
import 'mdn-polyfills/NodeList.prototype.forEach';
import 'mdn-polyfills/Element.prototype.closest';
import 'mdn-polyfills/Element.prototype.matches';
import 'mdn-polyfills/MouseEvent';
import 'mdn-polyfills/CustomEvent';
</code>```

after this you should stop experiencing many of the issues in IE.

Body:
When I generate a project with Angular CLI (8.0.0), I run ng serve, open the application up in Internet Explorer and I am presented with a blank screen.

I had a look at the polyfills.ts files and I uncommented the following lines:

    import 'classlist.js';
    import 'web-animations-js';

I've also removed all core.js imports as Angular 8 supports core.js 3.0 directly.

I've also ran npm i.

package.json:

"dependencies": {
    "@angular/animations": "~8.0.0",
    "@angular/common": "~8.0.0",
    "@angular/compiler": "~8.0.0",
    "@angular/core": "~8.0.0",
    "@angular/forms": "~8.0.0",
    "@angular/platform-browser": "~8.0.0",
    "@angular/platform-browser-dynamic": "~8.0.0",
    "@angular/router": "~8.0.0",
    "classlist.js": "^1.1.20150312",
    "rxjs": "~6.4.0",
    "tslib": "^1.9.0",
    "web-animations-js": "^2.3.1",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.0",
    "@angular/cli": "~8.0.0",
    "@angular/compiler-cli": "~8.0.0",
    "@angular/language-service": "~8.0.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.4.3"
  }

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

EDIT:

browserlists:

# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries

# You can see what browsers were selected by your queries by running:
#   npx browserslist

> 0.5%
last 2 versions
Firefox ESR
not dead
IE 9-11 # For IE 9-11 support, remove 'not'.

EDIT 2:

The console in Internet Explorer (11) shows the following errors:

polyfills.js:
Syntax error (3168, 5)
(line 3168 beginning) -> class Zone {

vendor.js:
Syntax error (156, 1)
(line 156 beginning) -> class PlatformLocation {

main.ts:
Syntax error (95, 20)
(points to the AppComponent)

What else do I need to do?

Body:
To support IE fully we had to pull in a special set of polyfills from the mdn-polyfills library.

To install them use

npm i -s mdn-polyfills

next add them to the polyfills.ts file like this

import 'mdn-polyfills/Object.assign';
import 'mdn-polyfills/Object.create';
import 'mdn-polyfills/Object.entries';
import 'mdn-polyfills/Array.from';
import 'mdn-polyfills/Array.of';
import 'mdn-polyfills/Array.prototype.find';
import 'mdn-polyfills/Array.prototype.forEach';
import 'mdn-polyfills/Array.prototype.filter';
import 'mdn-polyfills/Array.prototype.findIndex';
import 'mdn-polyfills/Array.prototype.includes';
import 'mdn-polyfills/String.prototype.includes';
import 'mdn-polyfills/String.prototype.repeat';
import 'mdn-polyfills/String.prototype.startsWith';
import 'mdn-polyfills/String.prototype.endsWith';
import 'mdn-polyfills/String.prototype.padStart';
import 'mdn-polyfills/String.prototype.padEnd';
import 'mdn-polyfills/Function.prototype.bind';
import 'mdn-polyfills/NodeList.prototype.forEach';
import 'mdn-polyfills/Element.prototype.closest';
import 'mdn-polyfills/Element.prototype.matches';
import 'mdn-polyfills/MouseEvent';
import 'mdn-polyfills/CustomEvent';

after this you should stop experiencing many of the issues in IE.


问:
Why the status of my G Suite Marketplace app always displays: GAM: pending?
I have published my G Suite Marketplace app for the better part of a month, but the status is always "GAM: pending" and there is no one who told me if there is something wrong with my app and I do't know what should I do for this situation? </p>

答:
The same thing is happening to me. When I reached out to Add-on Support they replied with the following:

The “GAM pending” status shown in the CWS developer dashboard is an
  expected behaviour and is an old status that will be changed once the
  CWS migration completed.


问:
Is there anyway to reset multi index in pandas?
I want to obtain stock data using pandas_datareader. I have the data, but the index I got is multiIndex.
_data.columns

```<code>MultiIndex(levels=[['High', 'Low', 'Open', 'Close', 'Volume', 'Adj Close'], ['MSFT']],
           codes=[[0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 0, 0]],
           names=['Attributes', 'Symbols'])

from pandas_datareader import data as pdr
import yfinance
_data = pdr.get_data_yahoo(['MSFT'], start='2019-01-01', end='2019-05-30')
</code>```

The format I want to get is single index.So that i can use that data to plot

```<code>    symbol  date            price
0   MSFT    2000-01-01  39.81
1   MSFT    2000-02-01  36.35
2   MSFT    2000-03-01  43.22
3   MSFT    2000-04-01  28.37
4   MSFT    2000-05-01  25.45
</code>```

Body:
I want to obtain stock data using pandas_datareader. I have the data, but the index I got is multiIndex.
_data.columns

MultiIndex(levels=[['High', 'Low', 'Open', 'Close', 'Volume', 'Adj Close'], ['MSFT']],
           codes=[[0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 0, 0]],
           names=['Attributes', 'Symbols'])

from pandas_datareader import data as pdr
import yfinance
_data = pdr.get_data_yahoo(['MSFT'], start='2019-01-01', end='2019-05-30')

The format I want to get is single index.So that i can use that data to plot

    symbol  date            price
0   MSFT    2000-01-01  39.81
1   MSFT    2000-02-01  36.35
2   MSFT    2000-03-01  43.22
3   MSFT    2000-04-01  28.37
4   MSFT    2000-05-01  25.45

Body:
I think you need reset_index with melt

 from pandas_datareader import data as pdr
import yfinance
_data = pdr.get_data_yahoo(['MSFT'], start='2019-01-01', end='2019-05-30')
print(_data)

   Attributes   High    Low Open    Close   Volume  Adj Close
Symbols MSFT    MSFT    MSFT    MSFT    MSFT    MSFT
Date
2019-01-02  101.750000  98.940002   99.550003   101.120003  35329300.0  100.318642
2019-01-03  100.190002  97.199997   100.099998  97.400002   42523600.0  96.628120
2019-01-04  102.510002  98.930000   99.720001   101.930000  44060600.0  101.122223
2019-01-07  103.269997  100.980003  101.639999  102.059998  35656100.0  101.251190
2019-01-08  103.970001  101.709999  103.040001  102.800003  31514400.0  101.985329

we can reset_index and melt passing date as our id_vars

df = _data.reset_index().melt(id_vars='Date') # You can filter out attributes if you don't need them.
print(df)

 Date   Attributes  Symbols value
0   2019-01-02  High    MSFT    101.750000
1   2019-01-03  High    MSFT    100.190002
2   2019-01-04  High    MSFT    102.510002
3   2019-01-07  High    MSFT    103.269997
4   2019-01-08  High    MSFT    103.970001
5   2019-01-09  High    MSFT    104.879997
6   2019-01-10  High    MSFT    103.750000
7   2019-01-11  High    MSFT    103.440002


问:
None persistent Prometheus metrics on Kubernetes
I'm collecting Prometheus metrics from a uwsgi application hosted on Kubernetes, the metrics are not retained after the pods are deleted. Prometheus server is hosted on the same kubernetes cluster and I have assigned a persistent storage to it.

How do I retain the metrics from the pods even after they deleted?

The Prometheus deployment yaml:

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: prometheus
  namespace: default
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: prometheus
    spec:
      containers:
        - name: prometheus
          image: prom/prometheus
          args:
            - "--config.file=/etc/prometheus/prometheus.yml"
            - "--storage.tsdb.path=/prometheus/"
            - "--storage.tsdb.retention=2200h"
          ports:
            - containerPort: 9090
          volumeMounts:
            - name: prometheus-config-volume
              mountPath: /etc/prometheus/
            - name: prometheus-storage-volume
              mountPath: /prometheus/
      volumes:
        - name: prometheus-config-volume
          configMap:
            defaultMode: 420
            name: prometheus-server-conf
        - name: prometheus-storage-volume
          persistentVolumeClaim:
            claimName: azurefile
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: prometheus
  name: prometheus
spec:
  type: LoadBalancer
  loadBalancerIP: ...
  ports:
    - port: 80
      protocol: TCP
      targetPort: 9090
  selector:
    app: prometheus

</code>```

Application deployment yaml:

```<code>
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: api-app
  template:
    metadata:
      labels:
        app: api-app
    spec:
      containers:
      - name: nginx
        image: nginx
        lifecycle:
          preStop:
            exec:
              command: ["/usr/sbin/nginx","-s","quit"]
        ports:
          - containerPort: 80
            protocol: TCP
        resources:
          limits:
            cpu: 50m
            memory: 100Mi
          requests:
            cpu: 10m
            memory: 50Mi
        volumeMounts:
          - name: app-api
            mountPath: /var/run/app
          - name: nginx-conf
            mountPath: /etc/nginx/conf.d
      - name: api-app
        image: azurecr.io/app_api_se:opencv
        workingDir: /app
        command: ["/usr/local/bin/uwsgi"]
        args:
          - "--die-on-term"
          - "--manage-script-name"
          - "--mount=/=api:app_dispatch"
          - "--socket=/var/run/app/uwsgi.sock"
          - "--chmod-socket=777"
          - "--pyargv=se"
          - "--metrics-dir=/storage"
          - "--metrics-dir-restore"
        resources:
          requests:
            cpu: 150m
            memory: 1Gi
        volumeMounts:
          - name: app-api
            mountPath: /var/run/app
          - name: storage
            mountPath: /storage
      volumes:
        - name: app-api
          emptyDir: {}
        - name: storage
          persistentVolumeClaim:
            claimName: app-storage
        - name: nginx-conf
          configMap:
            name: app
      tolerations:
      - key: "sku"
        operator: "Equal"
        value: "test"
        effect: "NoSchedule"
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: api-app
  name: api-app
spec:
  ports:
    - port: 80
      protocol: TCP
      targetPort: 80
  selector:
    app: api-app
</code>```

答:
With this configuration for a volume, it will be removed when you release a pod. You are basically looking for a PersistentVolumne, documentation and example.

Also check, PersistentVolumeClaim.

Body:
I'm collecting Prometheus metrics from a uwsgi application hosted on Kubernetes, the metrics are not retained after the pods are deleted. Prometheus server is hosted on the same kubernetes cluster and I have assigned a persistent storage to it.

How do I retain the metrics from the pods even after they deleted?

The Prometheus deployment yaml:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: prometheus
  namespace: default
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: prometheus
    spec:
      containers:
        - name: prometheus
          image: prom/prometheus
          args:
            - "--config.file=/etc/prometheus/prometheus.yml"
            - "--storage.tsdb.path=/prometheus/"
            - "--storage.tsdb.retention=2200h"
          ports:
            - containerPort: 9090
          volumeMounts:
            - name: prometheus-config-volume
              mountPath: /etc/prometheus/
            - name: prometheus-storage-volume
              mountPath: /prometheus/
      volumes:
        - name: prometheus-config-volume
          configMap:
            defaultMode: 420
            name: prometheus-server-conf
        - name: prometheus-storage-volume
          persistentVolumeClaim:
            claimName: azurefile
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: prometheus
  name: prometheus
spec:
  type: LoadBalancer
  loadBalancerIP: ...
  ports:
    - port: 80
      protocol: TCP
      targetPort: 9090
  selector:
    app: prometheus

Application deployment yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: api-app
  template:
    metadata:
      labels:
        app: api-app
    spec:
      containers:
      - name: nginx
        image: nginx
        lifecycle:
          preStop:
            exec:
              command: ["/usr/sbin/nginx","-s","quit"]
        ports:
          - containerPort: 80
            protocol: TCP
        resources:
          limits:
            cpu: 50m
            memory: 100Mi
          requests:
            cpu: 10m
            memory: 50Mi
        volumeMounts:
          - name: app-api
            mountPath: /var/run/app
          - name: nginx-conf
            mountPath: /etc/nginx/conf.d
      - name: api-app
        image: azurecr.io/app_api_se:opencv
        workingDir: /app
        command: ["/usr/local/bin/uwsgi"]
        args:
          - "--die-on-term"
          - "--manage-script-name"
          - "--mount=/=api:app_dispatch"
          - "--socket=/var/run/app/uwsgi.sock"
          - "--chmod-socket=777"
          - "--pyargv=se"
          - "--metrics-dir=/storage"
          - "--metrics-dir-restore"
        resources:
          requests:
            cpu: 150m
            memory: 1Gi
        volumeMounts:
          - name: app-api
            mountPath: /var/run/app
          - name: storage
            mountPath: /storage
      volumes:
        - name: app-api
          emptyDir: {}
        - name: storage
          persistentVolumeClaim:
            claimName: app-storage
        - name: nginx-conf
          configMap:
            name: app
      tolerations:
      - key: "sku"
        operator: "Equal"
        value: "test"
        effect: "NoSchedule"
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: api-app
  name: api-app
spec:
  ports:
    - port: 80
      protocol: TCP
      targetPort: 80
  selector:
    app: api-app


问:
notification small icon color not the color I set
I'm build a notification, setSmallIcon(icon is use white image) and setColor, but I found the color on the phone is not the color i set, the color on the phone is doesn't change, if change red to yellow is ok, but change color value in one type color eg:lightblue darkblue is doesn't change. And if i set color red, the color on the phone is more dark than i set color.
I don't know how to cause this, in virtual phone & sumsung also.

need your help. thx

```<code>NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.ic_app_notification)
                    .setColor(ContextCompat.getColor(this, R.color.notification_icon_color)).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_app_login))
                    .setContentTitle(title)
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);
</code>```

in manifest set color too

```<code>android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/notification_icon_color"
</code>```

I set color #63B9C7
but on the phone is not #63B9C7

答:
When building the notification, you can set the color and the icon. If your icon is a pure white image, it'll apply the color for you in the correct spots.

I had this problem too and I found that the problem is with graphical icon. You can solve the problem by using this online tool. open this link:

choose your image ( with large dimension ), download the resource and copy them to your project.

and finally set the notification icon using .setSmallIcon(R.drawable.ICON_NEW_NAME)

hope this helps

Edit

just a reminder why color may look different on screen , check this link

Body:
I'm build a notification, setSmallIcon(icon is use white image) and setColor, but I found the color on the phone is not the color i set, the color on the phone is doesn't change, if change red to yellow is ok, but change color value in one type color eg:lightblue darkblue is doesn't change. And if i set color red, the color on the phone is more dark than i set color.
I don't know how to cause this, in virtual phone & sumsung also.

need your help. thx

NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.ic_app_notification)
                    .setColor(ContextCompat.getColor(this, R.color.notification_icon_color)).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_app_login))
                    .setContentTitle(title)
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

in manifest set color too

android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/notification_icon_color"

I set color #63B9C7
but on the phone is not #63B9C7


Title: Is there anyway to reset multi index in pandas?

Body:
A possible solution to your problem might be:

from pandas_datareader import data as pdr
data = pdr.get_data_yahoo(['MSFT'], start='2019-01-01', end='2019-05-30')
data.columns = data.columns.levels[0]
data['symbol'] = 'MSFT'
data.head()

Attributes  High    Low Open    Close   Volume  Adj Close   symbol
Date
2019-01-02  101.750000  98.940002   99.550003   101.120003  35329300.0  100.318642  MSFT
2019-01-03  100.190002  97.199997   100.099998  97.400002   42523600.0  96.628120   MSFT
2019-01-04  102.510002  98.930000   99.720001   101.930000  44060600.0  101.122223  MSFT
2019-01-07  103.269997  100.980003  101.639999  102.059998  35656100.0  101.251190  MSFT
2019-01-08  103.970001  101.709999  103.040001  102.800003  31514400.0  101.985329  MSFT


问:
How to fix "value used in formula is wrong data type" error when trying to convert a range into an array?
I'm making a udf to convert the entered range into an array, and if done successfully, the function will return "worked" into the cell. However, it keeps returning #VALUE!, and says:

"a value used in the formula is of the wrong data type."

```<code>Function test(rng As Range) As String

Dim Arr() As Variant
Arr = Range(rng)

test="worked"

End Function
</code>```

答:
Was typing this as a comment, but will put as an answer due to content.  Note that @DisplayName gave the appropriate answer to resolve your issue.

In your code you use 'Range()` with inappropriate syntax.  Here are some examples of appropriate range references:

```<code>Sheets("Name).Range("A1")  'Uses cell A1 on sheets Name
Sheets("Name").Cells(1,1)  'Just like the above, calls cell A1

i = 1
Sheets("Name).Range("A" & i)  'Ampersand joins the variable i (typically used to iterate through a loop) with the column "A"

Sheets("Name").Range("Cat")  'Uses a named range, where cat is predefined and is on sheets Name

With Sheets("Name")
    Set rng = .Range(.Cells(1,1),.Cells(2,2)) 'Creates a range from A1 to B2... note the dots to make them use the appropriate sheet
End With
rng.value = "Cat"  'Each cell in the range will have "Cat" input
</code>```

Body:
I'm making a udf to convert the entered range into an array, and if done successfully, the function will return "worked" into the cell. However, it keeps returning #VALUE!, and says:

"a value used in the formula is of the wrong data type."

Function test(rng As Range) As String

Dim Arr() As Variant
Arr = Range(rng)

test="worked"

End Function

Body:
Was typing this as a comment, but will put as an answer due to content.  Note that @DisplayName gave the appropriate answer to resolve your issue.

In your code you use 'Range()` with inappropriate syntax.  Here are some examples of appropriate range references:

Sheets("Name).Range("A1")  'Uses cell A1 on sheets Name
Sheets("Name").Cells(1,1)  'Just like the above, calls cell A1

i = 1
Sheets("Name).Range("A" & i)  'Ampersand joins the variable i (typically used to iterate through a loop) with the column "A"

Sheets("Name").Range("Cat")  'Uses a named range, where cat is predefined and is on sheets Name

With Sheets("Name")
    Set rng = .Range(.Cells(1,1),.Cells(2,2)) 'Creates a range from A1 to B2... note the dots to make them use the appropriate sheet
End With
rng.value = "Cat"  'Each cell in the range will have "Cat" input


问:
How to deal with duplicate elements in the list in Haskell

Possible Duplicate:

  Searching through list

I need to write a function 'once' which, given a list of Integers and an Integer n, returns a Boolean indicating whether n occurs exactly once in the list. E.g.

```<code>Main>  once [2,3,2,4] 2
False
Main> once [1..100] 2
True
</code>```

And here is my current code:

```<code>once :: Int -> [Int] -> Bool
once x [] = False
once x (y:ys) = (x==y) || (once x ys)
</code>```

It checks only whether x is part of the list, but it cannot tell x appeared more than once in the list and therefore return false.
Need help with this, thanks!

答:
Try this:

write a function once, that scans the list until it finds the element for the first time or the end of the list. In the latter case it returns False, else it calls once'on the rest of the list and returns the result.

once' does essentially the same as once, but returns False, if the element is found and True, if not.

Body:
Possible Duplicate:

  Searching through list

I need to write a function 'once' which, given a list of Integers and an Integer n, returns a Boolean indicating whether n occurs exactly once in the list. E.g.

Main>  once [2,3,2,4] 2
False
Main> once [1..100] 2
True

And here is my current code:

once :: Int -> [Int] -> Bool
once x [] = False
once x (y:ys) = (x==y) || (once x ys)

It checks only whether x is part of the list, but it cannot tell x appeared more than once in the list and therefore return false.
Need help with this, thanks!


问:
Issue after deleting and adding platform on ionic
I have an app developed in ionic 3, and I was resolving a problem with apple store connect.The solution I found was remove ios platform by the project, add it again and then reinstall the camera plugin. After I made it, I can't build the app on terminal to deploy it on a device or on the simulator.

My Ionic and Cordova Info

Ionic:

```<code>   ionic (Ionic CLI)  : 4.2.1 (/usr/local/lib/node_modules/ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.1.9
</code>```

Cordova:

```<code>   cordova (Cordova CLI) : 8.0.0
   Cordova Platforms     : android 6.4.0, ios 4.5.5
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 1.2.1, (and 13 other plugins)
</code>```

The commands I've used: ionic cordova platform rm ios, ionic cordova platform add ios, ionic plugin remove camera-plugin, ionic plugin add camera-plugin.

I've already tried uncheck and check the "Automatically manage signing" on Xcode, and is still not working with the same issue.

答: After I re-added the ios platform, ionic has been created another xcode file project in platforms/ios/. So I opened this new project and unchecked and checked again the option "Automatically manage signing", at the General option menu.</p>

Body:
I have an app developed in ionic 3, and I was resolving a problem with apple store connect.The solution I found was remove ios platform by the project, add it again and then reinstall the camera plugin. After I made it, I can't build the app on terminal to deploy it on a device or on the simulator.

My Ionic and Cordova Info

Ionic:

   ionic (Ionic CLI)  : 4.2.1 (/usr/local/lib/node_modules/ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.1.9

Cordova:

   cordova (Cordova CLI) : 8.0.0
   Cordova Platforms     : android 6.4.0, ios 4.5.5
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 1.2.1, (and 13 other plugins)

The commands I've used: ionic cordova platform rm ios, ionic cordova platform add ios, ionic plugin remove camera-plugin, ionic plugin add camera-plugin.

I've already tried uncheck and check the "Automatically manage signing" on Xcode, and is still not working with the same issue.


问:
Displaying the content of an xml collection with XQuery
I have to use an xml database (Sedna) to store and retrieve Java objects. Every custom class in the project is stored into a collection. I have the following problem : I'm not sure how the objects are written into the collection. That is to say, I don't know their exact xml structure, so I can't do a proper query on them.

Is there a query that, for a given collection, will show me the content of a collection?

```<code>Host h = new Host();
h.name = "test1";
h.freeSpace = 32;
String id1 = this.addHost(h);

//addHost method
try
{
  Collection c = this.findCollection("Hosts"); //gives me the Hosts collection
  if (c == null)
    return null;

  h.id = c.createId();
  BinaryResource br = (BinaryResource) c.createResource(h.id, BinaryResource.RESOURCE_TYPE);
  br.setContent(h);
  c.storeResource(br);
  return h.id;

} catch (XMLDBException e) {
  System.err.println("Error adding Host entry into the database: " + e.getMessage());
  return null;
}
</code>```

答:
To view structure (schema) of your database or collection or document query one of the following system documents (Retrieving Metadata):

$schema – descriptive schema
of all documents and collections with
some schema-related information;

$schema_<name> – the
descriptive schema of the document or
collection named ;

For example, run se_term, and execute doc('$schema_test') to get structure of the 'test' document/collection.

How do you store your resources? Please give us snippet of code. It's very hard to understand even which one API do you use (XML:DB, XQJ, native Sedna Java API).

Body:
I have to use an xml database (Sedna) to store and retrieve Java objects. Every custom class in the project is stored into a collection. I have the following problem : I'm not sure how the objects are written into the collection. That is to say, I don't know their exact xml structure, so I can't do a proper query on them.

Is there a query that, for a given collection, will show me the content of a collection?

Host h = new Host();
h.name = "test1";
h.freeSpace = 32;
String id1 = this.addHost(h);

//addHost method
try
{
  Collection c = this.findCollection("Hosts"); //gives me the Hosts collection
  if (c == null)
    return null;

  h.id = c.createId();
  BinaryResource br = (BinaryResource) c.createResource(h.id, BinaryResource.RESOURCE_TYPE);
  br.setContent(h);
  c.storeResource(br);
  return h.id;

} catch (XMLDBException e) {
  System.err.println("Error adding Host entry into the database: " + e.getMessage());
  return null;
}


答:
It does not really matter if there are two copies of the identical data.frame. But to be honest I do not see any point to assign the data.frame twice.

You can use the pryr package to see how much memory an object allocates.

```<code>library(pryr)

df <- do.call(data.frame, replicate(8000, rep(FALSE, 8000), simplify=FALSE))

assign("dname_out", df, envir = globalenv())

mem_used()
337 MB

mem_change(df <- get("dname_out", envir = globalenv()))

736 B

> mem_used()
337 MB
</code>```

The change in memory is only 736 Bytes, so actually you can not crash your pc with creating tons of copies.

Title: Avoiding copying large objects in R - does get() function make copy?

Body:
I have an inherited some R code that uses an idiom to avoid copying of large data frames. When a function that builds the data frame finishes, it does not return the data frame, but instead stores it in the global environment context:

assign(df_name, df, envir = globalenv())

After the function finishes, the calling code retrieves the data frame with this:

df <- get(df_name, envir = globalenv())

My question is this: does the get() function itself actually make a copy when it returns a value, thus creating the very copy that this idiom was meant to avoid? If so, is there a better way of doing this?

Body:
It does not really matter if there are two copies of the identical data.frame. But to be honest I do not see any point to assign the data.frame twice.

You can use the pryr package to see how much memory an object allocates.

library(pryr)

df <- do.call(data.frame, replicate(8000, rep(FALSE, 8000), simplify=FALSE))

assign("dname_out", df, envir = globalenv())

mem_used()
337 MB

mem_change(df <- get("dname_out", envir = globalenv()))

736 B

> mem_used()
337 MB

The change in memory is only 736 Bytes, so actually you can not crash your pc with creating tons of copies.


问:
Best way to initialize Java constants based on environment
I would like to initialize a set of variables, which ideally would be final constants, based on my development environment.

That is, if my app is set to point to my development env, then var=x, but if my environment is set to production, then my var=y.

I am not a fan of a single constants class with globals which can easily be sufficient for this.  I like the concept of storing my constants in interfaces but am struggling with the best pattern where the variable value changes based on the environment.

答: You can use a Factory pattern to achieve this. You can call as EnvironmentFactory and based upon environment, you can set the value. To correlate, I provide the example of Person, a person can be male and person can be female based upon the gender. It means sex is a variable which you want store based upon gender. There may be many suitable patterns, based upon your situation, I suggest for Factory Pattern.


问:
Is it possible to register the rest endpoints in MarkLogic Query console
Is it possible to register the rest endpoints in MarkLogic Query Console using XQuery?</p>

答:
In Query Console, you can use the xdmp.http*() functions to call the REST API endpoints on the same server.

Hoping that helps,


问:
Using an API key in Amazon API Gateway
I have created an API Key and added it to my functions. I have then deployed the api and tested it but still get:

```<code>"message": "Forbidden"
</code>```

How do I pass the api key with my JSON request as I have been using "x-api-key": "theKey"?

答:
For Private API Gateways accessed through public DNS, we need to pass additional header of 'x-apigw-api-id' with the api id along with 'x-api-key' if configured.

curl -v https://{vpce-id}.execute-api.{region}.vpce.amazonaws.com/test -H 'x-apigw-api-id:{api-id}'

Its documented below,

https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-api-test-invoke-url.html#w20aac13c16c28c11

Title: Using an API key in Amazon API Gateway

Body:
I have created an API Key and added it to my functions. I have then deployed the api and tested it but still get:

"message": "Forbidden"

How do I pass the api key with my JSON request as I have been using "x-api-key": "theKey"?


问:
Css grid: horizontal two colums, but vertical flip
I use

```<code>gridTemplateColumns: `repeat(auto-fill, minmax(250px, 1fr))`,
</code>```

to get two columns, if their width less than 250px, I get layout:

```<code>[1] [2]
</code>```

And if the width is less than 250, I get layout:

```<code>[1]
[2]
</code>```

I wonder if it is possible to have vertical layout flipped:

```<code>[2]
[1]
</code>```

while keeping horizontal as described first [1] [2].

答:
For this particular case where there are only two grid items, you can hack it by mirroring the vertical direction in the grid container and inverting the mirror effect in the grid items - see demo below:

.wrapper {
 display: grid;
 grid-auto-rows: 100px; /* set a row height for illustration */
 grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
 transform: scaleY(-1); /* mirror vertically */
}

.wrapper > div {
  background: aliceblue;
  border: 1px solid cadetblue;
  display: flex;
  align-items: center;
  justify-content: center;
  transform: scaleY(-1); /* straighten the grid item */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div>1</div>
  <div>2</div>
</div></code>```

Body:
I use

gridTemplateColumns: `repeat(auto-fill, minmax(250px, 1fr))`,

to get two columns, if their width less than 250px, I get layout:

[1] [2]

And if the width is less than 250, I get layout:

[1]
[2]

I wonder if it is possible to have vertical layout flipped:

[2]
[1]

while keeping horizontal as described first [1] [2].

Body:
For this particular case where there are only two grid items, you can hack it by mirroring the vertical direction in the grid container and inverting the mirror effect in the grid items - see demo below:

.wrapper {
 display: grid;
 grid-auto-rows: 100px; /* set a row height for illustration */
 grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
 transform: scaleY(-1); /* mirror vertically */
}

.wrapper > div {
  background: aliceblue;
  border: 1px solid cadetblue;
  display: flex;
  align-items: center;
  justify-content: center;
  transform: scaleY(-1); /* straighten the grid item */
}

<div class="wrapper">
  <div>1</div>
  <div>2</div>
</div>


问:
Controls Moving problem in Perl Win32::GUI
In Perl Win32::GUI desktop apps,
While checkbox checked status I need to hide some controls and I need to move the controls to places which are hidden, for window compact view in Perl Win32::GUI. While using below code the control's images are repeated(duplicates) at the time of Controls movement. Kindly please give solution to avoid duplicate images of controls while moving and resizing the window.</p>

```<code>sub Check_Status{
  if($btwdates->GetCheck eq 1){
    $Pushlistmodelabel->Move(30,168);
    $Fromdatelabel->Show();
    $get_From_day->Show();
    $Todatelabel->Show();
    $get_To_day->Show();
    $FoldersOption->Disable();

    $PushListButton->Move(200,255);
    $processlabel->Move(2,285);

    $PushListButton->Move(135,295);
    $processlabel->Move(2,320);

    $Selectionlabel->Move(195,168);
    $FilesOption->Move(200,195);
    $FoldersOption->Move(200,225);

    $With_root->Move(35,195);
    $Without_root->Move(35,225);
    $changeOption->Move(35,255);
    $replacepath->Move(180,255);
    Win32::GUI::DoEvents() >= 0;

  }
  else{
    $FoldersOption->Move(200,165);
    $FilesOption->Move(200,135);
    $FoldersOption->Enable();
    $Selectionlabel->Move(195,108);
    $Pushlistmodelabel->Move(30,108);

    $Fromdatelabel->Hide();
    $get_From_day->Hide();
    $Todatelabel->Hide();
    $get_To_day->Hide();

    $PushListButton->Move(200,195);
    $processlabel->Move(2,225);
    $Pushlistmodelabel->Move(30,108);
    $With_root->Move(35,135);
    $Without_root->Move(35,165);
    $changeOption->Move(35,195);
    $replacepath->Move(180,195);

  }
}
</code>```

答:
Taking a shot in the dark (I don't have a win32 perl install), you could try the SetRedraw method. SetRedraw(0) before rearranging the controls and SetRedraw(1) afterwards. Maybe also a manual Redraw() afterwards.

There is a non-perl-specific discussion of some techniques for avoiding flicker when updating a window in the question Win32 GUI flickering on resize.

Body:
In Perl Win32::GUI desktop apps,
While checkbox checked status I need to hide some controls and I need to move the controls to places which are hidden, for window compact view in Perl Win32::GUI. While using below code the control's images are repeated(duplicates) at the time of Controls movement. Kindly please give solution to avoid duplicate images of controls while moving and resizing the window.

sub Check_Status{
  if($btwdates->GetCheck eq 1){
    $Pushlistmodelabel->Move(30,168);
    $Fromdatelabel->Show();
    $get_From_day->Show();
    $Todatelabel->Show();
    $get_To_day->Show();
    $FoldersOption->Disable();

    $PushListButton->Move(200,255);
    $processlabel->Move(2,285);

    $PushListButton->Move(135,295);
    $processlabel->Move(2,320);

    $Selectionlabel->Move(195,168);
    $FilesOption->Move(200,195);
    $FoldersOption->Move(200,225);

    $With_root->Move(35,195);
    $Without_root->Move(35,225);
    $changeOption->Move(35,255);
    $replacepath->Move(180,255);
    Win32::GUI::DoEvents() >= 0;

  }
  else{
    $FoldersOption->Move(200,165);
    $FilesOption->Move(200,135);
    $FoldersOption->Enable();
    $Selectionlabel->Move(195,108);
    $Pushlistmodelabel->Move(30,108);

    $Fromdatelabel->Hide();
    $get_From_day->Hide();
    $Todatelabel->Hide();
    $get_To_day->Hide();

    $PushListButton->Move(200,195);
    $processlabel->Move(2,225);
    $Pushlistmodelabel->Move(30,108);
    $With_root->Move(35,135);
    $Without_root->Move(35,165);
    $changeOption->Move(35,195);
    $replacepath->Move(180,195);

  }
}


问:
It doesn't increment the position
I have the following code, i want to move a box my pressing arrow(left arrow in this case) but is adding only once to left property. If i press multiple times on the left arrow it remains on the same spot. Can't figure why..</p>

```<code>const box = document.querySelector('div');
const body = document.querySelector('body');

body.addEventListener('keydown', move);

function move(event) {
    let ddd = event.which || event.keyCode;
    let left = 0;
    box.style.position = 'absolute';
    if(ddd === 37) {
        left += 5;
        box.style.left = left + 'px';
    }
}
</code>```

答:
That's because you're resetting the value of left every time. Store left outside of move to prevent resetting it.

```<code>const box = document.querySelector('div');
const body = document.querySelector('body');
let left = 0;

body.addEventListener('keydown', move);

function move(event) {
    let ddd = event.which || event.keyCode;
    box.style.position = 'absolute';
    if(ddd === 37) {
        left += 5;
        box.style.left = left + 'px';
    }
}
</code>```

Title: It doesn't increment the position

Body:
I have the following code, i want to move a box my pressing arrow(left arrow in this case) but is adding only once to left property. If i press multiple times on the left arrow it remains on the same spot. Can't figure why..

const box = document.querySelector('div');
const body = document.querySelector('body');

body.addEventListener('keydown', move);

function move(event) {
    let ddd = event.which || event.keyCode;
    let left = 0;
    box.style.position = 'absolute';
    if(ddd === 37) {
        left += 5;
        box.style.left = left + 'px';
    }
}

Body:
That's because you're resetting the value of left every time. Store left outside of move to prevent resetting it.

const box = document.querySelector('div');
const body = document.querySelector('body');
let left = 0;

body.addEventListener('keydown', move);

function move(event) {
    let ddd = event.which || event.keyCode;
    box.style.position = 'absolute';
    if(ddd === 37) {
        left += 5;
        box.style.left = left + 'px';
    }
}


问:
Text in front and image at background at back inside the specific div
I'm trying to create a div where it has front text and background image.

So far, here's my basic html

Hello World

```

Here is what the result I get.

But I want something like this from Microsoft word.

I hope somebody helps me. Thank you in advance

答:
Here is a way to do it with position: absolute

.image-container {
  position: relative;
  display: inline-block;
}

.image-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-container">
  <img src="https://placekitten.com/600/400" alt="">
  <div class="image-text">Centered text</div>
</div></code>```

JSFiddle Demo

Body:
I'm trying to create a div where it has front text and background image.

So far, here's my basic html

Hello World

Here is what the result I get.

But I want something like this from Microsoft word.

I hope somebody helps me. Thank you in advance

Body:
Here is a way to do it with position: absolute

.image-container {
  position: relative;
  display: inline-block;
}

.image-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 30px;
}

<div class="image-container">
  <img src="https://placekitten.com/600/400" alt="">
  <div class="image-text">Centered text</div>
</div>

JSFiddle Demo


问:
Why does MS SQL allow you to create an illegal column?
I recently saw a tweet stating that you could prevent other developers from reading from a table using the SELECT * FROM TableName by building your table in the following way:

```<code>CREATE TABLE [TableName]
(
   [ID] INT IDENTITY NOT NULL,
   [Name] VARCHAR(50) NOT NULL,
   [DontUseStar] AS (1 / 0)
);
</code>```

It's easy to see that using the SELECT * here would try to read the blank column name as 1 divided by 0 (thus causing a divide by zero error), but without a datatype assigned to the column.

Why does SQL allow you to create a column with no assigned data type, with a name it knows will be illegal?

答: I think it's a greate way to create a table which allows no rows to be selected select * from . Why one may need such a table?  Who knows, probably to wire a INSTEAD OF trigger to it or something.  Any programming language will allow the code like x=1/0, it's not a compiler business to decide why one needs it.

Body:
I recently saw a tweet stating that you could prevent other developers from reading from a table using the SELECT * FROM TableName by building your table in the following way:

CREATE TABLE [TableName]
(
   [ID] INT IDENTITY NOT NULL,
   [Name] VARCHAR(50) NOT NULL,
   [DontUseStar] AS (1 / 0)
);

It's easy to see that using the SELECT * here would try to read the blank column name as 1 divided by 0 (thus causing a divide by zero error), but without a datatype assigned to the column.

Why does SQL allow you to create a column with no assigned data type, with a name it knows will be illegal?


问:
Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. (Migrations)
I have a project with this structure

TooSeeWeb.Infrastructure is for migrations.

When I try to run migrations with this command

```<code>dotnet ef migrations add ExampleMigration -s ..\TooSeeWeb
</code>```

I have this error

Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. If you're using custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option

How I can fix this?

答:
You have to point to your web project

```<code> dotnet ef --startup-project ../TooSeeWeb migrations add MigrationName -c NameOfYourDBContext
</code>```

More details about multi project you can find https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/projects

Body:
I have a project with this structure

TooSeeWeb.Infrastructure is for migrations.

When I try to run migrations with this command

dotnet ef migrations add ExampleMigration -s ..\TooSeeWeb

I have this error

Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. If you're using custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option

How I can fix this?

Body:
You have to point to your web project

 dotnet ef --startup-project ../TooSeeWeb migrations add MigrationName -c NameOfYourDBContext

More details about multi project you can find https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/projects


问:
Enzyme – test event handler function who needs an arbitrary `target` property
Disclaimer: I'm using Preact as a lib and enzyme-adapter-preact-pure as the Enzyme's adapter.

I wrote the following function:

```<code>function handleInputChange(e) {
  const target = e.target,
    value = target.type === 'checkbox' ? target.checked : target.value;
  this.setState({ [target.name]: value });
}
</code>```

This function is standalone and it's meant to be used inside React's
Component instances like that:

```<code>class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: null
    };

    this.handleInputChange = handleInputChange.bind(this);
  }

  render() {
    return <input name="name" onChange={this.handleInputChange} />;
  }
}
</code>```

This way I don't need to reimplement it on every component that needs to handle input changes.

The problem:

As I rely on event.target and it's properties, I don't know how to test it with Enzyme, because I can't set the target and those properties as I wish:

```<code>// Test file
// Consider `wrapper` as an instance of `App` shown above, mounted with Enzyme's `mount` function.

test('it changes the correspondent state key when input is changed', () => {
  wrapper.find('input').simulate('change', { target: { value: 'foo', name: 'name' } });
  expect(wrapper.state('name')).toEqual('foo');
});
</code>```

Trying this is throwing an error: TypeError: Cannot set property target of [object Event] which has only a getter at Function.assign (<anonymous>)

答:
Since you are relying on more than just target.value you also need to pass appropriate mock that covers all your bases.

Below code should resolve it.

```<code>wrapper.find('input').simulate('change', {
  target: {
    value: 'foo',
    name: 'name',
    checked: true,
    type: 'checkbox'
  }
});

// OR

// In this case there will be no checkbox found and this it wont look for checked value present or not
wrapper.find('input').simulate('change', {
  target: {
    value: 'foo',
    name: 'name'
  }
});
</code>```

Body:
Disclaimer: I'm using Preact as a lib and enzyme-adapter-preact-pure as the Enzyme's adapter.

I wrote the following function:

function handleInputChange(e) {
  const target = e.target,
    value = target.type === 'checkbox' ? target.checked : target.value;
  this.setState({ [target.name]: value });
}

This function is standalone and it's meant to be used inside React's
Component instances like that:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: null
    };

    this.handleInputChange = handleInputChange.bind(this);
  }

  render() {
    return <input name="name" onChange={this.handleInputChange} />;
  }
}

This way I don't need to reimplement it on every component that needs to handle input changes.

The problem:

As I rely on event.target and it's properties, I don't know how to test it with Enzyme, because I can't set the target and those properties as I wish:

// Test file
// Consider `wrapper` as an instance of `App` shown above, mounted with Enzyme's `mount` function.

test('it changes the correspondent state key when input is changed', () => {
  wrapper.find('input').simulate('change', { target: { value: 'foo', name: 'name' } });
  expect(wrapper.state('name')).toEqual('foo');
});

Trying this is throwing an error: TypeError: Cannot set property target of [object Event] which has only a getter at Function.assign (<anonymous>)

Body:
Since you are relying on more than just target.value you also need to pass appropriate mock that covers all your bases.

Below code should resolve it.

wrapper.find('input').simulate('change', {
  target: {
    value: 'foo',
    name: 'name',
    checked: true,
    type: 'checkbox'
  }
});

// OR

// In this case there will be no checkbox found and this it wont look for checked value present or not
wrapper.find('input').simulate('change', {
  target: {
    value: 'foo',
    name: 'name'
  }
});


问:
Allocation of temp directory inside tomcat installation base results in error due to read only property
I am moving a project from Eclipse to Intellij IDEA. I have already added the jars to the Project Structure -> Libraries and added them to the module as a dependency. The tomcat server is up and running so navigation of the web application is working correctly.

Unfortunately, when using the jar to create an excel file I get the error java.lang.RuntimeException: java.io.IOException: Could not create temporary directory 'C:\path_to_tomcat_installation\temp\poifiles\'

My Question is how/why is eclipse/tomcat able to use the poi to create a excel file without this error and Intellij IDEA cannot

答:
It turns out there are a lot of questions and answers on stackoverflow about changing the value of java.io.tmpdir.

Initially I set a windows system variable CATALINA_TMPDIR to c:/new/temp/dir, but as this is a system wide setting I ultimately decided to not use that method.

The simplest method and most direct was to use CrazyCoders suggestion.
Under Run -> Edit Configurations.
In the Server tab of the Tomcat Server, in the VM options box enter -Djava.io.tmpdir=c:/new/temp/dir


问:
C# creating a form for given size
I want to draw a rectangle on the screen. I guess the most appropriate way is use a form without boarder.

```<code>Form frm = new Form();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = new Point(GlobalPosX, GlobalPosY);
frm.Size = new Size(101, 30);
frm.BackColor = System.Drawing.Color.Yellow;
frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
frm.Show();
</code>```

The created from is not as the given size. It's size is similar to the window having boarder. The displayed window is bit larger as I given and the position is also moved little bit upper and left.
Is there another way to achieve my goal?

答:
Drawing C# graphics without using Windows Forms

That like talks about making a border-less window.  From there, just use the Graphics object to draw whatever you'd like

Title: C# creating a form for given size

Body:
I want to draw a rectangle on the screen. I guess the most appropriate way is use a form without boarder.

Form frm = new Form();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = new Point(GlobalPosX, GlobalPosY);
frm.Size = new Size(101, 30);
frm.BackColor = System.Drawing.Color.Yellow;
frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
frm.Show();

The created from is not as the given size. It's size is similar to the window having boarder. The displayed window is bit larger as I given and the position is also moved little bit upper and left.
Is there another way to achieve my goal?