问:
Which is preferred SELECT or SET
When assigning a variable, is there a functional difference between set and select?

I often write scripts that have to iterate through processes, and on each iteration I update a variable with a value.

For example, my company's product has multiple servers, on each server we have a certain number of databases that our clients data resides in. Each database has between 5 and 50 clients.  A table in a primary database indicates which of the individual databases each client is on. Today I found a problem with the primary key on one table, and we need to modify the primary key to add a column to it.  The table on each database may have several hundred thousand records, so we expect the updates to take some time.  We need to do these overnight to avoid performance issues.  So I've written the following script to iterate through the process on each database (I'll execute it separately on each server):

```<code>DECLARE @DBTABLE TABLE
(
    TableID                 INT IDENTITY PRIMARY KEY NOT NULL,
    DbName                  VARCHAR(50) NOT NULL,
    ServerName              VARCHAR(50) NOT NULL,
    ProcFlag                INT NOT NULL DEFAULT 0
)

INSERT INTO @DBTABLE (DbName, ServerName)
SELECT      DISTINCT DbName, ServerName
FROM        PrimaryDatabase.dbo.Cients WITH(NOLOCK)
WHERE       ClientInactive = 0
    AND     ServerName = @@SERVERNAME

DECLARE     @TABLETEST  INT
DECLARE     @TABLEID    INT
DECLARE     @DBNAME     VARCHAR(50)
DECLARE     @SERVERNAME VARCHAR(50)
DECLARE     @VAR_SQL    VARCHAR(MAX)

SET     @TABLETEST = (SELECT COUNT(*) FROM @DBTABLE WHERE ProcFlag = 0)
WHILE   @TABLETEST > 0
BEGIN
    SET     @TABLEID =      (SELECT MIN(TableID) FROM @DBTABLE WHERE ProcFlag = 0)
    SET     @DBNAME =       (SELECT DbName FROM @DBTABLE WHERE TableID = @TABLEID)
    SET     @SERVERNAME =   (SELECT ServerName FROM @DBTABLE WHERE TableID = @TABLEID)

    SET     @VAR_SQL = '

        ALTER TABLE ' + @DBNAME + '.dbo.ClientDealTable DROP CONSTRAINT [PK_ClientDealTable]
        ALTER TABLE ' + @DBNAME + '.dbo.ClientDealTable ADD CONSTRAINT [PK_ClientDealTable] PRIMARY KEY CLUSTERED ([ClientID] ASC, [DealNumber] ASC, [DealDate] ASC)
    '

    EXEC(@VAR_SQL)

    UPDATE      @DBTABLE SET ProcFlag = 1 WHERE TableID = @TABLEID
    SET         @TABLETEST = (SELECT COUNT(*) FROM @DBTABLE WHERE ProcFlag = 0)

END
</code>```

Is SET or SELECT the preferred option here, or does it really matter? Is there a performance difference?

答:
SET can only set the value of a single variable. using SELECT you can set the value of any number of variables.

But in your code I wouldn't use either. I would do this without looping. Not to mention there is a mountain less code to write. This should do the same thing and is a lot simpler.

```<code>DECLARE @VAR_SQL VARCHAR(MAX)

SELECT @VAR_SQL = 'ALTER TABLE ' + QUOTENAME(DbName) + '.dbo.ClientDealTable DROP CONSTRAINT [PK_ClientDealTable];ALTER TABLE ' + QUOTENAME(DbName) + '.dbo.ClientDealTable ADD CONSTRAINT [PK_ClientDealTable] PRIMARY KEY CLUSTERED ([ClientID] ASC, [DealNumber] ASC, [DealDate] ASC)'
FROM PrimaryDatabase.dbo.Cients --WITH(NOLOCK)
WHERE ClientInactive = 0
    AND ServerName = @@SERVERNAME

exec sp_executesql @VAR_SQL
</code>```

Title: Which is preferred SELECT or SET

Body:
When assigning a variable, is there a functional difference between set and select?

I often write scripts that have to iterate through processes, and on each iteration I update a variable with a value.

For example, my company's product has multiple servers, on each server we have a certain number of databases that our clients data resides in. Each database has between 5 and 50 clients.  A table in a primary database indicates which of the individual databases each client is on. Today I found a problem with the primary key on one table, and we need to modify the primary key to add a column to it.  The table on each database may have several hundred thousand records, so we expect the updates to take some time.  We need to do these overnight to avoid performance issues.  So I've written the following script to iterate through the process on each database (I'll execute it separately on each server):

DECLARE @DBTABLE TABLE
(
    TableID                 INT IDENTITY PRIMARY KEY NOT NULL,
    DbName                  VARCHAR(50) NOT NULL,
    ServerName              VARCHAR(50) NOT NULL,
    ProcFlag                INT NOT NULL DEFAULT 0
)

INSERT INTO @DBTABLE (DbName, ServerName)
SELECT      DISTINCT DbName, ServerName
FROM        PrimaryDatabase.dbo.Cients WITH(NOLOCK)
WHERE       ClientInactive = 0
    AND     ServerName = @@SERVERNAME

DECLARE     @TABLETEST  INT
DECLARE     @TABLEID    INT
DECLARE     @DBNAME     VARCHAR(50)
DECLARE     @SERVERNAME VARCHAR(50)
DECLARE     @VAR_SQL    VARCHAR(MAX)

SET     @TABLETEST = (SELECT COUNT(*) FROM @DBTABLE WHERE ProcFlag = 0)
WHILE   @TABLETEST > 0
BEGIN
    SET     @TABLEID =      (SELECT MIN(TableID) FROM @DBTABLE WHERE ProcFlag = 0)
    SET     @DBNAME =       (SELECT DbName FROM @DBTABLE WHERE TableID = @TABLEID)
    SET     @SERVERNAME =   (SELECT ServerName FROM @DBTABLE WHERE TableID = @TABLEID)

    SET     @VAR_SQL = '

        ALTER TABLE ' + @DBNAME + '.dbo.ClientDealTable DROP CONSTRAINT [PK_ClientDealTable]
        ALTER TABLE ' + @DBNAME + '.dbo.ClientDealTable ADD CONSTRAINT [PK_ClientDealTable] PRIMARY KEY CLUSTERED ([ClientID] ASC, [DealNumber] ASC, [DealDate] ASC)
    '

    EXEC(@VAR_SQL)

    UPDATE      @DBTABLE SET ProcFlag = 1 WHERE TableID = @TABLEID
    SET         @TABLETEST = (SELECT COUNT(*) FROM @DBTABLE WHERE ProcFlag = 0)

END

Is SET or SELECT the preferred option here, or does it really matter? Is there a performance difference?

Body:
SET can only set the value of a single variable. using SELECT you can set the value of any number of variables.

But in your code I wouldn't use either. I would do this without looping. Not to mention there is a mountain less code to write. This should do the same thing and is a lot simpler.

DECLARE @VAR_SQL VARCHAR(MAX)

SELECT @VAR_SQL = 'ALTER TABLE ' + QUOTENAME(DbName) + '.dbo.ClientDealTable DROP CONSTRAINT [PK_ClientDealTable];ALTER TABLE ' + QUOTENAME(DbName) + '.dbo.ClientDealTable ADD CONSTRAINT [PK_ClientDealTable] PRIMARY KEY CLUSTERED ([ClientID] ASC, [DealNumber] ASC, [DealDate] ASC)'
FROM PrimaryDatabase.dbo.Cients --WITH(NOLOCK)
WHERE ClientInactive = 0
    AND ServerName = @@SERVERNAME

exec sp_executesql @VAR_SQL


来源: stackexchange

问:
Execute Python code from within PyQt event loop
I am testing a gui built using PyQt and I would like the ability to interact with the gui using python code that is executed after the PyQt event loop starts (app.exec_()). Another way of saying this is I would like the call to app.exec_ to return immediately as if the gui were modeless, followed by further python code which interacts with the gui.

I found this example of running the PyQt loop in a thread but don't want to do something so unconventional. Is there any way to get the PyQt message loop to continue processing messages while also executing python code in the main thread after exec_ has been called?

答:
As a possible easy answer, try not calling app.exec_() in your script and running your PyQt program using python -i My_PyQt_app.py.

For example:

## My_PyQt_app.py
import sys
from PyQt5.QtWidgets import QApplication, QWidget

app = QApplication(sys.argv)

window = QWidget()
window.show()

# Don't start the event loop as you would do normally!
# app.exec_()
```

Doing this should allow you to run the GUI through the terminal and interact with it in the command line.

ContentLicense: CC BY-SA 4.0

Body:
As a possible easy answer, try not calling app.exec_() in your script and running your PyQt program using python -i My_PyQt_app.py.

For example:

## My_PyQt_app.py
import sys
from PyQt5.QtWidgets import QApplication, QWidget

app = QApplication(sys.argv)

window = QWidget()
window.show()

# Don't start the event loop as you would do normally!
# app.exec_()

Doing this should allow you to run the GUI through the terminal and interact with it in the command line.


问:
Store representations in SQL rather than whole strings?
I want to mark my users with one out of four static strings: indestructible, unstoppable, superefficient and megafantastic.

Would it be faster and more efficient to store a one char representation of the string rather than the whole string? Sort of like a key<->value mapping. The DB would only need to match one letter instead of a whole string when I do a search.

In the DB these words would only be represented as i,u,s and m. On the users profile I print indesctuctible if I get an i, unstoppable if I get a u etc.

Do I actually speed up anything by doing like this or is it just unnecessary work?

What if I have 10 more of these representations?

答:
I think it is a waste of time. Beware of micro-optimizations. For such a reduction you would loose all meaning in the database for that column, loose the flexibility to have values that start with same letter, have to modify your DAL to pass in just the first letter when given a whole word.

I would normally index the column and leave it as full strings. If that was the bottleneck in your system then your writing the fastest, most efficient programs in the world and you don't need my humble advice anyway ;-).

ContentLicense: CC BY-SA 3.0


问:
How do I check if a double is a multiple of another double in c#?
I am currently attempting:

```<code>if (4.750 % 0.125 == 0 )
</code>```

but it looks like c# doesn't want decimal for mod operation. How do I check if a number is a multiple of 0.125 then?

thanks!

答:
Comparing floats/doubles with zero is pretty dangerous, because of the floating-point precision. You can do two things:

multiply both numbers by 1000 (on example), then cast to int and do your comparison

or

compare like this:

if (Math.Abs(a % b) < 0.001)
```

Body:
I am currently attempting:

if (4.750 % 0.125 == 0 )

but it looks like c# doesn't want decimal for mod operation. How do I check if a number is a multiple of 0.125 then?

thanks!


问:
Can the Python .replace() function replace whole phrases?
I'm a video editor trying to automate word docs of talent scripts into STR files for captions to speed up the process. Since each video is structured the same, the idea works pretty well. In the scripts, there are editing directions that I'm trying to remove from the STR file I'm creating with Python and the python-docx library by using the .replace() function, however this doesn't seem to be working. These all begin with '(CUT' and the following possible sentences vary. The program correctly picks up where these sentences are occurring but the replace function yields no resulting change. What am I doing wrong here?</p>
```<code>for x in range(2,len(doc.paragraphs)):
newPara = doc.paragraphs[x].text

if (newPara.find('(CUT') != -1):
    newPara.replace('(CUT', '')

    if (newPara.find('COMPLETE)') != -1):
        newPara.replace(' AWAY COMPLETE)', '')

    elif (newPara.find('TITLE)') != -1):
        newPara.replace(' AWAY TO TITLE)', '')

    elif (newPara.find('SIDE)') != -1):
        newPara.replace(' BACK TO SIDE)', '')
</code>```

答:
As the guy above said, strings are immutable and the str.replace() function returns a new string.

But adding to your code.

You don't need all those conditionals, the if the str.replace() does not find the substring you're looking for it returns the same string.

Example:

```<code>newPara = '(CUT AWAY COMPLETE) AWAY TO TITLE) BACK TO SIDE)Empty String'

if (newPara.find('(CUT') != -1):
    newPara = newPara.replace('(CUT', '')
    newPara = newPara.replace(' AWAY COMPLETE)', '')
    newPara = newPara.replace(' AWAY TO TITLE)', '')
    newPara = newPara.replace(' BACK TO SIDE)', '')

print(newPara)
</code>```

prints: 'Empty String'

also:

```<code>if (newPara.find('(CUT') != -1):
    for substring in ['(CUT',' AWAY COMPLETE)',' AWAY TO TITLE)', ' BACK TO SIDE)']:
        newPara = newPara.replace(substring, '')
</code>```

Body:
I'm a video editor trying to automate word docs of talent scripts into STR files for captions to speed up the process. Since each video is structured the same, the idea works pretty well. In the scripts, there are editing directions that I'm trying to remove from the STR file I'm creating with Python and the python-docx library by using the .replace() function, however this doesn't seem to be working. These all begin with '(CUT' and the following possible sentences vary. The program correctly picks up where these sentences are occurring but the replace function yields no resulting change. What am I doing wrong here?

for x in range(2,len(doc.paragraphs)):
newPara = doc.paragraphs[x].text

if (newPara.find('(CUT') != -1):
    newPara.replace('(CUT', '')

    if (newPara.find('COMPLETE)') != -1):
        newPara.replace(' AWAY COMPLETE)', '')

    elif (newPara.find('TITLE)') != -1):
        newPara.replace(' AWAY TO TITLE)', '')

    elif (newPara.find('SIDE)') != -1):
        newPara.replace(' BACK TO SIDE)', '')

Body:
As the guy above said, strings are immutable and the str.replace() function returns a new string.

But adding to your code.

You don't need all those conditionals, the if the str.replace() does not find the substring you're looking for it returns the same string.

Example:

newPara = '(CUT AWAY COMPLETE) AWAY TO TITLE) BACK TO SIDE)Empty String'

if (newPara.find('(CUT') != -1):
    newPara = newPara.replace('(CUT', '')
    newPara = newPara.replace(' AWAY COMPLETE)', '')
    newPara = newPara.replace(' AWAY TO TITLE)', '')
    newPara = newPara.replace(' BACK TO SIDE)', '')

print(newPara)

prints: 'Empty String'

also:

if (newPara.find('(CUT') != -1):
    for substring in ['(CUT',' AWAY COMPLETE)',' AWAY TO TITLE)', ' BACK TO SIDE)']:
        newPara = newPara.replace(substring, '')


问:
Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type
I get this error in my SwiftUI View, see code below; I also get Cannot convert return expression of type 'List' to return type 'some View'.

```<code> struct RestaurantView: View {

    @State private var isSshowingMapActionSheet = false
    @State private var isShowingSafariView = false
    let restaurant: Restaurant!
    var currenstatus: String  {
        if restaurant.isOpen {
            return "Open"
        }
        return "Closed"
    }
    var mapActionSheetButtons: [ActionSheet.Button] = [
        .default("Open in Maps", action: {
            self.openInMaps()
        }),
        .default("Open in Google Maps", action: {
            self.openInGoogleMaps()
        }),
        .cancel(Text("Cancel"))
    ]
    lazy var mapActionSheet = ActionSheet(title: Text(""), buttons: mapActionSheetButtons)

    func openInMaps() {
        let placemark = MKPlacemark(coordinate: restaurant.location.coordinate, addressDictionary: [CNPostalAddressStreetKey as String: restaurant.address!])

        let mapItem = MKMapItem(placemark: placemark)
        mapItem.name = self.restaurant.name
        mapItem.phoneNumber = self.restaurant.phone

        let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]

        mapItem.openInMaps(launchOptions: launchOptions)
    }
    func openInGoogleMaps() {
        if let url = URL(string: "comgooglemapsurl://maps.google.com/?q=\(restaurant.name.URLEncoded)@\(restaurant.location.coordinate.latitude),\(restaurant.location.coordinate.longitude)") {
            UIApplication.shared.open(url, options: [:])
        }
    }

    var body: some View {
        List {
            ListRow("ClockGlyph", action: {

            }, label: {
                OpenHoursView(restaurant)
            })

        ListRow("PhoneGlyph", action: {
            UIApplication.shared.op
        }, label: {
            Text(self.restaurant!.phone)
        })

        if (restaurant.homepage != nil) {
            return ListRow("SafariGlyph", action: {
                isShowingSafariView.toggle()
            }, label:  {
                Text(restaurant.homepage)
            }
        }

        ListRow("PhoneGlyph", action: {
            UIApplication.shared.canOpenURL(self.restaurant.phoneURL)
        }, label: {
            Text(self.restaurant.phone)
        })

            if restaurant!.facebookURL != nil {
                ListRow("FacebookGlyph", action: {
                }, label: {
                    Text(self.restaurant.facebookURL!)
                })
            }

        ListRow("PinGlyph", action: {
            self..isSshowingMapActionSheet.toggle()
        }, label: {
            VStack {
                Text(restaurant!.address!.replacingOccurrences(of: "\n", with: ", "))
                Text("Visa vägbeskrivning")
                    .font(.subheadline)
                    .foregroundColor(.gray)
            }

        })

        .actionSheet(isPresented: $isSshowingMapActionSheet, content: {
                mapActionSheet
            })
        .sheet(item: $isShowingSafariView, content: {
                SafariView(url: restaurant.homepageURL)

            })
    }

}
</code>```

And here's my ListRow class:

```<code>struct ListRow<Label> : View where Label : View {
    let image: Image
    var action:(() -> ())
    let label: () -> Label

    init(_ image: Image, action: @escaping () -> Void, @ViewBuilder label: @escaping () -> Label) {
        self.image = image
        self.action = action
        self.label = label
    }
    var body: some View {
        Button(action: self.action) {
            HStack(spacing: 10) {
                image.resizable().frame(width: 20, height: 20)
                self.label().font(.subheadline)
            }
        }
    }
}
</code>```

答:
There a few typos that cause the compiling to fail.

With SwiftUI you can get Xcode errors that are not very helpful, you should try commenting out different lines until it gives you are more informative error. With the new beta Xcode 11.4 it should be better.

In general, try building smaller views, break them out into separate structs more so that it's easier to spot typos, it will also help the compiler.

Body:
I get this error in my SwiftUI View, see code below; I also get Cannot convert return expression of type 'List' to return type 'some View'.

 struct RestaurantView: View {

    @State private var isSshowingMapActionSheet = false
    @State private var isShowingSafariView = false
    let restaurant: Restaurant!
    var currenstatus: String  {
        if restaurant.isOpen {
            return "Open"
        }
        return "Closed"
    }
    var mapActionSheetButtons: [ActionSheet.Button] = [
        .default("Open in Maps", action: {
            self.openInMaps()
        }),
        .default("Open in Google Maps", action: {
            self.openInGoogleMaps()
        }),
        .cancel(Text("Cancel"))
    ]
    lazy var mapActionSheet = ActionSheet(title: Text(""), buttons: mapActionSheetButtons)

    func openInMaps() {
        let placemark = MKPlacemark(coordinate: restaurant.location.coordinate, addressDictionary: [CNPostalAddressStreetKey as String: restaurant.address!])

        let mapItem = MKMapItem(placemark: placemark)
        mapItem.name = self.restaurant.name
        mapItem.phoneNumber = self.restaurant.phone

        let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]

        mapItem.openInMaps(launchOptions: launchOptions)
    }
    func openInGoogleMaps() {
        if let url = URL(string: "comgooglemapsurl://maps.google.com/?q=\(restaurant.name.URLEncoded)@\(restaurant.location.coordinate.latitude),\(restaurant.location.coordinate.longitude)") {
            UIApplication.shared.open(url, options: [:])
        }
    }

    var body: some View {
        List {
            ListRow("ClockGlyph", action: {

            }, label: {
                OpenHoursView(restaurant)
            })

        ListRow("PhoneGlyph", action: {
            UIApplication.shared.op
        }, label: {
            Text(self.restaurant!.phone)
        })

        if (restaurant.homepage != nil) {
            return ListRow("SafariGlyph", action: {
                isShowingSafariView.toggle()
            }, label:  {
                Text(restaurant.homepage)
            }
        }

        ListRow("PhoneGlyph", action: {
            UIApplication.shared.canOpenURL(self.restaurant.phoneURL)
        }, label: {
            Text(self.restaurant.phone)
        })

            if restaurant!.facebookURL != nil {
                ListRow("FacebookGlyph", action: {
                }, label: {
                    Text(self.restaurant.facebookURL!)
                })
            }

        ListRow("PinGlyph", action: {
            self..isSshowingMapActionSheet.toggle()
        }, label: {
            VStack {
                Text(restaurant!.address!.replacingOccurrences(of: "\n", with: ", "))
                Text("Visa vägbeskrivning")
                    .font(.subheadline)
                    .foregroundColor(.gray)
            }

        })

        .actionSheet(isPresented: $isSshowingMapActionSheet, content: {
                mapActionSheet
            })
        .sheet(item: $isShowingSafariView, content: {
                SafariView(url: restaurant.homepageURL)

            })
    }

}

And here's my ListRow class:

struct ListRow : View where Label : View {
    let image: Image
    var action:(() -> ())
    let label: () -> Label

    init(_ image: Image, action: @escaping () -> Void, @ViewBuilder label: @escaping () -> Label) {
        self.image = image
        self.action = action
        self.label = label
    }
    var body: some View {
        Button(action: self.action) {
            HStack(spacing: 10) {
                image.resizable().frame(width: 20, height: 20)
                self.label().font(.subheadline)
            }
        }
    }
}


问:
std::future<>::get empties the result
I have a threaded function that would return the external IP, and thought I could use it with std::future:

```<code>std::future<std::string> GetIP4;
GetIP4 = std::async([]() -> std::string
    {
        return GetWanIP();
    });
</code>```

When later in the code I call GetIP4.get(), I get a std::string. However this empties the object, so the next time I try to call get from another thread it crashes.

Is this the intended behaviour of std::future<>::get()? Is it a scenario "I have it only once"? I didn't find anything in the documentation.

答:
From cppreference on std::future<T>::get :

Any shared state is released. valid() is false after a call to this method.

And just before mentions that

The behavior is undefined if valid() is false before the call to this function.

Since valid() must be true to call get() and get() causes valid() to become false, then it isn't possible to get() the same future result more than once.

Title: std::future<>::get empties the result

Body:
I have a threaded function that would return the external IP, and thought I could use it with std::future:

std::future<std::string> GetIP4;
GetIP4 = std::async([]() -> std::string
    {
        return GetWanIP();
    });

When later in the code I call GetIP4.get(), I get a std::string. However this empties the object, so the next time I try to call get from another thread it crashes.

Is this the intended behaviour of std::future<>::get()? Is it a scenario "I have it only once"? I didn't find anything in the documentation.


问:
Conditional Formatting based on Cell Text
I have the data in the columns ABCD in one sheet and a pivot based on that data on another. I want to conditional format my pivot table values based on the value of the Color column in my data sheet using VBA.

What is the Rule that I will need to create here? I recall we can use Name Manager for this purpose, but I am not sure how to?

答:
Use a VLOOKUP and create 3 rules with the following formulas:

```<code>=VLOOKUP(G$2,$A:$D,4)="red"

=VLOOKUP(G$2,$A:$D,4)="yellow"

=VLOOKUP(G$2,$A:$D,4)="green"
</code>```

And match each condition with the appropriate colour

Body:
Use a VLOOKUP and create 3 rules with the following formulas:

=VLOOKUP(G$2,$A:$D,4)="red"

=VLOOKUP(G$2,$A:$D,4)="yellow"

=VLOOKUP(G$2,$A:$D,4)="green"

And match each condition with the appropriate colour


问:
Custom Component in android
I have created custom component with a Button Bar on the Bottom of
the screen and a Title and status bar on the top of the screen. I want
to include this custom component in every one of my Activities. Now,
in a any given activity, how do I go about adding content on the
screen (say a button in the middle of the screen) in a addition to my
custom component thats ever present?</p>

答:
How about adding a base layout with can contain the header and footer that you use everywhere and then have a stub in the middle that you can inflate with whatever you like?

I think that will solve your problem.

You can read about ViewStub here:
http://android-developers.blogspot.com/2009/03/android-layout-tricks-3-optimize-with.html

Title: Custom Component in android


问:
Can't get either Postgres permissions or PVC working in AKS
These are pretty much the steps I have followed in order. Basically what is outlined in the documentation:

https://learn.microsoft.com/en-us/azure/aks/azure-files-dynamic-pv

azure-storage-claim.yaml

```<code>kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: test-app-sc
provisioner: kubernetes.io/azure-file
mountOptions:
  - dir_mode=0777
  - file_mode=0777
  - uid=1000
  - gid=1000
  - mfsymlinks
  - nobrl
  - cache=none
parameters:
  skuName: Standard_LRS
  location: westus
</code>```

azure-storage.yaml

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: test-app-storage
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: test-app-sc
  resources:
    requests:
      storage: 15Gi
</code>```

PVC is now setup.

Changed the mountPath per the Postgres image documentation:

PGDATA

This optional variable can be used to define another location - like a subdirectory - for the database files. The default is /var/lib/postgresql/data, but if the data volume you're using is a filesystem mountpoint (like with GCE persistent disks), Postgres initdb recommends a subdirectory (for example /var/lib/postgresql/data/pgdata ) be created to contain the data.

This is an environment variable that is not Docker specific. Because the variable is used by the postgres server binary (see the PostgreSQL docs), the entrypoint script takes it into account.

Based on that, I have my postgres.yaml setup like the following:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      component: postgres
  template:
    metadata:
      labels:
        component: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:11-alpine
          ports:
            - containerPort: 5432
          env:
            - name: POSTGRES_DB
              valueFrom:
                secretKeyRef:
                  name: test-app-secrets
                  key: PGDATABASE
            - name: POSTGRES_USER
              valueFrom:
                secretKeyRef:
                  name: test-app-secrets
                  key: PGUSER
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: test-app-secrets
                  key: PGPASSWORD
            - name: POSTGRES_INITDB_ARGS
              value: "-A md5"
            - name: PGDATA
              value: /var/lib/postgresql-data
          volumeMounts:
            - name: test-app-storage
              mountPath: /var/lib/postgresql-data
              subPath: postgres-storage
      volumes:
        - name: test-app-storage
          persistentVolumeClaim:
            claimName: test-app-storage
---
apiVersion: v1
kind: Service
metadata:
  name: postgres-cluster-ip-service
spec:
  type: ClusterIP
  selector:
    component: postgres
  ports:
    - port: 1423
      targetPort: 5432
</code>```

You get the error:

```<code>chmod: changing permissions of '/var/lib/postgresql-data': Operation not permitted
</code>```

So with either of that as the Dockerfile:

```<code>FROM postgres:11-alpine
EXPOSE 5432
RUN /bin/bash -c 'chmod 777 /var/lib/postgresql-data'

</code>```

Or

```<code>FROM postgres:11-alpine
EXPOSE 5432
</code>```

It doesn't really matter, you still get the same type of error by doing any the following:

```<code>            ...
            - name: POSTGRES_INITDB_ARGS
              value: "-A md5"
          volumeMounts:
            - name: test-app-storage
              mountPath: /var/lib/postgresql-data
              subPath: postgres-storage
      volumes:
        - name: test-app-storage
          persistentVolumeClaim:
            claimName: test-app-storage
     ...
</code>```

Results in the following error:

```<code>The files belonging to this database system will be owned by user "postgres". This user must also own the server process.
The database cluster will be initialized with locale "en_US.utf8". The default database encoding has accordingly been set to "UTF8". The default text search configuration will be set to "english".

Data page checksums are disabled.

initdb: error: directory "/var/lib/postgresql-data" exists but is not empty If you want to create a new database system, either remove or empty the directory "/var/lib/postgresql-data" or run initdb with an argument other than "/var/lib/postgresql-data".
</code>```

Try this:

```<code>            ...
            - name: POSTGRES_INITDB_ARGS
              value: "-A md5"
          volumeMounts:
            - name: test-app-storage
              mountPath: /var/lib/postgresql-data
              subPath: postgres-storage
      volumes:
        - name: test-app-storage
          persistentVolumeClaim:
            claimName: test-app-storage
     ...
</code>```

And it results in this:

```<code>chmod: changing permissions of '/var/lib/postgresql-data': Operation not permitted
</code>```

Try this:

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: test-app-storage
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: test-app-sc
  resources:
    requests:
      storage: 15Gi
</code>```0

And it results in this:

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: test-app-storage
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: test-app-sc
  resources:
    requests:
      storage: 15Gi
</code>```1

Someone suggested to get rid of the volume mounts like so:

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: test-app-storage
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: test-app-sc
  resources:
    requests:
      storage: 15Gi
</code>```2

Which, hey, that actually works! But doesn't persist data given it just uses the Pod storage so is pretty pointless:

And sure enough when you create a table in Postgres, destroy the Pod, and then redeploy it, of course the table is no longer there.

So more than likely I'm doing something wrong, but I've been following the documentation and seems like this should work.

Where are things going wrong?

EDIT: Permissions in Pod

Apparently it is a permissions issue that occurs when PGDATA is the same directory as mountPath. For example:

```<code>  ...
  - name: PGDATA
    value: /var/lib/postgresql-data
volumeMounts:
  - name: test-app-storage
    mountPath: /var/lib/postgresql-data
    subPath: postgres-storage
...

or

  ...
  # if PGDATA is not specified it defaults to /var/lib/postgresql/data
  # - name: PGDATA
  #   value: /var/lib/postgresql-data
volumeMounts:
  - name: test-app-storage
    mountPath: /var/lib/postgresql/data
    subPath: postgres-storage
...

</code>```

Something like this where they do not match will create the Pod, but uses Pod storage which I obviously don't want:

```<code>  # Thus /var/lib/postgresql/data
  # - name: PGDATA
  #   value: /var/lib/postgresql-data
volumeMounts:
  - name: test-app-storage
    mountPath: /var/lib/postgresql-data
    subPath: postgres-storage
</code>```

Permissions ls -l looks like this:

```<code>$ ls -l

drwxr-xr-x 1 root     root     4096 Feb  2 06:06 apt
drwxr-xr-x 1 root     root     4096 Feb  2 06:07 dpkg
drwxr-xr-x 2 root     root     4096 Feb  2 06:06 exim4
drwxr-xr-x 2 root     root     4096 Aug 28  2018 logrotate
drwxr-xr-x 2 root     root     4096 Nov 10 12:17 misc
drwxr-xr-x 2 root     root     4096 Jan 30 00:00 pam
drwxr-xr-x 1 postgres postgres 4096 Feb  2 06:07 postgresql
drwxrwxrwx 2     1000     1000    0 Jan 31 21:46 postgresql-data
drwxr-xr-x 1 root     root     4096 Jan 30 00:00 systemd
drwxr-xr-x 3 root     root     4096 Feb  2 06:07 ucf

$ ls -l postgresql && ls -l postgresql/data && ls -l postgresql-data
total 4
drwx------ 19 postgres postgres 4096 Feb  5 23:28 data
total 124
drwx------ 6 postgres postgres  4096 Feb  5 23:28 base
drwx------ 2 postgres postgres  4096 Feb  5 23:29 global
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_commit_ts
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_dynshmem
-rw------- 1 postgres postgres  4281 Feb  5 23:28 pg_hba.conf
-rw------- 1 postgres postgres  1636 Feb  5 23:28 pg_ident.conf
drwx------ 4 postgres postgres  4096 Feb  5 23:33 pg_logical
drwx------ 4 postgres postgres  4096 Feb  5 23:28 pg_multixact
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_notify
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_replslot
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_serial
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_snapshots
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_stat
drwx------ 2 postgres postgres  4096 Feb  5 23:51 pg_stat_tmp
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_subtrans
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_tblspc
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_twophase
-rw------- 1 postgres postgres     3 Feb  5 23:28 PG_VERSION
drwx------ 3 postgres postgres  4096 Feb  5 23:28 pg_wal
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_xact
-rw------- 1 postgres postgres    88 Feb  5 23:28 postgresql.auto.conf
-rw------- 1 postgres postgres 26588 Feb  5 23:28 postgresql.conf
-rw------- 1 postgres postgres    36 Feb  5 23:28 postmaster.opts
-rw------- 1 postgres postgres    94 Feb  5 23:28 postmaster.pid
total 0
</code>```

The permissions for where it creates the data files is postgres. However, doing this, it doesn't map to Azure Files and the PVC. It just stays and is destroyed with the Pod.

I think what is happening is mountPath uses root and PGDATA uses postgres, and somehow mountPath is trying to use postgres???

Really, not sure and still lost as to how to resolve it.

EDIT2

Came across this answer:

https://stackoverflow.com/a/51203031/3123109

So added the following to mine:

```<code>- name: postgres
  image: postgres
  command:
  - /bin/chown
  - -R
  - "1000"
  - /var/lib/postgresql/data
</code>```

But this generates a new error:

```<code>The selected container has not logged any messages yet.
</code>```

Progress, I guess.

答:
I think your problem might be due to the fact that you are trying to use a subPath as part of your deployment object

Please retry your first configuration without this line:

subPath: postgres-storage

It should result into this
volumeMounts:
            - name: postgres-storage
              mountPath: /var/lib/postgresql/data/pgdata

Let me know if that helps.

UPDATE: The docker image for the postgresql requires special attention when using persistent storage

https://hub.docker.com/_/postgres

The main caveat to note is that postgres doesn't care what UID it runs as (as long as the owner of /var/lib/postgresql/data matches), but initdb does care (and needs the user to exist in /etc/passwd):

The three easiest ways to get around this:

use the Debian variants (not the Alpine variants) and thus allow the image to use the nss_wrapper library to "fake" /etc/passwd contents for you (see docker-library/postgres#448 for more details)

bind-mount /etc/passwd read-only from the host (if the UID you desire is a valid user on your host):

$ docker run -it --rm --user "$(id -u):$(id -g)" -v /etc/passwd:/etc/passwd:ro -e POSTGRES_PASSWORD=mysecretpassword postgres
The files belonging to this database system will be owned by user "jsmith"

Initialize the target directory separately from the final runtime (with a chown in between):

$ docker volume create pgdata
$ docker run -it --rm -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=mysecretpassword postgres
The files belonging to this database system will be owned by user "postgres".
( once it's finished initializing successfully and is waiting for connections, stop it )
$ docker run -it --rm -v pgdata:/var/lib/postgresql/data bash chown -R 1000:1000 /var/lib/postgresql/data
$ docker run -it --rm --user 1000:1000 -v pgdata:/var/lib/postgresql/data postgres
LOG:  database system was shut down at 2017-01-20 00:03:23 UTC
LOG:  MultiXact member wraparound protections are now enabled
LOG:  autovacuum launcher started
LOG:  database system is ready to accept connections

One solution would be to leverage the helm chart made by bitnami, they have worked out the default of the complex persistent storage configurations using an init container, and they also support the /dev/shm configuration needed to fix

Also note that the default /dev/shm size for containers is 64MB. If the shared memory is exhausted you will encounter ERROR: could not resize shared memory segment . . . : No space left on device. You will want to pass --shm-size=256MB for example to docker run, or alternatively in docker-compose

Here's the example of the init container used by the chart.

https://github.com/helm/charts/blob/master/stable/postgresql/templates/statefulset.yaml#L74-L115

The recommendation would be to use helm to install the Postgres chart (which uses a statefuset) instead of trying to deploy the DB using a deployment object. (normally you want to use deployment objects for stateless application).

Body:
These are pretty much the steps I have followed in order. Basically what is outlined in the documentation:

https://learn.microsoft.com/en-us/azure/aks/azure-files-dynamic-pv

azure-storage-claim.yaml

kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: test-app-sc
provisioner: kubernetes.io/azure-file
mountOptions:
  - dir_mode=0777
  - file_mode=0777
  - uid=1000
  - gid=1000
  - mfsymlinks
  - nobrl
  - cache=none
parameters:
  skuName: Standard_LRS
  location: westus

azure-storage.yaml

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: test-app-storage
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: test-app-sc
  resources:
    requests:
      storage: 15Gi

PVC is now setup.

Changed the mountPath per the Postgres image documentation:

PGDATA

This optional variable can be used to define another location - like a subdirectory - for the database files. The default is /var/lib/postgresql/data, but if the data volume you're using is a filesystem mountpoint (like with GCE persistent disks), Postgres initdb recommends a subdirectory (for example /var/lib/postgresql/data/pgdata ) be created to contain the data.

This is an environment variable that is not Docker specific. Because the variable is used by the postgres server binary (see the PostgreSQL docs), the entrypoint script takes it into account.

Based on that, I have my postgres.yaml setup like the following:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      component: postgres
  template:
    metadata:
      labels:
        component: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:11-alpine
          ports:
            - containerPort: 5432
          env:
            - name: POSTGRES_DB
              valueFrom:
                secretKeyRef:
                  name: test-app-secrets
                  key: PGDATABASE
            - name: POSTGRES_USER
              valueFrom:
                secretKeyRef:
                  name: test-app-secrets
                  key: PGUSER
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: test-app-secrets
                  key: PGPASSWORD
            - name: POSTGRES_INITDB_ARGS
              value: "-A md5"
            - name: PGDATA
              value: /var/lib/postgresql-data
          volumeMounts:
            - name: test-app-storage
              mountPath: /var/lib/postgresql-data
              subPath: postgres-storage
      volumes:
        - name: test-app-storage
          persistentVolumeClaim:
            claimName: test-app-storage
---
apiVersion: v1
kind: Service
metadata:
  name: postgres-cluster-ip-service
spec:
  type: ClusterIP
  selector:
    component: postgres
  ports:
    - port: 1423
      targetPort: 5432

You get the error:

chmod: changing permissions of '/var/lib/postgresql-data': Operation not permitted

So with either of that as the Dockerfile:

FROM postgres:11-alpine
EXPOSE 5432
RUN /bin/bash -c 'chmod 777 /var/lib/postgresql-data'

Or

FROM postgres:11-alpine
EXPOSE 5432

It doesn't really matter, you still get the same type of error by doing any the following:

            ...
            - name: POSTGRES_INITDB_ARGS
              value: "-A md5"
          volumeMounts:
            - name: test-app-storage
              mountPath: /var/lib/postgresql-data
              subPath: postgres-storage
      volumes:
        - name: test-app-storage
          persistentVolumeClaim:
            claimName: test-app-storage
     ...

Results in the following error:

The files belonging to this database system will be owned by user "postgres". This user must also own the server process.
The database cluster will be initialized with locale "en_US.utf8". The default database encoding has accordingly been set to "UTF8". The default text search configuration will be set to "english".

Data page checksums are disabled.

initdb: error: directory "/var/lib/postgresql-data" exists but is not empty If you want to create a new database system, either remove or empty the directory "/var/lib/postgresql-data" or run initdb with an argument other than "/var/lib/postgresql-data".

Try this:

            ...
            - name: POSTGRES_INITDB_ARGS
              value: "-A md5"
          volumeMounts:
            - name: test-app-storage
              mountPath: /var/lib/postgresql-data
              subPath: postgres-storage
      volumes:
        - name: test-app-storage
          persistentVolumeClaim:
            claimName: test-app-storage
     ...

And it results in this:

chmod: changing permissions of '/var/lib/postgresql-data': Operation not permitted

Try this:

            ...
            - name: POSTGRES_INITDB_ARGS
              value: "-A md5"
              value: "-D /var/lib/postgresql/data/pgdata"
          volumeMounts:
            - name: test-app-storage
              mountPath: /var/lib/postgresql/data/pgdata
              subPath: postgres-storage
      volumes:
        - name: test-app-storage
          persistentVolumeClaim:
            claimName: test-app-storage
     ...

And it results in this:

The files belonging to this database system will be owned by user "postgres". This user must also own the server process.
The database cluster will be initialized with locale "en_US.utf8". The default database encoding has accordingly been set to "UTF8". The default text search configuration will be set to "english".

Data page checksums are disabled.

initdb: error: could not change permissions of directory "/var/lib/postgresql/data/pgdata": Operation not permitted fixing permissions on existing directory /var/lib/postgresql/data/pgdata ...

So nothing seems to work that I've tried and following the documentation where I can.

Someone suggested to get rid of the volume mounts like so:

            ...
            - name: POSTGRES_INITDB_ARGS
              value: "-A md5"
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
      volumes:
        - name: test-app-storage
          persistentVolumeClaim:
            claimName: test-app-storage
     ...

Which, hey, that actually works! But doesn't persist data given it just uses the Pod storage so is pretty pointless:

And sure enough when you create a table in Postgres, destroy the Pod, and then redeploy it, of course the table is no longer there.

So more than likely I'm doing something wrong, but I've been following the documentation and seems like this should work.

Where are things going wrong?

EDIT: Permissions in Pod

Apparently it is a permissions issue that occurs when PGDATA is the same directory as mountPath. For example:

  ...
  - name: PGDATA
    value: /var/lib/postgresql-data
volumeMounts:
  - name: test-app-storage
    mountPath: /var/lib/postgresql-data
    subPath: postgres-storage
...

or

  ...
  # if PGDATA is not specified it defaults to /var/lib/postgresql/data
  # - name: PGDATA
  #   value: /var/lib/postgresql-data
volumeMounts:
  - name: test-app-storage
    mountPath: /var/lib/postgresql/data
    subPath: postgres-storage
...

Something like this where they do not match will create the Pod, but uses Pod storage which I obviously don't want:

  # Thus /var/lib/postgresql/data
  # - name: PGDATA
  #   value: /var/lib/postgresql-data
volumeMounts:
  - name: test-app-storage
    mountPath: /var/lib/postgresql-data
    subPath: postgres-storage

Permissions ls -l looks like this:

$ ls -l

drwxr-xr-x 1 root     root     4096 Feb  2 06:06 apt
drwxr-xr-x 1 root     root     4096 Feb  2 06:07 dpkg
drwxr-xr-x 2 root     root     4096 Feb  2 06:06 exim4
drwxr-xr-x 2 root     root     4096 Aug 28  2018 logrotate
drwxr-xr-x 2 root     root     4096 Nov 10 12:17 misc
drwxr-xr-x 2 root     root     4096 Jan 30 00:00 pam
drwxr-xr-x 1 postgres postgres 4096 Feb  2 06:07 postgresql
drwxrwxrwx 2     1000     1000    0 Jan 31 21:46 postgresql-data
drwxr-xr-x 1 root     root     4096 Jan 30 00:00 systemd
drwxr-xr-x 3 root     root     4096 Feb  2 06:07 ucf

$ ls -l postgresql && ls -l postgresql/data && ls -l postgresql-data
total 4
drwx------ 19 postgres postgres 4096 Feb  5 23:28 data
total 124
drwx------ 6 postgres postgres  4096 Feb  5 23:28 base
drwx------ 2 postgres postgres  4096 Feb  5 23:29 global
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_commit_ts
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_dynshmem
-rw------- 1 postgres postgres  4281 Feb  5 23:28 pg_hba.conf
-rw------- 1 postgres postgres  1636 Feb  5 23:28 pg_ident.conf
drwx------ 4 postgres postgres  4096 Feb  5 23:33 pg_logical
drwx------ 4 postgres postgres  4096 Feb  5 23:28 pg_multixact
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_notify
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_replslot
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_serial
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_snapshots
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_stat
drwx------ 2 postgres postgres  4096 Feb  5 23:51 pg_stat_tmp
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_subtrans
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_tblspc
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_twophase
-rw------- 1 postgres postgres     3 Feb  5 23:28 PG_VERSION
drwx------ 3 postgres postgres  4096 Feb  5 23:28 pg_wal
drwx------ 2 postgres postgres  4096 Feb  5 23:28 pg_xact
-rw------- 1 postgres postgres    88 Feb  5 23:28 postgresql.auto.conf
-rw------- 1 postgres postgres 26588 Feb  5 23:28 postgresql.conf
-rw------- 1 postgres postgres    36 Feb  5 23:28 postmaster.opts
-rw------- 1 postgres postgres    94 Feb  5 23:28 postmaster.pid
total 0

The permissions for where it creates the data files is postgres. However, doing this, it doesn't map to Azure Files and the PVC. It just stays and is destroyed with the Pod.

I think what is happening is mountPath uses root and PGDATA uses postgres, and somehow mountPath is trying to use postgres???

Really, not sure and still lost as to how to resolve it.

EDIT2

Came across this answer:

https://stackoverflow.com/a/51203031/3123109

So added the following to mine:

- name: postgres
  image: postgres
  command:
  - /bin/chown
  - -R
  - "1000"
  - /var/lib/postgresql/data

But this generates a new error:

The selected container has not logged any messages yet.

Progress, I guess.


问:
Python cx_freeze & setuptools
I want to use cx_freeze to freeze a python app but I also want to keep the posibillity to use pip to install the package from source. When I try to install the package in developement mode (pip install -e .), I get the error as below. It seems that cx_freeze uses distutils and not setuptools in the background. Is it possible to force cx_freeze to use also setuptools?

```<code>D:\Python\FPF4Creator>pip install -e .
You are using pip version 7.0.3, however version 7.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
Obtaining file:///D:/Python/FPF4Creator
Requirement already satisfied (use --upgrade to upgrade): jinja2 in c:\winpython\python-2.7.6\lib\site-packages (from fpf4creator==0.0.2)
Requirement already satisfied (use --upgrade to upgrade): six in c:\winpython\python-2.7.6\lib\site-packages (from fpf4creator==0.0.2)
Requirement already satisfied (use --upgrade to upgrade): markupsafe in c:\winpython\python-2.7.6\lib\site-packages (from jinja2->fpf4creator==0.0.2)
Installing collected packages: fpf4creator
  Running setup.py develop for fpf4creator
    Complete output from command C:\WinPython\python-2.7.6\python.exe -c "import setuptools, tokenize; __file__='D:\\Python\\FPF4Creator\\setup.py'; e
    xec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" develop --no-deps:
  running develop
    Checking .pth file support in C:\Program Files (x86)\fpf4creator\Lib\site-packages\
      error: can't create or remove files in install directory

      The following error occurred while trying to add or remove files in the
      installation directory:

      [Error 5] Zugriff verweigert: 'C:\\Program Files (x86)\\fpf4creator'

      The installation directory you specified (via --install-dir, --prefix, or
      the distutils default setting) was:

      C:\Program Files (x86)\fpf4creator\Lib\site-packages\

      This directory does not currently exist.  Please create it and try again, or
      choose a different installation directory (using the -d or --install-dir
      option).

----------------------------------------
Command "C:\WinPython\python-2.7.6\python.exe -c "import setuptools, tokenize; __file__='D:\\Python\\FPF4Creator\\setup.py'; exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" develop --no-deps" failed with error code 1 in D:\Python\FPF4Creator
</code>```

The setup.py looks like this:

```<code>import os
from setuptools import find_packages
from cx_Freeze import setup, Executable

from fpf4creator import __version__

options = {
    'build_exe': {
        'include_files': 'fpf4creator/data',
    }
}

executables = [
    Executable('fpf4creator/gui.py', targetName='FPF4Creator.exe',
               icon='fpf4creator/data/gui/icon.ico', base="Win32GUI")
]

fpf4_data = []
for root, dirnames, filenames in os.walk('fpf4creator/data'):
    for fname in filenames:
        fpf4_data.append(os.path.join(root, fname).replace('fpf4creator/', ''))

setup(
    name='fpf4creator',
    version=__version__,
    author='Author',
    author_email='mail@author.com',
    packages=find_packages(),
    package_data={
        'fpf4creator': fpf4_data
    },
    install_requires=['jinja2', 'six'],
    entry_points={
        'gui_scripts': [
            'fpf4Creator = fpf4creator.gui:main',
        ],
    },
    options=options,
    executables=executables
)
</code>```

答:
(Answer posted to re-iterate the answer given by @ThomasK as a comment several years ago since it helped me now)

You should create an additional setup file for cx-Freeze. The name of that file can be chosen freely but should not be setup.py.

Unfortunately, you may need to specify most of the setup arguments a second time. You could also tinker with a solution that retrieves the setup arguments from setup.py by making use of the fact that sys.path contains the main script's directory.

```<code>================== setup.py ==================

from setuptools import setup, find_packages
setup_arguments = { 'name': 'myapp', 'version': '0.0.0' }
if __name__ == '__main__' :
    setup( **setup_arguments )
</code>```

```<code>================ setup_cx.py =================

from setup import setup_arguments
from cx_Freeze import setup
setup( **setup_arguments )
</code>```

Title: Python cx_freeze & setuptools

Body:
I want to use cx_freeze to freeze a python app but I also want to keep the posibillity to use pip to install the package from source. When I try to install the package in developement mode (pip install -e .), I get the error as below. It seems that cx_freeze uses distutils and not setuptools in the background. Is it possible to force cx_freeze to use also setuptools?

D:\Python\FPF4Creator>pip install -e .
You are using pip version 7.0.3, however version 7.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
Obtaining file:///D:/Python/FPF4Creator
Requirement already satisfied (use --upgrade to upgrade): jinja2 in c:\winpython\python-2.7.6\lib\site-packages (from fpf4creator==0.0.2)
Requirement already satisfied (use --upgrade to upgrade): six in c:\winpython\python-2.7.6\lib\site-packages (from fpf4creator==0.0.2)
Requirement already satisfied (use --upgrade to upgrade): markupsafe in c:\winpython\python-2.7.6\lib\site-packages (from jinja2->fpf4creator==0.0.2)
Installing collected packages: fpf4creator
  Running setup.py develop for fpf4creator
    Complete output from command C:\WinPython\python-2.7.6\python.exe -c "import setuptools, tokenize; __file__='D:\\Python\\FPF4Creator\\setup.py'; e
    xec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" develop --no-deps:
  running develop
    Checking .pth file support in C:\Program Files (x86)\fpf4creator\Lib\site-packages\
      error: can't create or remove files in install directory

      The following error occurred while trying to add or remove files in the
      installation directory:

      [Error 5] Zugriff verweigert: 'C:\\Program Files (x86)\\fpf4creator'

      The installation directory you specified (via --install-dir, --prefix, or
      the distutils default setting) was:

      C:\Program Files (x86)\fpf4creator\Lib\site-packages\

      This directory does not currently exist.  Please create it and try again, or
      choose a different installation directory (using the -d or --install-dir
      option).

----------------------------------------
Command "C:\WinPython\python-2.7.6\python.exe -c "import setuptools, tokenize; __file__='D:\\Python\\FPF4Creator\\setup.py'; exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" develop --no-deps" failed with error code 1 in D:\Python\FPF4Creator

The setup.py looks like this:

import os
from setuptools import find_packages
from cx_Freeze import setup, Executable

from fpf4creator import __version__

options = {
    'build_exe': {
        'include_files': 'fpf4creator/data',
    }
}

executables = [
    Executable('fpf4creator/gui.py', targetName='FPF4Creator.exe',
               icon='fpf4creator/data/gui/icon.ico', base="Win32GUI")
]

fpf4_data = []
for root, dirnames, filenames in os.walk('fpf4creator/data'):
    for fname in filenames:
        fpf4_data.append(os.path.join(root, fname).replace('fpf4creator/', ''))

setup(
    name='fpf4creator',
    version=__version__,
    author='Author',
    author_email='mail@author.com',
    packages=find_packages(),
    package_data={
        'fpf4creator': fpf4_data
    },
    install_requires=['jinja2', 'six'],
    entry_points={
        'gui_scripts': [
            'fpf4Creator = fpf4creator.gui:main',
        ],
    },
    options=options,
    executables=executables
)

Body:
(Answer posted to re-iterate the answer given by @ThomasK as a comment several years ago since it helped me now)

You should create an additional setup file for cx-Freeze. The name of that file can be chosen freely but should not be setup.py.

Unfortunately, you may need to specify most of the setup arguments a second time. You could also tinker with a solution that retrieves the setup arguments from setup.py by making use of the fact that sys.path contains the main script's directory.

================== setup.py ==================

from setuptools import setup, find_packages
setup_arguments = { 'name': 'myapp', 'version': '0.0.0' }
if __name__ == '__main__' :
    setup( **setup_arguments )

================ setup_cx.py =================

from setup import setup_arguments
from cx_Freeze import setup
setup( **setup_arguments )


问:
Plot Smoothing Savgol filter in Modis NETCDF in python
Is it possible to insert the savgol filter in a NETCDF file in MODIS and plot the smoothing spatially in python?

Here is my sample code

```<code>import matplotlib.pyplot as plt
import xarray as xr
import pandas as pd
import numpy as np

# open Netcdf file
ds = xr.open_dataset('MOD16A2.006_500m_aid20001.nc')

# show information in xarray dataset
ds

<xarray.Dataset>
Dimensions:     (lat: 2567, lon: 2739, time: 45)
Coordinates:
  * time        (time) object 2001-01-01 00:00:00 ... 2001-12-27 00:00:00
  * lat         (lat) float64 -7.348 -7.352 -7.356 ... -18.03 -18.04 -18.04
  * lon         (lon) float64 -61.64 -61.63 -61.63 ... -50.24 -50.23 -50.23
Data variables:
    crs         int8 ...
    ET_500m     (time, lat, lon) float32 ...
    ET_QC_500m  (time, lat, lon) float32 ...
Attributes:
    title:        MOD16A2.006 for aid0001
    Conventions:  CF-1.6
    institution:  Land Processes Distributed Active Archive Center (LP DAAC)
    source:       AppEEARS v2.36
    references:   See README.txt
    history:      See README.txt

# Get Variables
lat = ds.lat
lon = ds.lon
time = ds.time
data = ds.ET_500m[0,:,:]
units = ds.ET_500m[:,:,:].units

# Plot image
data.plot.imshow(cmap='viridis_r', figsize=(10,8))
</code>```

Due to the noise that the amount of clouds causes in the pixel quality, I need to apply a spatial smoothing method to improve the quality of data derived from MODIS

I think the savgol filter fits the situation, but I don't know how to use it spatially. I may have another method of smoothing, but I don't know.

答:
Yes it is possible, please provide a working code example next time.  I would suggest using netCDF4 or xarray in python, getting the data, and using the 2d Savgol filter as found in the following documentation:

https://scipy.github.io/old-wiki/pages/Cookbook/SavitzkyGolay

This will perform the smoothing, then export the data in the netCDF file and you should be good to go.

Also, you can use xarray in conjunction with cartopy for plotting the data as well:

http://xarray.pydata.org/en/stable/plotting.html

Body:
Is it possible to insert the savgol filter in a NETCDF file in MODIS and plot the smoothing spatially in python?

Here is my sample code

import matplotlib.pyplot as plt
import xarray as xr
import pandas as pd
import numpy as np

# open Netcdf file
ds = xr.open_dataset('MOD16A2.006_500m_aid20001.nc')

# show information in xarray dataset
ds

<xarray.Dataset>
Dimensions:     (lat: 2567, lon: 2739, time: 45)
Coordinates:
  * time        (time) object 2001-01-01 00:00:00 ... 2001-12-27 00:00:00
  * lat         (lat) float64 -7.348 -7.352 -7.356 ... -18.03 -18.04 -18.04
  * lon         (lon) float64 -61.64 -61.63 -61.63 ... -50.24 -50.23 -50.23
Data variables:
    crs         int8 ...
    ET_500m     (time, lat, lon) float32 ...
    ET_QC_500m  (time, lat, lon) float32 ...
Attributes:
    title:        MOD16A2.006 for aid0001
    Conventions:  CF-1.6
    institution:  Land Processes Distributed Active Archive Center (LP DAAC)
    source:       AppEEARS v2.36
    references:   See README.txt
    history:      See README.txt

# Get Variables
lat = ds.lat
lon = ds.lon
time = ds.time
data = ds.ET_500m[0,:,:]
units = ds.ET_500m[:,:,:].units

# Plot image
data.plot.imshow(cmap='viridis_r', figsize=(10,8))

Due to the noise that the amount of clouds causes in the pixel quality, I need to apply a spatial smoothing method to improve the quality of data derived from MODIS

I think the savgol filter fits the situation, but I don't know how to use it spatially. I may have another method of smoothing, but I don't know.


问:
Stateless Apache Airflow Service
I have been searching through many articles and the official documentation for Apache Airflow and have successfully configured things to utilize a local postgres instance for the service's metadata.  One thing I cannot figure out thus far is if Apache Airflow DAGs can be defined within my database as well, rather than in a folder relative to the airflow folder location.

My goal is to have a stateless Airflow service deployed with Cloud Foundry, and thus I cannot rely on any DAG configuration files stored on the machine.  Is there a way to deploy Airflow to Cloud Foundry in such a way that the DAG configuration files are dynamically retrieved from a remote database?

答:
You can use DAG serialization feature. It has limitations though:

Limitations

The Webserver will still need access to DAG files in the following cases, which is why we said “almost” stateless.

Rendered Template tab will still have to parse Python file as it needs all the details like the execution date and even the data passed by the upstream task using Xcom.

Code View will read the DAG File & show it using Pygments. However, it does not need to Parse the Python file so it is still a small operation.

Title: Stateless Apache Airflow Service


问:
Return all objects in array
I'm missing something super obvious here so please excuse my ignorance :(

I have a set of 5 checkboxes and would like to print out steps based on what checkbox was chosen. I'll need this for a bigger output so I'm storing the selection in it's own variable like so:

```<code>        $checkBox.find('input:checked').each(function() {
        $rec = $(this).val() + "\n";
        console.log($rec);

    });
</code>```

Everything returns fine when I select all 5 checkboxes and check in console:

console.log

However, I want to use the output stored in $rec to use later so I did this to see what it will look like:

```<code>        $checkBox.find('input:checked').each(function() {

        $rec = $(this).val() + "\n";
        console.log($rec);

    });

// call rec into text input
        $textOutput.val($textOutput.val() + $rec + "\n");
        console.log($rec);
</code>```

But for some reason, only the "Do Step 5" is returned when calling $rec again

second console.log

Since I'm already storing output of the 5 checkboxes in $rec why can't I access all again rather than just the last object?

答:
But for some reason, only the "Do Step 5" is returned when calling $rec again

You're assigning the value to $rec each time, so when you console.log() in each iteration, you get the current value. But when you console.log() after the each is finished, you only get the last value that was assigned to the variable. This is because when you assign a variable, you "overwrite" the existing value (technically you point the variable at a different value), either way, any reference to the previous value is lost.

Title: Return all objects in array

Body:
I'm missing something super obvious here so please excuse my ignorance :(

I have a set of 5 checkboxes and would like to print out steps based on what checkbox was chosen. I'll need this for a bigger output so I'm storing the selection in it's own variable like so:

        $checkBox.find('input:checked').each(function() {
        $rec = $(this).val() + "\n";
        console.log($rec);

    });

Everything returns fine when I select all 5 checkboxes and check in console:

console.log

However, I want to use the output stored in $rec to use later so I did this to see what it will look like:

        $checkBox.find('input:checked').each(function() {

        $rec = $(this).val() + "\n";
        console.log($rec);

    });

// call rec into text input
        $textOutput.val($textOutput.val() + $rec + "\n");
        console.log($rec);

But for some reason, only the "Do Step 5" is returned when calling $rec again

second console.log

Since I'm already storing output of the 5 checkboxes in $rec why can't I access all again rather than just the last object?


问:
Way to make a js function accessible in Idyll?
Title says it all. I'd like to be able to transform data using the derived variable syntax, but be able to write the transforming function in a different file for syntax help and legibilitiy</p>

答:
You can inject functions into Idyll by using a custom context as per the "runtime context" documentation

If you want to write custom code that reads or writes to Idyll's internal state, you can use the context API. This API provides events
  that fire whenever an Idyll variable is changed, and provides a
  function to push variable updates.

```<code>module.exports = (ctx) => {

  // The context has loaded,   // initial data is available   ctx.onInitialize(() => {
    const initialState = ctx.data();

    // Once the context has been initialized,
    // you can use the ctx.update() method
    // to modify data
    ctx.update({
       key: value
    })

  })

  // The application has mounted in the browser,   // the window object is available   ctx.onMount(() => {

  })

  // An update has been triggered,   // arguments contain only modified data   ctx.onUpdate((newData) => {

  })

}
</code>```

To configure a custom context locally, you can point Idyll to the file where you've implemented this logic, in the package.json config.

```<code>"idyll": {   "context": "./my-context-file.js" }
</code>```

Essentially you'll want to write your function, then add it to the context during the onInitialize event. Once you've done that, then your custom function should be usable from inside any idyll expression.

Body:
You can inject functions into Idyll by using a custom context as per the "runtime context" documentation

If you want to write custom code that reads or writes to Idyll's internal state, you can use the context API. This API provides events
  that fire whenever an Idyll variable is changed, and provides a
  function to push variable updates.

module.exports = (ctx) => {

  // The context has loaded,   // initial data is available   ctx.onInitialize(() => {
    const initialState = ctx.data();

    // Once the context has been initialized,
    // you can use the ctx.update() method
    // to modify data
    ctx.update({
       key: value
    })

  })

  // The application has mounted in the browser,   // the window object is available   ctx.onMount(() => {

  })

  // An update has been triggered,   // arguments contain only modified data   ctx.onUpdate((newData) => {

  })

}

To configure a custom context locally, you can point Idyll to the file where you've implemented this logic, in the package.json config.

"idyll": {   "context": "./my-context-file.js" }

Essentially you'll want to write your function, then add it to the context during the onInitialize event. Once you've done that, then your custom function should be usable from inside any idyll expression.


问:
Is fsbolero's runner, `bolero-live`, open source and if so, where is the source?
I've been having a problem getting a modified bolero app to perform HotReload. The problem appears to be in bolero-live as indicated by this top portion of the error log (line break inserted for convenience). However, the source code for bolero-live does not appear to be available despite the presence of its reference library code for the client and server projects, on github. I welcome any insight.

```<code>fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HLTL27BTITCT", Request id "0HLTL27BTITCT:00000001":
      An unhandled exception was thrown by the application.
System.IO.DirectoryNotFoundException:
      Could not find a part of the path '
          /mnt/drive1/testproj/test1/src/test1.Serve/bin/Debug
            /netstandard2.0/dist/_framework/_bin/test1.Client.dll
          '
   at Interop.ThrowExceptionForIoErrno(
          ErrorInfo errorInfo, String path, Boolean isDirectory
          ,Func`2 errorRewriter
          )
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(
          String path, OpenFlags flags, Int32 mode
          )
   at System.IO.FileStream..ctor(
          String path, FileMode mode, FileAccess access,
          FileShare share, Int32 bufferSize, FileOptions options
          )
   at System.IO.FileStream..ctor(
          String path, FileMode mode, FileAccess access
          ,FileShare share
          )
   at System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes)
   at System.IO.File.WriteAllBytes(String path, Byte[] bytes)
   at Elmish.HotReload.Bolero.Cli.ListenerController.Update() in
          /root/TeamCity/buildAgent/work/bbeb18eb622e1e0d/src
             /bolero-live/ListenerController.fs
          :line 39
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor
          .AwaitableResultExecutor.Execute(
            IActionResultTypeMapper mapper
            ,ObjectMethodExecutor executor
            ,Object controller, Object[] arguments
            )
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .Rethrow(ActionExecutedContext context)
</code>```

答: bolero-live seems to be merely FCSWatch on github.com

Body:
I've been having a problem getting a modified bolero app to perform HotReload. The problem appears to be in bolero-live as indicated by this top portion of the error log (line break inserted for convenience). However, the source code for bolero-live does not appear to be available despite the presence of its reference library code for the client and server projects, on github. I welcome any insight.

fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HLTL27BTITCT", Request id "0HLTL27BTITCT:00000001":
      An unhandled exception was thrown by the application.
System.IO.DirectoryNotFoundException:
      Could not find a part of the path '
          /mnt/drive1/testproj/test1/src/test1.Serve/bin/Debug
            /netstandard2.0/dist/_framework/_bin/test1.Client.dll
          '
   at Interop.ThrowExceptionForIoErrno(
          ErrorInfo errorInfo, String path, Boolean isDirectory
          ,Func`2 errorRewriter
          )
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(
          String path, OpenFlags flags, Int32 mode
          )
   at System.IO.FileStream..ctor(
          String path, FileMode mode, FileAccess access,
          FileShare share, Int32 bufferSize, FileOptions options
          )
   at System.IO.FileStream..ctor(
          String path, FileMode mode, FileAccess access
          ,FileShare share
          )
   at System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes)
   at System.IO.File.WriteAllBytes(String path, Byte[] bytes)
   at Elmish.HotReload.Bolero.Cli.ListenerController.Update() in
          /root/TeamCity/buildAgent/work/bbeb18eb622e1e0d/src
             /bolero-live/ListenerController.fs
          :line 39
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor
          .AwaitableResultExecutor.Execute(
            IActionResultTypeMapper mapper
            ,ObjectMethodExecutor executor
            ,Object controller, Object[] arguments
            )
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .Rethrow(ActionExecutedContext context)


问:
CSS: Depress Dropdown grouped with Radio Buttons
I'm using bootstrap to style a group of radio buttons that also include a dropdown.

When the user selects an option from the dropdown OTHER is not included as one of the radio buttons, so it looks like the last depressed radio button has been chosen when really C | D | E has been.

Is it possible to include the OTHER dropdown as one of the radio buttons so it looks depressed when the user selected C,D,E?

Codepen here if helpful: https://codepen.io/mayagans/pen/qBdaZEJ

$( document ).ready(function() {
    $("input[name='test']").change(function(){
      $("#results").text($("input[name='test']:checked").val());
    });
});

$(".dropdownitems").click(function () {
         var value = $(this).attr("href");
     document.getElementById("results").innerHTML = value
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" data-toggle="buttons">
  <label id='RADIO' class="btn btn-primary">
    <input type="radio" name="test" id="testNONE" autocomplete="off" value="NONE">NONE
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="testA" autocomplete="off" value="A">A
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="testB" autocomplete="off" value="B">B
  </label>
  <div class="btn-group">
    <label class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      <input type="radio" class="" name="test" id="OTHER" autocomplete="off">OTHER<span class="caret"></span>
    </label>
    <ul class="dropdown-menu">
      <li>C</li>
      <li>D</li>
      <li>E</li>
    </ul>
  </div>
</div>

<div id="results"></div></code>```

答:
I don't think that radio buttons are the good solution for this. You could just use "simple" buttons. Anyway, with bootstrap, you could add "active" to the button ( or radio button) class so that it will be shown as if it was pressed.
With single button

Pressed

```<code> <button type="button" class="btn btn-primary active">Click Me!</button>
</code>```

Normal

```<code> <button type="button" class="btn btn-primary">Click Me!</button>
</code>```

With your radio button it's the same

Pressed

```<code><label class='btn btn-primary active'>
    <input type='radio' name='test' id='testA' autocomplete='off' value='A'>A
  </label>
</code>```

Normal

```<code><label class='btn btn-primary'>
    <input type='radio' name='test' id='testA' autocomplete='off' value='A'>A
  </label>
</code>```

Example

```<code><script>
    $(document).ready(function () {
        let pressedId
        let buttonsId = ["a", "b"] // List of the buttons which are always visible
        let dropDownsButtonId = ["c", "d", "e"] //List of the buttons of the dropdown
        $("button").click(function () {
            if (buttonsId.includes(this.id)) { //First "if" for "always visible" button
                changeClass(this.id)
            } else if (dropDownsButtonId.includes(this.id)) {//Second if for the button of the dropdown
                changeClass("dropDownMenuButton")
            }
        })

        function changeClass(id) {
            if (pressedId !== undefined)
                document.getElementById(pressedId).className = document.getElementById(pressedId).className.replace(" active", "")
            document.getElementById(id).className += " active"
            pressedId = id
        }
    })
</script>

<button type="button" class="btn btn-primary" id="a">a</button>
    <button type="button" class="btn btn-primary" id="b">b</button>
    <div class="dropdown">
        <div class='btn-group'>
            <button class="btn btn-primary dropdown-toggle" type="button" id="dropDownMenuButton"
                    data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                Dropdown button
            </button>
            <ul class='dropdown-menu'>
                <li>
                    <button type="button" class="btn btn-primary" id="c">c</button>
                </li>
                <li>
                    <button type="button" class="btn btn-primary" id="d">d</button>
                </li>
                <li>
                    <button type="button" class="btn btn-primary" id="e">e</button>
                </li>
            </ul>
        </div>
    </div>
</code>```

Body:
I'm using bootstrap to style a group of radio buttons that also include a dropdown.

When the user selects an option from the dropdown OTHER is not included as one of the radio buttons, so it looks like the last depressed radio button has been chosen when really C | D | E has been.

Is it possible to include the OTHER dropdown as one of the radio buttons so it looks depressed when the user selected C,D,E?

Codepen here if helpful: https://codepen.io/mayagans/pen/qBdaZEJ

$( document ).ready(function() {
    $("input[name='test']").change(function(){
      $("#results").text($("input[name='test']:checked").val());
    });
});

$(".dropdownitems").click(function () {
         var value = $(this).attr("href");
     document.getElementById("results").innerHTML = value
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <input type="radio" name="test" id="testNONE" autocomplete="off" value="NONE">NONE

    <input type="radio" name="test" id="testA" autocomplete="off" value="A">A

    <input type="radio" name="test" id="testB" autocomplete="off" value="B">B

      <input type="radio" class="" name="test" id="OTHER" autocomplete="off">OTHER

C

D

E

Body:
I don't think that radio buttons are the good solution for this. You could just use "simple" buttons. Anyway, with bootstrap, you could add "active" to the button ( or radio button) class so that it will be shown as if it was pressed.
With single button

Pressed

 <button type="button" class="btn btn-primary active">Click Me!</button>

Normal

 <button type="button" class="btn btn-primary">Click Me!</button>

With your radio button it's the same

Pressed

<label class='btn btn-primary active'>
    <input type='radio' name='test' id='testA' autocomplete='off' value='A'>A
  </label>

Normal

<label class='btn btn-primary'>
    <input type='radio' name='test' id='testA' autocomplete='off' value='A'>A
  </label>

Example

<script>
    $(document).ready(function () {
        let pressedId
        let buttonsId = ["a", "b"] // List of the buttons which are always visible
        let dropDownsButtonId = ["c", "d", "e"] //List of the buttons of the dropdown
        $("button").click(function () {
            if (buttonsId.includes(this.id)) { //First "if" for "always visible" button
                changeClass(this.id)
            } else if (dropDownsButtonId.includes(this.id)) {//Second if for the button of the dropdown
                changeClass("dropDownMenuButton")
            }
        })

        function changeClass(id) {
            if (pressedId !== undefined)
                document.getElementById(pressedId).className = document.getElementById(pressedId).className.replace(" active", "")
            document.getElementById(id).className += " active"
            pressedId = id
        }
    })
</script>

<button type="button" class="btn btn-primary" id="a">a</button>
    <button type="button" class="btn btn-primary" id="b">b</button>
    <div class="dropdown">
        <div class='btn-group'>
            <button class="btn btn-primary dropdown-toggle" type="button" id="dropDownMenuButton"
                    data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                Dropdown button
            </button>
            <ul class='dropdown-menu'>
                <li>
                    <button type="button" class="btn btn-primary" id="c">c</button>
                </li>
                <li>
                    <button type="button" class="btn btn-primary" id="d">d</button>
                </li>
                <li>
                    <button type="button" class="btn btn-primary" id="e">e</button>
                </li>
            </ul>
        </div>
    </div>


问:
Add double quotation mark to first word of each line
I have an R file of results, such as below:

```<code>filename totalvar result runtime
file1  100 0 20.45
file2  400 4 4.50
...
filen  200 1 2.00
</code>```

Some of the filename contains weird characters so I have to add quotations to it. What is the easiest way to use VIM for adding quotation marks to first word of each line?
Something like

```<code>filename totalvar result runtime
"file1"  100 0 20.45
"file2"  400 4 4.50
...
"filen"  200 1 2.00
</code>```

答:
Record it for one line, using the following keys (with the cursor at the start of the first line):

(Esc)qai"(Esc)ea"(Esc)j0q

Then you can write NumberOfLines@a example: 100@a for a 100 line you want the first word of each to be within "".

Body:
I have an R file of results, such as below:

filename totalvar result runtime
file1  100 0 20.45
file2  400 4 4.50
...
filen  200 1 2.00

Some of the filename contains weird characters so I have to add quotations to it. What is the easiest way to use VIM for adding quotation marks to first word of each line?
Something like

filename totalvar result runtime
"file1"  100 0 20.45
"file2"  400 4 4.50
...
"filen"  200 1 2.00


问:
Pandas astype() extremely slow with large number of nulls?
I have a dataframe of decent size (95,000 rows, 68 columns.) When I load in the excel file it makes a certain column go from text to being interpreted as an int. I either need a way to specify on loading that a certain column is to hold strings, or I need to figure out why astype(str) is performing so slowly.

Example code below

```<code>import pandas as pd
df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': ['a', 'b', 'c', 'd', 'e'],
    'C': ['1.1', '2.1', '3.0', '4.1', '5.1'] })
df['A']=df['A'].astype(str)+'addedtext'
print(df)
</code>```

This code works fine, does exactly what I want, changing Column A from ints to strings and verifying they are strings by using + with other strings and getting the result I want

The problem is, running this on a single column (95000 rows) of my other dataframe takes 7-8 minutes.  I feel like thats very slow for such a simple change?  Maybe I'm crazy.  Is there a faster method?  Is there a way to load a csv or excel file in but specify one column by a certain data type before hand?  Could it have to do with the fact that there is a very large number of nulls in that column?

EDIT: Im just dumb.  my timing loop contained the saving of the file.

答:
I would maybe try a list comprehension:

```<code>df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': ['a', 'b', 'c', 'd', 'e'],
    'C': ['1.1', '2.1', '3.0', '4.1', '5.1'] })

start= time.time()
df['A']=df['A'].astype(str)+'addedtext'
end = time.time()
print('original:', end-start)

start= time.time()
df['A']=[str(x) + 'addedtext' for x in df['A']]
end = time.time()
print('slightly faster alternative', end-start)
</code>```

my results were:

original: 0.002001523971557617

slightly faster alternative 0.000997781753540039

Hope this helps

Body:
I have a dataframe of decent size (95,000 rows, 68 columns.) When I load in the excel file it makes a certain column go from text to being interpreted as an int. I either need a way to specify on loading that a certain column is to hold strings, or I need to figure out why astype(str) is performing so slowly.

Example code below

import pandas as pd
df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': ['a', 'b', 'c', 'd', 'e'],
    'C': ['1.1', '2.1', '3.0', '4.1', '5.1'] })
df['A']=df['A'].astype(str)+'addedtext'
print(df)

This code works fine, does exactly what I want, changing Column A from ints to strings and verifying they are strings by using + with other strings and getting the result I want

The problem is, running this on a single column (95000 rows) of my other dataframe takes 7-8 minutes.  I feel like thats very slow for such a simple change?  Maybe I'm crazy.  Is there a faster method?  Is there a way to load a csv or excel file in but specify one column by a certain data type before hand?  Could it have to do with the fact that there is a very large number of nulls in that column?

EDIT: Im just dumb.  my timing loop contained the saving of the file.

Body:
I would maybe try a list comprehension:

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': ['a', 'b', 'c', 'd', 'e'],
    'C': ['1.1', '2.1', '3.0', '4.1', '5.1'] })

start= time.time()
df['A']=df['A'].astype(str)+'addedtext'
end = time.time()
print('original:', end-start)

start= time.time()
df['A']=[str(x) + 'addedtext' for x in df['A']]
end = time.time()
print('slightly faster alternative', end-start)

my results were:

original: 0.002001523971557617

slightly faster alternative 0.000997781753540039

Hope this helps


问:
Vlc player inside QFrame
I would like to put the VLC video player inside a frame.
every time I run it it opens in a new window
how can I put it inside the frame

here is the code

```<code>import sys

import os.path

from PyQt5.QtCore import Qt, QTimer

from PyQt5.QtGui import QPalette, QColor

from PyQt5.QtWidgets import QMainWindow, QWidget, QFrame, QSlider, QHBoxLayout, QPushButton, \
    QVBoxLayout, QAction, QFileDialog, QApplication

import vlc

from PyQt5 import QtCore, QtGui, QtWidgets

class Player(QMainWindow):

    def __init__(self, master=None):

        QMainWindow.__init__(self, master)

        self.setWindowTitle("Media Player")

        # creating a basic vlc instance

        self.instance = vlc.Instance()

        # creating an empty vlc media player

        self.mediaplayer = self.instance.media_player_new()

        self.isPaused = False

         ##########video frame

        self.videoframe = QFrame(self)

        self.videoframe.setGeometry(QtCore.QRect(210, 70, 391, 291))

        self.videoframe.setFrameShape(QtWidgets.QFrame.Box)

        self.videoframe.setFrameShadow(QtWidgets.QFrame.Raised)

        self.vboxlayout = QVBoxLayout()

        self.vboxlayout.addWidget(self.videoframe)

        ######### the vlc

        self.filename='C:/Users/Kikomi/Pictures/Camera Roll/kk.mp4'

        self.media = self.instance.media_new(self.filename)

        self.mediaplayer.set_media(self.media)

        self.mediaplayer.play()

if __name__ == "__main__":

    app = QApplication(sys.argv)

    player = Player()

    player.show()

    player.resize(640, 480)

    if sys.argv[1:]:

        player.OpenFile(sys.argv[1])

    sys.exit(app.exec_())
</code>```

答:
You have to pass the winId() of the QFrame to the mediaplayer, and the method depends on each OS as I show below:

```<code>import sys

import vlc

from PyQt5 import QtCore, QtGui, QtWidgets

class Player(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(Player, self).__init__(parent)
        self.setWindowTitle("Media Player")
        # creating a basic vlc instance
        self.instance = vlc.Instance()
        self.mediaplayer = self.instance.media_player_new()
        ##########video frame
        self.videoframe = QtWidgets.QFrame(
            frameShape=QtWidgets.QFrame.Box, frameShadow=QtWidgets.QFrame.Raised
        )

        <b>if sys.platform.startswith("linux"):  # for Linux using the X Server
            self.mediaplayer.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32":  # for Windows
            self.mediaplayer.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin":  # for MacOS
            self.mediaplayer.set_nsobject(self.videoframe.winId())</b>

        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        lay = QtWidgets.QVBoxLayout(central_widget)
        lay.addWidget(self.videoframe)

        filename = "/path/of/your/video.mp4"
        media = self.instance.media_new(filename)
        self.mediaplayer.set_media(media)
        self.mediaplayer.play()

if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)

    player = Player()
    player.show()
    player.resize(640, 480)

    sys.exit(app.exec_())</code>```

Title: Vlc player inside QFrame

Body:
I would like to put the VLC video player inside a frame.
every time I run it it opens in a new window
how can I put it inside the frame

here is the code

import sys

import os.path

from PyQt5.QtCore import Qt, QTimer

from PyQt5.QtGui import QPalette, QColor

from PyQt5.QtWidgets import QMainWindow, QWidget, QFrame, QSlider, QHBoxLayout, QPushButton, \
    QVBoxLayout, QAction, QFileDialog, QApplication

import vlc

from PyQt5 import QtCore, QtGui, QtWidgets

class Player(QMainWindow):

    def __init__(self, master=None):

        QMainWindow.__init__(self, master)

        self.setWindowTitle("Media Player")

        # creating a basic vlc instance

        self.instance = vlc.Instance()

        # creating an empty vlc media player

        self.mediaplayer = self.instance.media_player_new()

        self.isPaused = False

         ##########video frame

        self.videoframe = QFrame(self)

        self.videoframe.setGeometry(QtCore.QRect(210, 70, 391, 291))

        self.videoframe.setFrameShape(QtWidgets.QFrame.Box)

        self.videoframe.setFrameShadow(QtWidgets.QFrame.Raised)

        self.vboxlayout = QVBoxLayout()

        self.vboxlayout.addWidget(self.videoframe)

        ######### the vlc

        self.filename='C:/Users/Kikomi/Pictures/Camera Roll/kk.mp4'

        self.media = self.instance.media_new(self.filename)

        self.mediaplayer.set_media(self.media)

        self.mediaplayer.play()

if __name__ == "__main__":

    app = QApplication(sys.argv)

    player = Player()

    player.show()

    player.resize(640, 480)

    if sys.argv[1:]:

        player.OpenFile(sys.argv[1])

    sys.exit(app.exec_())

Body:
You have to pass the winId() of the QFrame to the mediaplayer, and the method depends on each OS as I show below:

import sys

import vlc

from PyQt5 import QtCore, QtGui, QtWidgets

class Player(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(Player, self).__init__(parent)
        self.setWindowTitle("Media Player")
        # creating a basic vlc instance
        self.instance = vlc.Instance()
        self.mediaplayer = self.instance.media_player_new()
        ##########video frame
        self.videoframe = QtWidgets.QFrame(
            frameShape=QtWidgets.QFrame.Box, frameShadow=QtWidgets.QFrame.Raised
        )

        if sys.platform.startswith("linux"):  # for Linux using the X Server
            self.mediaplayer.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32":  # for Windows
            self.mediaplayer.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin":  # for MacOS
            self.mediaplayer.set_nsobject(self.videoframe.winId())

        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        lay = QtWidgets.QVBoxLayout(central_widget)
        lay.addWidget(self.videoframe)

        filename = "/path/of/your/video.mp4"
        media = self.instance.media_new(filename)
        self.mediaplayer.set_media(media)
        self.mediaplayer.play()

if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)

    player = Player()
    player.show()
    player.resize(640, 480)

    sys.exit(app.exec_())


问:
How do I compare a raw time in Java?
For example suppose I have

```<code>String endTime = "16:30:45";
</code>```

How would I determine whether right now is before this time?

答:
```<code>SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");

Date d1=df.parse(endTime);
Date d2=df.parse(startTime);

long d1Ms=d1.getTime();
long d2Ms=d2.getTime();

if(d1Ms < d2Ms)
{
   //doSomething
}
else
{
   // something else
}
</code>```

Title: How do I compare a raw time in Java?

Body:
For example suppose I have

String endTime = "16:30:45";

How would I determine whether right now is before this time?


问:
How to verify if method of interface is called
I would like to test if a method from an interface is called. For example, I would like to verify that "map.put(A,B)" is called like in the below code. How would I do this in Junit? Would I need to use Mockito?</p>

```<code>
  public void funcName() {
    Map<String, Object> map = new HashMap<>();
    map.put("VALUE", new Object());
    ...
  }

</code>```

答:
If the code was exactly the one you posted, Mockito wouldn't be enough: you would need of PowerMockito.

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest({MyClass.class})
public class MyTest{
    Map<String, Object> hashMap;

    @Before
    public void setUp() throws Exception {
        hashMap = Mockito.spy(new HashMap<>());
        PowerMockito.whenNew(HashMap.class).withAnyArguments().thenReturn((HashMap) hashMap);
    }

    /**
     * Test of doSomething method, of class MyMap.
     */
    @Test
    public void testDoSomething() {
        MyClass myClass = new MyClass();
        myClass.funcName();
        Mockito.verify(hashMap).put(Mockito.anyString(), Mockito.any());
    }
}
</code>```

The use of PowerMockito is indeed necessary, when you have testability issues about:

Private methods

Static methods

Final or private class

Constructors

But PowerMockito is never a clean solution: is always better to avoid using it ; furthemore, using injection leds to better design.

Sometime even less is enough: if your code had been something like this:

```<code>
public void funcName(Map<String, Object> map){
 // something here
  map.put("", obj);
 // other stuff
}
</code>```

It wouldn't have been necessary PowerMockito:

```<code>public class MyTest{
    Map<String, Object> hashMap;

    @Before
    public void setUp() throws Exception {
        hashMap = Mockito.spy(new HashMap<>());
    }

    /**
     * Test of doSomething method, of class MyMap.
     */
    @Test
    public void testDoSomething() {
        MyClass myClass = new MyClass();
        myClass.funcName(hashMap);
        Mockito.verify(hashMap).put(Mockito.anyString(), Mockito.any());
    }
}

</code>```

Body:
I would like to test if a method from an interface is called. For example, I would like to verify that "map.put(A,B)" is called like in the below code. How would I do this in Junit? Would I need to use Mockito?

  public void funcName() {
    Map<String, Object> map = new HashMap<>();
    map.put("VALUE", new Object());
    ...
  }

Body:
If the code was exactly the one you posted, Mockito wouldn't be enough: you would need of PowerMockito.

@RunWith(PowerMockRunner.class)
@PrepareForTest({MyClass.class})
public class MyTest{
    Map<String, Object> hashMap;

    @Before
    public void setUp() throws Exception {
        hashMap = Mockito.spy(new HashMap<>());
        PowerMockito.whenNew(HashMap.class).withAnyArguments().thenReturn((HashMap) hashMap);
    }

    /**
     * Test of doSomething method, of class MyMap.
     */
    @Test
    public void testDoSomething() {
        MyClass myClass = new MyClass();
        myClass.funcName();
        Mockito.verify(hashMap).put(Mockito.anyString(), Mockito.any());
    }
}

The use of PowerMockito is indeed necessary, when you have testability issues about:

Private methods

Static methods

Final or private class

Constructors

But PowerMockito is never a clean solution: is always better to avoid using it ; furthemore, using injection leds to better design.

Sometime even less is enough: if your code had been something like this:

public void funcName(Map<String, Object> map){
 // something here
  map.put("", obj);
 // other stuff
}

It wouldn't have been necessary PowerMockito:

public class MyTest{
    Map<String, Object> hashMap;

    @Before
    public void setUp() throws Exception {
        hashMap = Mockito.spy(new HashMap<>());
    }

    /**
     * Test of doSomething method, of class MyMap.
     */
    @Test
    public void testDoSomething() {
        MyClass myClass = new MyClass();
        myClass.funcName(hashMap);
        Mockito.verify(hashMap).put(Mockito.anyString(), Mockito.any());
    }
}


问:
How to detect if webp images are supported via CSS
How do you detect in CSS if webp images are supported?

```<code>.home-banner-background {
     background-image: url('img/banner.jpg');
 }
 /*Here is an if statement that will check if webp is supported*/ {
        .home-banner-background {
            background-image: url('img/banner.webp');
        }
}
</code>```

Is there an "if" statement which can do that?

答:
You could actually just add it to the original declaration without needing multiple classes, @supports, or bringing in another library similar to this:

```<code>.home-banner-background {
    background-image: url('img/banner.jpg');
    background-image: -webkit-image-set(url('img/banner.webp') 1x,
                                        url('img/banner-2x.webp') 2x),
                                        /* etc */;
}
</code>```

Webkit will use the webp images and all others will fallback to the regular image.

Body:
How do you detect in CSS if webp images are supported?

.home-banner-background {
     background-image: url('img/banner.jpg');
 }
 /*Here is an if statement that will check if webp is supported*/ {
        .home-banner-background {
            background-image: url('img/banner.webp');
        }
}

Is there an "if" statement which can do that?

Body:
You could actually just add it to the original declaration without needing multiple classes, @supports, or bringing in another library similar to this:

.home-banner-background {
    background-image: url('img/banner.jpg');
    background-image: -webkit-image-set(url('img/banner.webp') 1x,
                                        url('img/banner-2x.webp') 2x),
                                        /* etc */;
}

Webkit will use the webp images and all others will fallback to the regular image.