问:
append dictionary to data frame
I have a function, which returns a dictionary like this:

```<code>{'truth': 185.179993, 'day1': 197.22307753038834, 'day2': 197.26118010160317, 'day3': 197.19846975345905, 'day4': 197.1490578795196, 'day5': 197.37179265011116}
</code>```

I am trying to append this dictionary to a dataframe like so:

```<code>output = pd.DataFrame()
output.append(dictionary, ignore_index=True)
print(output.head())
</code>```

Unfortunately, the printing of the dataframe results in an empty dataframe. Any ideas?

答:
The previous answer (user alex, answered Aug 9 2018 at 20:09) now triggers a warning saying that appending to a dataframe will be deprecated in a future version.

A way to do it is to transform the dictionary to a dataframe and the concatenate the dataframes:

```<code>output = pd.DataFrame()
df_dictionary = pd.DataFrame([dictionary])
output = pd.concat([output, df_dictionary], ignore_index=True)
print(output.head())
</code>```

Title: append dictionary to data frame

Body:
I have a function, which returns a dictionary like this:

{'truth': 185.179993, 'day1': 197.22307753038834, 'day2': 197.26118010160317, 'day3': 197.19846975345905, 'day4': 197.1490578795196, 'day5': 197.37179265011116}

I am trying to append this dictionary to a dataframe like so:

output = pd.DataFrame()
output.append(dictionary, ignore_index=True)
print(output.head())

Unfortunately, the printing of the dataframe results in an empty dataframe. Any ideas?

Body:
The previous answer (user alex, answered Aug 9 2018 at 20:09) now triggers a warning saying that appending to a dataframe will be deprecated in a future version.

A way to do it is to transform the dictionary to a dataframe and the concatenate the dataframes:

output = pd.DataFrame()
df_dictionary = pd.DataFrame([dictionary])
output = pd.concat([output, df_dictionary], ignore_index=True)
print(output.head())


来源: stackexchange

问:
can't select element created using map() function
I have displayed some element using Array.map function but now i cannot select any element that are created using Array.map function.when I select console log an element that is created using that map function it shows null

const fetchData = function() {
  let display = products.map(function(product) {
    return `

   ${product.category}

   ${product.name}

${product.price}

  <button
id="name"
    class="btn-add  absolute right-5 bottom-3 bg-orange-400 rounded text-sm px-2 py-2 text-white font-medium"
  >
    Add To Cart
  </button>

`;
  });

  display = display.join("");
  mainSection.innerHTML = display;
};

window.addEventListener("DOMContentLoaded", fetchData);

let btnAdd = document.querySelector(".btn-add")

console.log(btnAdd)```

答:
Put

```<code>let btnAdd = document.querySelector(".btn-add")

console.log(btnAdd)
</code>```

inside fetchData at the very bottom, when the .btn-add is already created and appended to the DOM.

You try to access .btn-add when it hasn't exist yet, DOMContentLoaded event hasn't fired yet. window.addEventListener("DOMContentLoaded", fetchData); here you only add a listener, but not execute, so your HTML in display variable hasn't exist yet

ContentLicense: CC BY-SA 4.0

Body:
Put

let btnAdd = document.querySelector(".btn-add")

console.log(btnAdd)

inside fetchData at the very bottom, when the .btn-add is already created and appended to the DOM.

You try to access .btn-add when it hasn't exist yet, DOMContentLoaded event hasn't fired yet. window.addEventListener("DOMContentLoaded", fetchData); here you only add a listener, but not execute, so your HTML in display variable hasn't exist yet


问:
LINQ to SQL eager loading with conditions
I'm trying to learn LINQ to SQL and i've found out about the LoadWith function. All the examples i've found will load all records from the table you specify in the LoadWith function e.g.

```<code>var dlo = new DataLoadOptions();
dlo.LoadWith<Blog>(b => b.Posts);
this.LoadOptions = dlo;
</code>```

What I would like to know is if it's possible to load in this example only the last blog post?

I've tried

```<code>dlo.LoadWith<Blog>(b => b.Posts.Max());
</code>```

But it doesn't like that syntax.

答:
You can do it using AssociateWith. This will work:

```<code>var options = new DataLoadOptions();
options.AssociateWith<Blog>(b =>
    b.Posts.Where(
        p1 => p1.SomeColumn == b.Posts.Max(p2 => p2. SomeColumn)
    ));
</code>```

Also, if you will be loading the info into a separate class or can use an anonymous one you can just do the query as:

```<code>var query = from b in context.Blogs
            //probably some where you already have
            select new MyBlogs // or with no type in case it is anonymous
            {
                AColumn = b.AColumn, //map any other values
                LatestPost = b.Posts.Where(
                      p1 => p1.SomeColumn == b.Posts.Max(p2 => p2. SomeColumn)
                  )).ToList()
            }
</code>```

OwnerDisplayName: Alex

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to learn LINQ to SQL and i've found out about the LoadWith function. All the examples i've found will load all records from the table you specify in the LoadWith function e.g.

var dlo = new DataLoadOptions();
dlo.LoadWith<Blog>(b => b.Posts);
this.LoadOptions = dlo;

What I would like to know is if it's possible to load in this example only the last blog post?

I've tried

dlo.LoadWith<Blog>(b => b.Posts.Max());

But it doesn't like that syntax.

Body:
You can do it using AssociateWith. This will work:

var options = new DataLoadOptions();
options.AssociateWith<Blog>(b =>
    b.Posts.Where(
        p1 => p1.SomeColumn == b.Posts.Max(p2 => p2. SomeColumn)
    ));

Also, if you will be loading the info into a separate class or can use an anonymous one you can just do the query as:

var query = from b in context.Blogs
            //probably some where you already have
            select new MyBlogs // or with no type in case it is anonymous
            {
                AColumn = b.AColumn, //map any other values
                LatestPost = b.Posts.Where(
                      p1 => p1.SomeColumn == b.Posts.Max(p2 => p2. SomeColumn)
                  )).ToList()
            }

OwnerDisplayName: Freddy Rios


问:
Flutter/Dart : Parsing 'yyyy-MM-dd HH:MM:SS' producing wrong output?
I am parsing a date in format yyyy-MM-dd HH:MM:SS using DateFormat

But I am getting some other date in parsed output

```<code>final dt = '2022-02-07 05:00:11';
final datm =  DateFormat('yyyy-MM-dd HH:MM:SS').parse(dt);

print ("DATE_CALC ${datm.day} - ${datm.month} - ${datm.year} ${datm.hour} : ${datm.minute} : ${datm.second}   ");
</code>```

Actual Output:

```<code>DATE_CALC 7 - 2 - 2021 5 : 0 : 0
</code>```

Expected :

```<code>DATE_CALC 07 - 12 - 2022 05 : 00 : 11
</code>```

Why I am getting some wrong date ? Am I doing anything wrong ?

答:
```<code>final dt = '2022-02-07 05:00:11';
final datm =  DateFormat("yyyy-MM-dd HH:mm:ss").parse(dt);
  print ("DATE_CALC ${datm.day} - ${datm.month} - ${datm.year} ${datm.hour} : ${datm.minute} : ${datm.second}   ");
</code>```

Try this
Hour minute and seconds can be parsed like this HH:mm:ss not like HH:MM:SS

Body:
I am parsing a date in format yyyy-MM-dd HH:MM:SS using DateFormat

But I am getting some other date in parsed output

final dt = '2022-02-07 05:00:11';
final datm =  DateFormat('yyyy-MM-dd HH:MM:SS').parse(dt);

print ("DATE_CALC ${datm.day} - ${datm.month} - ${datm.year} ${datm.hour} : ${datm.minute} : ${datm.second}   ");

Actual Output:

DATE_CALC 7 - 2 - 2021 5 : 0 : 0

Expected :

DATE_CALC 07 - 12 - 2022 05 : 00 : 11

Why I am getting some wrong date ? Am I doing anything wrong ?

Body:
final dt = '2022-02-07 05:00:11';
final datm =  DateFormat("yyyy-MM-dd HH:mm:ss").parse(dt);
  print ("DATE_CALC ${datm.day} - ${datm.month} - ${datm.year} ${datm.hour} : ${datm.minute} : ${datm.second}   ");

Try this
Hour minute and seconds can be parsed like this HH:mm:ss not like HH:MM:SS


问:
Kotlin using ArgumentCaptor.capture() returns null
I'm pretty new to testing so I might be doing something wrong.I'm trying to capture the values that are passed to a method

```<code>    @Mock
    private lateinit var service: TestService

    @InjectMocks
    private lateinit var underTest: UnderTestService

    @org.junit.jupiter.api.Test
        fun `testMethod`() {
            //given
            val var1 = Test.Value
            val var2 = TestClass::class.java
            val var3 = listOf(Entry1(), Entry2())

            //when
            underTest.method(var1, var2, var3)

            val argumentCaptor = ArgumentCaptor.forClass(String::class.java)

            verify(service, times(2)).method(
                argumentCaptor.capture(),
                argumentCaptor.capture()

        )
</code>```

Here, after doing verify the argumentCaptor.capture() return null for some reason and I don't understand what am I doing wrong?

```<code>java.lang.NullPointerException: argumentCaptor.capture() must not be null
</code>```

I think that it is kotlin related, the signature of the method that I'm trying to get the parameters looks like this

```<code>    fun method(param1: String, vararg param2: String?) {
            //do something
  }
</code>```

答:
MockitoKotlinHelpers.kt can help you here. The capture function provides a way to call ArgumentCaptor.capture()

Example:

```<code>verify(service, times(2)).method(
                capture(argumentCaptor),
                capture(argumentCaptor));
</code>```

Body:
I'm pretty new to testing so I might be doing something wrong.I'm trying to capture the values that are passed to a method

    @Mock
    private lateinit var service: TestService

    @InjectMocks
    private lateinit var underTest: UnderTestService

    @org.junit.jupiter.api.Test
        fun `testMethod`() {
            //given
            val var1 = Test.Value
            val var2 = TestClass::class.java
            val var3 = listOf(Entry1(), Entry2())

            //when
            underTest.method(var1, var2, var3)

            val argumentCaptor = ArgumentCaptor.forClass(String::class.java)

            verify(service, times(2)).method(
                argumentCaptor.capture(),
                argumentCaptor.capture()

        )

Here, after doing verify the argumentCaptor.capture() return null for some reason and I don't understand what am I doing wrong?

java.lang.NullPointerException: argumentCaptor.capture() must not be null

I think that it is kotlin related, the signature of the method that I'm trying to get the parameters looks like this

    fun method(param1: String, vararg param2: String?) {
            //do something
  }

Body:
MockitoKotlinHelpers.kt can help you here. The capture function provides a way to call ArgumentCaptor.capture()

Example:

verify(service, times(2)).method(
                capture(argumentCaptor),
                capture(argumentCaptor));


问:
Kubectl deployment - how to load env vars from JSON file
I'm using kubectl to deploy ASP.Net core apps to K8S cluster.
At the current moment I hardcode container PORTs and ConnectionString for DataBase like this:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: mydeploy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mydeploy
  template:
    metadata:
      labels:
        app: mydeploy
    spec:
      containers:
        - name: mydeploy
          image: harbor.com/my_app:latest
          env:
          - name: MyApp__ConnectionString
            value: "Host=postgres-ap-svc;Port=5432;Database=db;Username=postgres;Password=password"
          ports:
            - containerPort: 5076
</code>```

But the good solution I think - to use such variables from appsettings.json file (ASP.Net config file).
So my question - How to load this vars from JSON file and use in yaml file?

JSON file is like this:

```<code>{
  "MyApp": {
    "ConnectionString": "Host=postgres-ap-svc;Port=5432;Database=db;Username=postgres;Password=password"
  },
  "ClientBaseUrls": {
    "MyApp": "http://mydeploy-svc:5076/api",
  }
}
</code>```

答:
You can try using literal mode:

```<code>kubectl create configmap appsettings --from-literal='ConnectionString'='Host=postgres-ap-svc;Port=5432;Database=db;Username=postgres;Password=password' --from-literal='MyApp'='http://mydeploy-svc:5076/api'
</code>```

If this doesn't work you may need to write separate JSON-YAML parser.

Body:
I'm using kubectl to deploy ASP.Net core apps to K8S cluster.
At the current moment I hardcode container PORTs and ConnectionString for DataBase like this:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mydeploy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mydeploy
  template:
    metadata:
      labels:
        app: mydeploy
    spec:
      containers:
        - name: mydeploy
          image: harbor.com/my_app:latest
          env:
          - name: MyApp__ConnectionString
            value: "Host=postgres-ap-svc;Port=5432;Database=db;Username=postgres;Password=password"
          ports:
            - containerPort: 5076

But the good solution I think - to use such variables from appsettings.json file (ASP.Net config file).
So my question - How to load this vars from JSON file and use in yaml file?

JSON file is like this:

{
  "MyApp": {
    "ConnectionString": "Host=postgres-ap-svc;Port=5432;Database=db;Username=postgres;Password=password"
  },
  "ClientBaseUrls": {
    "MyApp": "http://mydeploy-svc:5076/api",
  }
}

Body:
You can try using literal mode:

kubectl create configmap appsettings --from-literal='ConnectionString'='Host=postgres-ap-svc;Port=5432;Database=db;Username=postgres;Password=password' --from-literal='MyApp'='http://mydeploy-svc:5076/api'

If this doesn't work you may need to write separate JSON-YAML parser.


问:
Query user's Outlook properties to see if they are a member of a specific distribution group in Outlook using Excel VBA
I wish to query a user's Outlook properties via Excel to see if they are a member of a specific distribution list.

We have four teams and also visitors known as Other.

The aim is to query if a user is a member of Team A Operators if so return a string value of Team A, elseif member of Team B operators return a string value of Team B and so on up to Team D. If not a member of any of those then return a string value of Other.

Also what is the user identifier for Outlook? Is it their email address or their login identification?

答:
You can use the GetMemeber method of the DistLisItem class from the Outlook object model to get each member of the distribution list. For example, the following code locates every distribution list in the default Contacts folder and determines whether the list contains the current user:

```<code>Sub DisplayYourDLNames()
 Dim myNameSpace As Outlook.NameSpace
 Dim myFolder As Outlook.Folder
 Dim myDistList As Outlook.DistListItem
 Dim myFolderItems As Outlook.Items
 Dim x As Integer
 Dim y As Integer
 Dim iCount As Integer

 Set myNameSpace = Application.GetNamespace("MAPI")
 Set myFolder = myNameSpace.GetDefaultFolder(olFolderContacts)
 Set myFolderItems = myFolder.Items
 iCount = myFolderItems.Count
 For x = 1 To iCount
   If TypeName(myFolderItems.Item(x)) = "DistListItem" Then
     Set myDistList = myFolderItems.Item(x)
     For y = 1 To myDistList.MemberCount
       If myDistList.GetMember(y).Name = myNameSpace.CurrentUser.Name Then
         MsgBox "Your are a member of " & myDistList.DLName
       End If
     Next y
   End If
 Next x

End Sub
</code>```

Body:
You can use the GetMemeber method of the DistLisItem class from the Outlook object model to get each member of the distribution list. For example, the following code locates every distribution list in the default Contacts folder and determines whether the list contains the current user:

Sub DisplayYourDLNames()
 Dim myNameSpace As Outlook.NameSpace
 Dim myFolder As Outlook.Folder
 Dim myDistList As Outlook.DistListItem
 Dim myFolderItems As Outlook.Items
 Dim x As Integer
 Dim y As Integer
 Dim iCount As Integer

 Set myNameSpace = Application.GetNamespace("MAPI")
 Set myFolder = myNameSpace.GetDefaultFolder(olFolderContacts)
 Set myFolderItems = myFolder.Items
 iCount = myFolderItems.Count
 For x = 1 To iCount
   If TypeName(myFolderItems.Item(x)) = "DistListItem" Then
     Set myDistList = myFolderItems.Item(x)
     For y = 1 To myDistList.MemberCount
       If myDistList.GetMember(y).Name = myNameSpace.CurrentUser.Name Then
         MsgBox "Your are a member of " & myDistList.DLName
       End If
     Next y
   End If
 Next x

End Sub


问:
Dynamically create serializer based on model field value
I have a model like so:

```<code>class A:
    name = models.CharField()
    group = models.ForeignKey('SomeModel', null=True, blank=True)
</code>```

When I serialize this, I would like the serielizer to have different formats based on whether the 'group' field is blank or not. Of course this can be achieved by having different serializers for different formats and calling them as required in the View layer:

```<code>class TypeASerializer(serializers.ModelSerializer)

    class Meta:
        model = A
        fields = ('id', 'name')

class TypeBSerializer(serializers.ModelSerializer)

    class Meta:
        model = A
        fields = ('id', 'name', 'group')
</code>```

But I wanted to handle it in the serializer layer itself and have a single serializer for this. Is that possible?

答:
Serializer.instance may be None in some cases.

And get_fields() is called only once because Serializer.fields is cached from django-rest-framework 3.10: https://github.com/encode/django-rest-framework/commit/7232586c7caf66f20f56b36f1c6a9c9648eb94a4

In other words, when a serializer is used as a list by many=True (in ListModelMixin, or as a field of another serializer), the fields of all items in the list are determined by the first instance.

In that case, the solution is to override to_representation():

```<code>class TypeASerializer(serializers.ModelSerializer)
    class Meta:
        model = A
        fields = ('id', 'name', 'group')

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        if not instance.group:
            del ret['group']
        return ret
</code>```

This solution is a little inefficient because all fields and values are obtained from super().to_presentation() but some of them are removed again. You can consider fully implementing to_representation() without calling super's.

Body:
I have a model like so:

class A:
    name = models.CharField()
    group = models.ForeignKey('SomeModel', null=True, blank=True)

When I serialize this, I would like the serielizer to have different formats based on whether the 'group' field is blank or not. Of course this can be achieved by having different serializers for different formats and calling them as required in the View layer:

class TypeASerializer(serializers.ModelSerializer)

    class Meta:
        model = A
        fields = ('id', 'name')

class TypeBSerializer(serializers.ModelSerializer)

    class Meta:
        model = A
        fields = ('id', 'name', 'group')

But I wanted to handle it in the serializer layer itself and have a single serializer for this. Is that possible?

Body:
Serializer.instance may be None in some cases.

And get_fields() is called only once because Serializer.fields is cached from django-rest-framework 3.10: https://github.com/encode/django-rest-framework/commit/7232586c7caf66f20f56b36f1c6a9c9648eb94a4

In other words, when a serializer is used as a list by many=True (in ListModelMixin, or as a field of another serializer), the fields of all items in the list are determined by the first instance.

In that case, the solution is to override to_representation():

class TypeASerializer(serializers.ModelSerializer)
    class Meta:
        model = A
        fields = ('id', 'name', 'group')

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        if not instance.group:
            del ret['group']
        return ret

This solution is a little inefficient because all fields and values are obtained from super().to_presentation() but some of them are removed again. You can consider fully implementing to_representation() without calling super's.


问:
The body of view to be destroyed gets called (but it shouldn't)
While verifying how binding invalidates a view (indirectly), I find an unexpected behavior.

If the view hierarchy is

```<code> list view -> detail view
</code>```

it works fine (as expected) to press a button in the detail view to delete the item.

However, if the view hierarchy is

```<code>list view -> detail view -> another detail view (containing the same item)
</code>```

it crashes when I press a button in the top-most detail view to delete the item. The crash occurs in the first detail view (the underlying one), because its body gets called.

To put it in another way, the behavior is:

If the detail view is the top-most view in the navigation stack, its body doesn't get called.

Otherwise, its body gets called.

I can't think out any reason for this behavior. My debugging showed below are what happened before the crash:

I pressed a button in top-most detail view to delete the item.

The ListView's body got called (as a result of ContentView body got called). It created only the detail view for the left item.

Then the first DetailView's body get called. This is what caused the crash. I can't think out why this occurred, because it certainly didn't occur for the top-most detail view.

Below is the code. Note the ListView and DetailView contains only binding and regular properties (they don't contain observable object or environment object, which I'm aware complicate the view invalidation behavior).

```<code>import SwiftUI

struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
}

struct ListView: View {
    @Binding var foos: [Foo]

    var body: some View {
        NavigationView {
            List {
                ForEach(foos) { foo in
                    NavigationLink {
                        DetailView(foos: $foos, fooID: foo.id, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var foos: [Foo]
    var fooID: Int
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(fooID)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foos.get(fooID).value)")
            NavigationLink {
                DetailView(foos: $foos, fooID: fooID, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                foos.remove(fooID)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView(foos: $dataModel.foos)
    }
}
</code>```

Test 1: Start the app, click on an item in the list view to go to the detail view, then click on "Delete It" button. This works fine.

The view hierarchy: list view -> detail view

Test 2: Start the app, click on an item in the list view to go to the detail view, then click on "Create another detail view" to go to another detail view. Then click on "Delete It" button. The crashes the first detail view.

The view hierarchy: list view -> detail view -> another detail view

Could it be just another bug of @Binding? Is there any robust way to work around the issue?

答:
Here is a working version. It's best to pass the model around so you can use array subscripting to mutate.

I also changed your id to UUID because that's what I'm used to and changed some vars that should be lets.

```<code>import SwiftUI

struct Foo: Identifiable {
    //var id: Int
    let id = UUID()
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
//extension Array where Element == Foo {
//    func get(_ id: Int) -> Foo {
//        return first(where: { $0.id == id })!
//    }
//
//    mutating func remove(_ id: Int) {
//        let index = firstIndex(where: { $0.id == id })!
//        remove(at: index)
//    }
//}

class DataModel: ObservableObject {
    //@Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
    @Published var foos: [Foo] = [Foo(value: 1), Foo(value: 2)]

    func foo(id: UUID) -> Foo? {
        foos.first(where: { $0.id == id })
    }
}

struct ListView: View {
    //@Binding var foos: [Foo]
    @StateObject var dataModel = DataModel()

    var body: some View {
        NavigationView {
            List {
                //ForEach(foos) { foo in
                ForEach(dataModel.foos) { foo in
                    NavigationLink {
                        //DetailView(foos: $foos, fooID: foo.id, label: "First detail view")
                        DetailView(dataModel: dataModel, foo: foo, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    //@Binding var foos: [Foo]
    @ObservedObject var dataModel: DataModel
    //var fooID: Int
    let foo: Foo
    let label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        //print(fooID)
        print(foo.id)

        return VStack {
            Text(label)
            Divider()
            //Text("Value: \(foos.get(fooID).value)")
            if let foo = dataModel.foo(id:foo.id) {
                Text("Value: \(foo.value) ")
            }
            NavigationLink {
                DetailView(dataModel: dataModel, foo: foo, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                //foos.remove(fooID)
                if let index = dataModel.foos.firstIndex(where: { $0.id == foo.id } ) {
                    dataModel.foos.remove(at: index)
                }
            }
        }
    }
}

struct ContentView: View {
    // no need for @ here because body doesn't need to update when model changes
    //@StateObject var dataModel = DataModel()

    var body: some View {
        //ListView(foos: $dataModel.foos)
        ListView()
    }
}
</code>```

Body:
While verifying how binding invalidates a view (indirectly), I find an unexpected behavior.

If the view hierarchy is

 list view -> detail view

it works fine (as expected) to press a button in the detail view to delete the item.

However, if the view hierarchy is

list view -> detail view -> another detail view (containing the same item)

it crashes when I press a button in the top-most detail view to delete the item. The crash occurs in the first detail view (the underlying one), because its body gets called.

To put it in another way, the behavior is:

If the detail view is the top-most view in the navigation stack, its body doesn't get called.

Otherwise, its body gets called.

I can't think out any reason for this behavior. My debugging showed below are what happened before the crash:

I pressed a button in top-most detail view to delete the item.

The ListView's body got called (as a result of ContentView body got called). It created only the detail view for the left item.

Then the first DetailView's body get called. This is what caused the crash. I can't think out why this occurred, because it certainly didn't occur for the top-most detail view.

Below is the code. Note the ListView and DetailView contains only binding and regular properties (they don't contain observable object or environment object, which I'm aware complicate the view invalidation behavior).

import SwiftUI

struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
}

struct ListView: View {
    @Binding var foos: [Foo]

    var body: some View {
        NavigationView {
            List {
                ForEach(foos) { foo in
                    NavigationLink {
                        DetailView(foos: $foos, fooID: foo.id, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var foos: [Foo]
    var fooID: Int
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(fooID)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foos.get(fooID).value)")
            NavigationLink {
                DetailView(foos: $foos, fooID: fooID, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                foos.remove(fooID)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView(foos: $dataModel.foos)
    }
}

Test 1: Start the app, click on an item in the list view to go to the detail view, then click on "Delete It" button. This works fine.

The view hierarchy: list view -> detail view

Test 2: Start the app, click on an item in the list view to go to the detail view, then click on "Create another detail view" to go to another detail view. Then click on "Delete It" button. The crashes the first detail view.

The view hierarchy: list view -> detail view -> another detail view

Could it be just another bug of @Binding? Is there any robust way to work around the issue?

Body:
Here is a working version. It's best to pass the model around so you can use array subscripting to mutate.

I also changed your id to UUID because that's what I'm used to and changed some vars that should be lets.

import SwiftUI

struct Foo: Identifiable {
    //var id: Int
    let id = UUID()
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
//extension Array where Element == Foo {
//    func get(_ id: Int) -> Foo {
//        return first(where: { $0.id == id })!
//    }
//
//    mutating func remove(_ id: Int) {
//        let index = firstIndex(where: { $0.id == id })!
//        remove(at: index)
//    }
//}

class DataModel: ObservableObject {
    //@Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
    @Published var foos: [Foo] = [Foo(value: 1), Foo(value: 2)]

    func foo(id: UUID) -> Foo? {
        foos.first(where: { $0.id == id })
    }
}

struct ListView: View {
    //@Binding var foos: [Foo]
    @StateObject var dataModel = DataModel()

    var body: some View {
        NavigationView {
            List {
                //ForEach(foos) { foo in
                ForEach(dataModel.foos) { foo in
                    NavigationLink {
                        //DetailView(foos: $foos, fooID: foo.id, label: "First detail view")
                        DetailView(dataModel: dataModel, foo: foo, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    //@Binding var foos: [Foo]
    @ObservedObject var dataModel: DataModel
    //var fooID: Int
    let foo: Foo
    let label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        //print(fooID)
        print(foo.id)

        return VStack {
            Text(label)
            Divider()
            //Text("Value: \(foos.get(fooID).value)")
            if let foo = dataModel.foo(id:foo.id) {
                Text("Value: \(foo.value) ")
            }
            NavigationLink {
                DetailView(dataModel: dataModel, foo: foo, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                //foos.remove(fooID)
                if let index = dataModel.foos.firstIndex(where: { $0.id == foo.id } ) {
                    dataModel.foos.remove(at: index)
                }
            }
        }
    }
}

struct ContentView: View {
    // no need for @ here because body doesn't need to update when model changes
    //@StateObject var dataModel = DataModel()

    var body: some View {
        //ListView(foos: $dataModel.foos)
        ListView()
    }
}


问:
Typescript cannot infer type not undefined through filter(x => x !== undefined)
The following Typescript (4.5.5) code triggers the error below:

```<code>interface Y {
  prop: string;
}

interface O {
  [key: string]: { x: number; y: Y | undefined };
}

function foo(o: O): Y[] {
  return Object.keys(o)
    .filter((key) => o[key].y !== undefined)
    .map((key) => o[key].y);
}
</code>```

Error:

```<code>Type '(Y | undefined)[]' is not assignable to type 'Y[]'.
  Type 'Y | undefined' is not assignable to type 'Y'.
    Type 'undefined' is not assignable to type 'Y'.ts(2322)
</code>```

Typescript does not seem to be able to infer the type from the filter().

Of course I can "fix" it by this:

```<code>.map((key) => data[key].error || ({} as Y))

or

function foo(o: O): (Y | undefined)[] { ... }
</code>```

I would have think that TS would be able to understand the filter(key => !!o[key].y)

Did I miss something?

答:
It worth using Object.values instead of Object.keys:

interface Y {
  prop: string;
}

interface O {
  [key: string]: { x: number; y: Y | undefined };
}

const withY = (value: O[string]): value is O[string] & { y: Y } =>
  value.y !== undefined

const getY = (value: O[string] & { y: Y }) => value.y

const foo = (o: O): Y[] =>
  Object.values(o)
    .filter(withY)
    .map(getY);
```

Playground

Also, I have added withY predicate which acts like a typeguard.

filter and map callbacks are moved out of foo scope. In this way you don't need to initialize same arrow function when foo is called. Consider it as a micro optimization which makes code more readable

Body:
The following Typescript (4.5.5) code triggers the error below:

interface Y {
  prop: string;
}

interface O {
  [key: string]: { x: number; y: Y | undefined };
}

function foo(o: O): Y[] {
  return Object.keys(o)
    .filter((key) => o[key].y !== undefined)
    .map((key) => o[key].y);
}

Error:

Type '(Y | undefined)[]' is not assignable to type 'Y[]'.
  Type 'Y | undefined' is not assignable to type 'Y'.
    Type 'undefined' is not assignable to type 'Y'.ts(2322)

Typescript does not seem to be able to infer the type from the filter().

Of course I can "fix" it by this:

.map((key) => data[key].error || ({} as Y))

or

function foo(o: O): (Y | undefined)[] { ... }

I would have think that TS would be able to understand the filter(key => !!o[key].y)

Did I miss something?

Body:
It worth using Object.values instead of Object.keys:

interface Y {
  prop: string;
}

interface O {
  [key: string]: { x: number; y: Y | undefined };
}

const withY = (value: O[string]): value is O[string] & { y: Y } =>
  value.y !== undefined

const getY = (value: O[string] & { y: Y }) => value.y

const foo = (o: O): Y[] =>
  Object.values(o)
    .filter(withY)
    .map(getY);

Playground

Also, I have added withY predicate which acts like a typeguard.

filter and map callbacks are moved out of foo scope. In this way you don't need to initialize same arrow function when foo is called. Consider it as a micro optimization which makes code more readable


问:
EF Core class library and migrations in azure pipeline
I know that to use EF Core in a class library a startup project is needed, as explained here: Is EF Core Add Migration Supported from .NET Standard Library?
However, I've managed to use dotnet ef migrations bundle locally using a single class library project (without using a startup project) by

Adding a ConfigurationBuilder you dbcontext

Overriding the "OnConfiguring" method to use the ConfigurationBuilder for reading the connection string where you have it. In my case from user secrets

```<code>    public partial class MyContext : DbContext
    {
        private readonly IConfiguration configuration;

        //will take the connection string from user secrets
        public MyContext()
        {
            this.configuration = new ConfigurationBuilder()
                .AddUserSecrets<ClpQUkMiContext>()
                .Build();
        }

        public MyContext(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                var connectionString = configuration["ConnectionStringInUserSecret"]
                optionsBuilder.UseSqlServer(connectionString);
            }
        }
</code>```

However, when I'm trying to use it in azure pipeline it's failing to find the connection string, which I have stored in a secret variable.
So far I've tried

Adding ".AddEnvironmentVariables()" to the configuration builder.

Mapping the secret variable in the yaml file, like

```<code>variables:
 MyConnectionString: $(MySecreatConnectionString) # Setting variable to be read by the context
</code>```

I would appreciate any help.

答:
Managed to solve the issue: To map a secret variable into an environment one that can be read by the configuration, it must be done inside each task, as crlearly explained here: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#secret-variables

dev variable inside the task

Body:
I know that to use EF Core in a class library a startup project is needed, as explained here: Is EF Core Add Migration Supported from .NET Standard Library?
However, I've managed to use dotnet ef migrations bundle locally using a single class library project (without using a startup project) by

Adding a ConfigurationBuilder you dbcontext

Overriding the "OnConfiguring" method to use the ConfigurationBuilder for reading the connection string where you have it. In my case from user secrets

    public partial class MyContext : DbContext
    {
        private readonly IConfiguration configuration;

        //will take the connection string from user secrets
        public MyContext()
        {
            this.configuration = new ConfigurationBuilder()
                .AddUserSecrets<ClpQUkMiContext>()
                .Build();
        }

        public MyContext(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                var connectionString = configuration["ConnectionStringInUserSecret"]
                optionsBuilder.UseSqlServer(connectionString);
            }
        }

However, when I'm trying to use it in azure pipeline it's failing to find the connection string, which I have stored in a secret variable.
So far I've tried

Adding ".AddEnvironmentVariables()" to the configuration builder.

Mapping the secret variable in the yaml file, like

variables:
 MyConnectionString: $(MySecreatConnectionString) # Setting variable to be read by the context

I would appreciate any help.


问:
Password Checker in java with do while
I need to write a password checker which ensures that password correct.

Firstly I prompt the user enter the password

Secondly, I prompt the user to reenter the password

thirdly, I need to check that the passwords are identical

But this steps need to repeat 1 through 3 until password is correctly entered twice.

Here is my code. But i cant understand the logic of repeat 1 through 3

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

public class Lab4Exercise1{
    public static void main(String[] args){

        System.out.print("Enter Your password");
        Scanner sc = new Scanner(System.in);
        double password = sc.nextDouble;
        double reentered = sc.nextDouble;

        do {

        }while (password==reentered);
    }
}
</code>```

答:
```<code>import java.util.*;
import java.io.*;

class PasswordChecker
{
    public static void main(String[] args) throws IOException
{
    Scanner scr = new Scanner(System.in);
    String s1;
    String s2;

    do{ System.out.println("Create a Password");
        s1=scr.next();
        System.out.println("Re-enter to confirm the Password");
        s2=scr.next();
        if(!s1.equals(s2))
        {
            System.out.println("Password did not match");
        }
        else{
            System.out.println("Registration Success");
        }

    } while(!s1.equals(s2));
}
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Password Checker in java with do while

Body:
I need to write a password checker which ensures that password correct.

Firstly I prompt the user enter the password

Secondly, I prompt the user to reenter the password

thirdly, I need to check that the passwords are identical

But this steps need to repeat 1 through 3 until password is correctly entered twice.

Here is my code. But i cant understand the logic of repeat 1 through 3

import java.util.*;

public class Lab4Exercise1{
    public static void main(String[] args){

        System.out.print("Enter Your password");
        Scanner sc = new Scanner(System.in);
        double password = sc.nextDouble;
        double reentered = sc.nextDouble;

        do {

        }while (password==reentered);
    }
}


问:
Represent a Vector<ManagedAddress> output in Mandos?
I am writing a mandos json test.

This is my method.

It returns a vector with addresses. I know with good probability this method works, I just need to test it, (I don't know how to write the test).

    #[storage_mapper("match_id_to_address_map")]
    #[view(getMatchIdToAddressMap)]
    fn match_id_to_address_map(&self, match_id: u32) -> SingleValueMapper<Vec<ManagedAddress>>;
```
<p>I want to write a test that makes sure it returns a vector with 2 addresses.</p>
<p>this is my mandos test:</p>
<pre class="lang-json prettyprint-override"><code>{
  "name": "new user with auto match",
  "steps": [
   // snipped for readability
    {
      "step": "scCall",
      "txId": "9",
      "tx": {
        "from": "address:user_one",
        "to": "sc:waiting_room",
        "function": "getMatchIdToAddressMap",
        "arguments": [
          "1"
        ],
        "gasLimit": "100000000",
        "gasPrice": "1"
      },
      "expect": {
        "out": [
          "u64:0|address:owner|address:user_one" // <- !!! IDK what to do here !!!
        ],
        "status": "",
        "logs": [],
        "gas": "*",
        "refund": "*"
      }
    }
  ]
}
</code>```

this is my error output:

Command line: ['/home/dan/elrondsdk/vmtools/mandos-test', '/home/dan/Elrond/SmartContracts/rooms/mandos']
Output: Scenario: deploy_and_wait.scen.json ...   ok
Scenario: duplicate_wait.scen.json ...   ok
Scenario: new_address_and_match.scen.json ...   FAIL: result mismatch. Tx 9. Want: ["u64:0|address:owner|address:user_one"]. Have: [0x6f776e65725f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f757365725f6f6e655f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f]
Done. Passed: 2. Failed: 1. Skipped: 0.
ERROR: some tests failed
```

答:
The actual decoded hex equals to

```<code>owner___________________________user_one________________________
</code>```

We can see that the u64:0 isn't represented.

I don't have the answer, but I have a lead.
Look at the serialization documentation and replace u64:0 with the top level-encoding

The doc: https://docs.elrond.com/developers/developer-reference/elrond-serialization-format/

Body:
I am writing a mandos json test.

This is my method.

It returns a vector with addresses. I know with good probability this method works, I just need to test it, (I don't know how to write the test).

    #[storage_mapper("match_id_to_address_map")]
    #[view(getMatchIdToAddressMap)]
    fn match_id_to_address_map(&self, match_id: u32) -> SingleValueMapper<Vec<ManagedAddress>>;

I want to write a test that makes sure it returns a vector with 2 addresses.

this is my mandos test:

{
  "name": "new user with auto match",
  "steps": [
   // snipped for readability
    {
      "step": "scCall",
      "txId": "9",
      "tx": {
        "from": "address:user_one",
        "to": "sc:waiting_room",
        "function": "getMatchIdToAddressMap",
        "arguments": [
          "1"
        ],
        "gasLimit": "100000000",
        "gasPrice": "1"
      },
      "expect": {
        "out": [
          "u64:0|address:owner|address:user_one" // <- !!! IDK what to do here !!!
        ],
        "status": "",
        "logs": [],
        "gas": "*",
        "refund": "*"
      }
    }
  ]
}

this is my error output:

Command line: ['/home/dan/elrondsdk/vmtools/mandos-test', '/home/dan/Elrond/SmartContracts/rooms/mandos']
Output: Scenario: deploy_and_wait.scen.json ...   ok
Scenario: duplicate_wait.scen.json ...   ok
Scenario: new_address_and_match.scen.json ...   FAIL: result mismatch. Tx 9. Want: ["u64:0|address:owner|address:user_one"]. Have: [0x6f776e65725f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f757365725f6f6e655f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f]
Done. Passed: 2. Failed: 1. Skipped: 0.
ERROR: some tests failed

Body:
The actual decoded hex equals to

owner___________________________user_one________________________

We can see that the u64:0 isn't represented.

I don't have the answer, but I have a lead.
Look at the serialization documentation and replace u64:0 with the top level-encoding

The doc: https://docs.elrond.com/developers/developer-reference/elrond-serialization-format/


问:
PyCharm does not highlight errors
I have a problem with PyCharm v2.7.
it does not show me errors.
I have configured it to show them as here
but nothing.
here a screenshot of what I see (no error displayed)

if I run code analysis it shows the errors marked as INVALID in the window but it does not highlight the code.
any idea?

答: I have tried many things, but only Invalidate Caches did the trick, after that I could hover the green arrow (top right side) and change Highlight to All Problems

Title: PyCharm does not highlight errors


问:
Get position of floating elements inside overflowed div
I have a div (MainDiv) with the overflow and static width and height. This div loads html content using AJAX. Those html is a multiple div-blocks with float: left CSS property, so MainDiv can be scrolled left and right. Every block has the same, fixed width

Little example:

```<code><div id="MainDiv">
<div class="Block" style="float: left;" id="Block1">Content #1</div>
<div class="Block" style="float: left;" id="Block1">Content #2</div>
<div class="Block" style="float: left;" id="Block1">Content #3</div>
...
<div class="Block" style="float: left;" id="BlockN">Content #N</div>
</div>
</code>```

How can i get position relative to MainDiv of one of div.Block using jQuery? For example, i need to get position of #Block10 relative to MainDiv.

答:
Using jQuery:</p>

```<code>var pos = $('#Block10').offset();
$('#Block10').append('X=' + (pos.left - $('#MainDiv').offset().left) + '<br />');
$('#Block10').append('Y=' + (pos.top - $('#MainDiv').offset().top) + '<br />');
</code>```

Body:
I have a div (MainDiv) with the overflow and static width and height. This div loads html content using AJAX. Those html is a multiple div-blocks with float: left CSS property, so MainDiv can be scrolled left and right. Every block has the same, fixed width

Little example:

Content #1

Content #2

Content #3

...

Content #N

How can i get position relative to MainDiv of one of div.Block using jQuery? For example, i need to get position of #Block10 relative to MainDiv.

Body:
Using jQuery:

var pos = $('#Block10').offset();
$('#Block10').append('X=' + (pos.left - $('#MainDiv').offset().left) + '<br />');
$('#Block10').append('Y=' + (pos.top - $('#MainDiv').offset().top) + '<br />');


问:
How to change the permissions of the file that is already created using wix installer
My requirement is, When installing the older installer package the file (Config.txt) is getting created with system permissions in the ProgramData folder.
And from the code, we are not able to remove the file without admin permissions.
For this reason, when installing the newer installer i wanted to changes the permissions of the file so that from the code i can remove that file.

I am new to Wix installer, i am trying it like as shown below. But it is not working.

Below is the code snippet:

```<code><Property Id="PROGRAMDATA" Value="C:\ProgramData\TestApp\Config"/>
<Property Id="APP_SEARCH">
            <DirectorySearch Id="APP_DIR" value="[PROGRAMDATA]" Depth="0">
                <FileSearch Id="FILE_SEARCH" Name="Config.txt" />
            </DirectorySearch>
</Property>

<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="CommonAppDataFolder" ShortSourceName="Common~1" SourceName="CommonAppData">
<Directory Id="NEWINSTALLDIR">
<Directory Id="APPCORE" Name="APPCore">
    <Component Id="APP" Guid="{681F6F86-00D7-41A3-8DBB-44AFE9880941}" KeyPath="yes">

        <File Id="FILE_SEARCH" Name="Config.txt" Value="[PROGRAMDATA]" KeyPath="no">
            <Permission GenericAll="yes" User="Everyone" Delete="yes"/>
        </File>
        <RemoveFile Id="FileKey3" Directory="APPCORE" Name="*" On="uninstall" />

    </Component>
</Directory>
</Directory>
</Directory>
</Directory>
</code>```

答:
Changing file permissions using Permission or PermissionEx only works with files that are created/installed by the very same setup.

In your case utilizing cacls will solve the problem.

```<code><!-- Edit file permissions -->
<CustomAction Id='UnlockFile' Directory='TARGETDIR' ExeCommand='echo Y | cacls "[MyFilePathProperty]" /C /E /G Users:W' Return='asyncNoWait' Execute='deferred'/>
<InstallExecuteSequence>
    <Custom Action='UnlockFile' Before='InstallFinalize'>NOT REMOVE</Custom>
</InstallExecuteSequence>
</code>```

Body:
My requirement is, When installing the older installer package the file (Config.txt) is getting created with system permissions in the ProgramData folder.
And from the code, we are not able to remove the file without admin permissions.
For this reason, when installing the newer installer i wanted to changes the permissions of the file so that from the code i can remove that file.

I am new to Wix installer, i am trying it like as shown below. But it is not working.

Below is the code snippet:

<Property Id="PROGRAMDATA" Value="C:\ProgramData\TestApp\Config"/>
<Property Id="APP_SEARCH">
            <DirectorySearch Id="APP_DIR" value="[PROGRAMDATA]" Depth="0">
                <FileSearch Id="FILE_SEARCH" Name="Config.txt" />
            </DirectorySearch>
</Property>

<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="CommonAppDataFolder" ShortSourceName="Common~1" SourceName="CommonAppData">
<Directory Id="NEWINSTALLDIR">
<Directory Id="APPCORE" Name="APPCore">
    <Component Id="APP" Guid="{681F6F86-00D7-41A3-8DBB-44AFE9880941}" KeyPath="yes">

        <File Id="FILE_SEARCH" Name="Config.txt" Value="[PROGRAMDATA]" KeyPath="no">
            <Permission GenericAll="yes" User="Everyone" Delete="yes"/>
        </File>
        <RemoveFile Id="FileKey3" Directory="APPCORE" Name="*" On="uninstall" />

    </Component>
</Directory>
</Directory>
</Directory>
</Directory>

Body:
Changing file permissions using Permission or PermissionEx only works with files that are created/installed by the very same setup.

In your case utilizing cacls will solve the problem.

<!-- Edit file permissions -->
<CustomAction Id='UnlockFile' Directory='TARGETDIR' ExeCommand='echo Y | cacls "[MyFilePathProperty]" /C /E /G Users:W' Return='asyncNoWait' Execute='deferred'/>
<InstallExecuteSequence>
    <Custom Action='UnlockFile' Before='InstallFinalize'>NOT REMOVE</Custom>
</InstallExecuteSequence>


问:
Streamlit - How can I know that cache data is used?
Part of my code uses @st.cache.

I would like to print a message when cached data is being used.

答:
Following code sample and explanation from streamlit doc can be useful to tweak into a value that is only printed first time. Vice versa can be more tricky.

```<code>import streamlit as st
import time

@st.cache(suppress_st_warning=True)  #  Changed this
def expensive_computation(a, b):
    #  Added this
    st.write("Cache miss: expensive_computation(", a, ",", b, ") ran")
    time.sleep(2)  # This makes the function take 2s to run
    return a * b

a = 2
b = 21
res = expensive_computation(a, b)

st.write("Result:", res)
</code>```

Explanation from Streamlit: Now when you rerun the app the text "Cache miss" appears on the first run, but not on any subsequent runs. That's because the cached function is only being executed once, and every time after that you're actually hitting the cache.

Source: https://docs.streamlit.io/library/advanced-features/caching

Body:
Following code sample and explanation from streamlit doc can be useful to tweak into a value that is only printed first time. Vice versa can be more tricky.

import streamlit as st
import time

@st.cache(suppress_st_warning=True)  #  Changed this
def expensive_computation(a, b):
    #  Added this
    st.write("Cache miss: expensive_computation(", a, ",", b, ") ran")
    time.sleep(2)  # This makes the function take 2s to run
    return a * b

a = 2
b = 21
res = expensive_computation(a, b)

st.write("Result:", res)

Explanation from Streamlit: Now when you rerun the app the text "Cache miss" appears on the first run, but not on any subsequent runs. That's because the cached function is only being executed once, and every time after that you're actually hitting the cache.

Source: https://docs.streamlit.io/library/advanced-features/caching


问:
Is it possible to query MySQL to get only fields that contain duplicate/repeating strings?
What I mean is, I have table with a "list" column. The data that goes into the "list" is related to addresses, so I sometimes get repeated zip codes for one record in that field.

For example, "12345,12345,12345,12456".

I want to know if it's possible to construct a query that would find the records that have an unknown string that duplicates within the field, such that I would get the records like "12345,12345,12345,12456", but not ones like "12345,45678,09876".

I hope that makes sense.

答:
I am still unclear what your desired result is based on your question however if it is simply to get all rows where there is a duplicate entry in column list you  could do the following:</p>
```<code>SELECT * FROM TABLE
WHERE COLUMN IN
   (SELECT COLUMN FROM TABLE
   having count(*) >1)
</code>```

Body:
I am still unclear what your desired result is based on your question however if it is simply to get all rows where there is a duplicate entry in column list you  could do the following:

SELECT * FROM TABLE
WHERE COLUMN IN
   (SELECT COLUMN FROM TABLE
   having count(*) >1)


问:
Keep items centered with interfering elements
I have a navbar which basically has one child div that serves as a list, and then these three options (potentially more in the future)

I want to ask how I can add a logo (img) at the left of this navbar, while maintaining the #navbar-options in the center, and all its items, cause if I try to add the image now, it will push the navbar options to off to the right depending on the image

```<code><div id="navbar">
    <div id="navbar-options">
        <div class="navbar-option"><a class="navbar-option-link" href="/">Home</a></div>
        <div class="navbar-option"><a class="navbar-option-link" href="/newsfeed">Newsfeed</a></div>
        <div class="navbar-option"><a class="navbar-option-link" href="/societies">Societies</a></div>
    </div>
</div>
</code>```

This is all the relevant CSS

```<code>#navbar {
    width: calc(100vw - 0);
    max-width: 100%;
    min-height: 2.5vw;
    background-color: var(--tertiary-clr);
    color: white;
    display: flex;
}

#navbar-options {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-evenly;
    align-items: center;
    margin: 0 auto;
}

.navbar-option {
    font-size: 1.5rem;
    padding: 1rem;
}
</code>```

This is the navbar currently, and an arrow indicating where I would like the image, without affecting the current position of the navbar options

答:
I just added the image I set the width and height and it worked

#navbar {
  width: calc(100vw - 0);
  max-width: 100%;
  min-height: 2.5vw;
  background-color: red;
  color: white;
  display: flex;
}
.img {
  width: 43px;
  height: 43px;
  margin: 8px;
}
#navbar-options {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-evenly;
  align-items: center;
  margin: 0 auto;
}

.navbar-option {
  font-size: 1.5rem;
  padding: 1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="navbar">
  <img class="img" src="https://cdn.freebiesupply.com/logos/large/2x/twitter-3-logo-png-transparent.png" alt="">
  <div id="navbar-options">
    <div class="navbar-option">Home</div>
    <div class="navbar-option">Newsfeed</div>
    <div class="navbar-option">Societies</div>
  </div>
</div></code>```

Body:
I have a navbar which basically has one child div that serves as a list, and then these three options (potentially more in the future)

I want to ask how I can add a logo (img) at the left of this navbar, while maintaining the #navbar-options in the center, and all its items, cause if I try to add the image now, it will push the navbar options to off to the right depending on the image

Home

Newsfeed

Societies

This is all the relevant CSS

#navbar {
    width: calc(100vw - 0);
    max-width: 100%;
    min-height: 2.5vw;
    background-color: var(--tertiary-clr);
    color: white;
    display: flex;
}

#navbar-options {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-evenly;
    align-items: center;
    margin: 0 auto;
}

.navbar-option {
    font-size: 1.5rem;
    padding: 1rem;
}

This is the navbar currently, and an arrow indicating where I would like the image, without affecting the current position of the navbar options

Body:
I just added the image I set the width and height and it worked

#navbar {
  width: calc(100vw - 0);
  max-width: 100%;
  min-height: 2.5vw;
  background-color: red;
  color: white;
  display: flex;
}
.img {
  width: 43px;
  height: 43px;
  margin: 8px;
}
#navbar-options {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-evenly;
  align-items: center;
  margin: 0 auto;
}

.navbar-option {
  font-size: 1.5rem;
  padding: 1rem;
}

<div id="navbar">
  <img class="img" src="https://cdn.freebiesupply.com/logos/large/2x/twitter-3-logo-png-transparent.png" alt="">
  <div id="navbar-options">
    <div class="navbar-option"><a class="navbar-option-link" href="/">Home</a></div>
    <div class="navbar-option"><a class="navbar-option-link" href="/newsfeed">Newsfeed</a></div>
    <div class="navbar-option"><a class="navbar-option-link" href="/societies">Societies</a></div>
  </div>
</div>


问:
install python huggingface datasets package without internet connection from python environment
I dont have access to internet connection from my python environment. I would like to install this library

I also noticed this page which has files required for the package. I installed that package by coping that file to my python environment and then running the below code

```<code>pip install 'datasets_package/datasets-1.18.3.tar.gz'
Successfully installed datasets-1.18.3 dill-0.3.4 fsspec-2022.1.0 multiprocess-0.70.12.2 pyarrow-6.0.1 xxhash-2.0.2
</code>```

But when I try the below code

```<code>import datasets
datasets.load_dataset('imdb', split =['train', 'test'])
</code>```

it throws error
ConnectionError: Couldn't reach https://raw.githubusercontent.com/huggingface/datasets/1.18.3/datasets/imdb/imdb.py (error 403)

I can access the file https://raw.githubusercontent.com/huggingface/datasets/1.18.3/datasets/imdb/imdb.py from outside my python enviroment

what files should I copy and what other code changes that I should make so that this line would work datasets.load_dataset('imdb', split =['train', 'test']) ?

#Update 1=====================

I followed below suggestions and copied below files within my python environment. So

```<code>os.listdir('huggingface_imdb_data/')
['dummy_data.zip',
 'dataset_infos.json',
 'imdb.py',
 'README.md',
 'aclImdb_v1.tar.gz']
</code>```

The last file comes from http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz and the other files come from github.com/huggingface/datasets/tree/master/datasets/imdb

Then I tried

```<code>import datasets
#datasets.load_dataset('imdb', split =['train', 'test'])
datasets.load_dataset('huggingface_imdb_data/aclImdb_v1.tar.gz')
</code>```

but i get the below error :(

```<code>HTTPError: 403 Client Error: Forbidden for url: https://huggingface.co/api/datasets/huggingface_imdb_data/aclImdb_v1.tar.gz?full=true
</code>```

I also tried

```<code>datasets.load_from_disk('huggingface_imdb_data/aclImdb_v1.tar.gz')
</code>```

but get the error

```<code>FileNotFoundError: Directory huggingface_imdb_data/aclImdb_v1.tar.gz is neither a dataset directory nor a dataset dict directory.
</code>```

答:
Unfortunately the method 1 not working because not yet supported: https://github.com/huggingface/datasets/issues/761

Method 1.:  You should use the data_files parameter of the
datasets.load_dataset function, and provide the path to your local
datafile. See the documentation:
https://huggingface.co/docs/datasets/package_reference/loading_methods.html#datasets.load_dataset

```<code>datasets.load_dataset
Parameters
...
data_dir (str, optional) – Defining the data_dir of the dataset configuration.
data_files (str or Sequence or Mapping, optional) – Path(s) to source data file(s).
...
</code>```

Update 1.: You should use something like this:

```<code>datasets.load_dataset('imdb', split =['train', 'test'], data_files='huggingface_imdb_data/aclImdb_v1.tar.gz')
</code>```

Method 2.:

Or check out this discussion: https://github.com/huggingface/datasets/issues/824#issuecomment-758358089

```<code>>here is my way to load a dataset offline, but it requires an online machine

(online machine)

    import datasets
    data = datasets.load_dataset(...)
    data.save_to_disk('./saved_imdb')

>copy the './saved_imdb' dir to the offline machine

(offline machine)

    import datasets
    data = datasets.load_from_disk('./saved_imdb')
</code>```

Body:
I dont have access to internet connection from my python environment. I would like to install this library

I also noticed this page which has files required for the package. I installed that package by coping that file to my python environment and then running the below code

pip install 'datasets_package/datasets-1.18.3.tar.gz'
Successfully installed datasets-1.18.3 dill-0.3.4 fsspec-2022.1.0 multiprocess-0.70.12.2 pyarrow-6.0.1 xxhash-2.0.2

But when I try the below code

import datasets
datasets.load_dataset('imdb', split =['train', 'test'])

it throws error
ConnectionError: Couldn't reach https://raw.githubusercontent.com/huggingface/datasets/1.18.3/datasets/imdb/imdb.py (error 403)

I can access the file https://raw.githubusercontent.com/huggingface/datasets/1.18.3/datasets/imdb/imdb.py from outside my python enviroment

what files should I copy and what other code changes that I should make so that this line would work datasets.load_dataset('imdb', split =['train', 'test']) ?

#Update 1=====================

I followed below suggestions and copied below files within my python environment. So

os.listdir('huggingface_imdb_data/')
['dummy_data.zip',
 'dataset_infos.json',
 'imdb.py',
 'README.md',
 'aclImdb_v1.tar.gz']

The last file comes from http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz and the other files come from github.com/huggingface/datasets/tree/master/datasets/imdb

Then I tried

import datasets
#datasets.load_dataset('imdb', split =['train', 'test'])
datasets.load_dataset('huggingface_imdb_data/aclImdb_v1.tar.gz')

but i get the below error :(

HTTPError: 403 Client Error: Forbidden for url: https://huggingface.co/api/datasets/huggingface_imdb_data/aclImdb_v1.tar.gz?full=true

I also tried

datasets.load_from_disk('huggingface_imdb_data/aclImdb_v1.tar.gz')

but get the error

FileNotFoundError: Directory huggingface_imdb_data/aclImdb_v1.tar.gz is neither a dataset directory nor a dataset dict directory.

Body:
Unfortunately the method 1 not working because not yet supported: https://github.com/huggingface/datasets/issues/761

Method 1.:  You should use the data_files parameter of the
datasets.load_dataset function, and provide the path to your local
datafile. See the documentation:
https://huggingface.co/docs/datasets/package_reference/loading_methods.html#datasets.load_dataset

datasets.load_dataset
Parameters
...
data_dir (str, optional) – Defining the data_dir of the dataset configuration.
data_files (str or Sequence or Mapping, optional) – Path(s) to source data file(s).
...

Update 1.: You should use something like this:

datasets.load_dataset('imdb', split =['train', 'test'], data_files='huggingface_imdb_data/aclImdb_v1.tar.gz')

Method 2.:

Or check out this discussion: https://github.com/huggingface/datasets/issues/824#issuecomment-758358089

>here is my way to load a dataset offline, but it requires an online machine

(online machine)

    import datasets
    data = datasets.load_dataset(...)
    data.save_to_disk('./saved_imdb')

>copy the './saved_imdb' dir to the offline machine

(offline machine)

    import datasets
    data = datasets.load_from_disk('./saved_imdb')


问:
CollectionView in Nib doesn't have cells?
I'm building my app like that: one ViewController = one nib file etc.

But when I added collection view in my view controller for some reason I can't add cells to it, what is the problem?

Also when I drag the cell to this collection view nothing happens...

Same problem with TableView...

答: Nibs don't support adding cells to collection views or table views directly in the nib. Only storyboards do. To use a nib with a collection/table view in it, you would have to programmatically register your cell class (or cell nib) with the collection/table view.</p>


问:
two question about python regular expressions
Q1. why we can not use word boundary and back reference without using r at start of regex?
e.g. '\b[a-z]{5}\d{3}\b' this not works but this r'\b[a-z]{5}\d{3}\b' works

Q2. why python does not support variable length negative look behind assertions while it supports variable length negative look ahead assertion, c# support both and i think it is an excellent feature to have also variable length negative look behind in python.

please clear these two concepts. thanks

答:
In regards to your first question, this is because the r designates a "raw string".  Without this r, your backslashes are interpreted as escape codes.  If you don't want to use raw strings, you can use '\\b[a-z]{5}\\d{3}\\b', although this is far less readable.  You can read more detail about raw strings here.

In regards to your second question, you should take a look at this excellent question, which discusses the differences between various flavors of regular expression used by different languages (namely C#, Java, and Python).


问:
How can I test an infinite loop bug in R
I have a bug in my R code that causes an infinite loop. I'd like to write a test that checks I have fixed this bug.

foo <- function () {
  while (TRUE) sleep(1) # oops!
}

# I want something like:
expect_completes_within(foo(), seconds = 10)
```

Is there any existing solution? Is there a way to interrupt execution and throw an error after a given time?

答:
```<code>R.utils::withTimeout(foo(), timeout = 10) # Stop foo() after 10 seconds.
</code>```

Solution has already been found here, where also code in base R has been provided.

Body:
I have a bug in my R code that causes an infinite loop. I'd like to write a test that checks I have fixed this bug.

foo <- function () {
  while (TRUE) sleep(1) # oops!
}

# I want something like:
expect_completes_within(foo(), seconds = 10)

Is there any existing solution? Is there a way to interrupt execution and throw an error after a given time?

Body:
R.utils::withTimeout(foo(), timeout = 10) # Stop foo() after 10 seconds.

Solution has already been found here, where also code in base R has been provided.


问:
req. 'connection' is @deprecated — since v13.0.0 - Use socket instead
I am trying to get the client's IP using Express:

```<code>const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
</code>```

When mouseover the req.connection in VS Code I get a warning:

```<code>(property) IncomingMessage.connection: Socket
@deprecated — since v13.0.0 - Use socket instead.

'connection' is deprecatedts(6385)
</code>```

How to implement the 'socket instead' / what is the proper way to find the IP of the client?

答: Just type req.socket.remoteAddress instead and you are good to go!</p>

Body:
I am trying to get the client's IP using Express:

const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

When mouseover the req.connection in VS Code I get a warning:

(property) IncomingMessage.connection: Socket
@deprecated — since v13.0.0 - Use socket instead.

'connection' is deprecatedts(6385)

How to implement the 'socket instead' / what is the proper way to find the IP of the client?


问:
How can I set state on individual elements in a mapped function using React?
I have an array of questions that I'm mapping through and displaying them in the UI, there is about 70+ questions.

Each question has a '+' button that reveals an answer when clicked, I want to reveal the answer using state but only for the specific question that is clicked, not the entire list. Currently I have it so when a button is clicked, it reveals all 70+ answers, what's the best way to do this so it only reveals one?

This is my code:

```<code>  const [open, setOpen] = useState(false);

 <div className='md:mt-8 pb-20'>
            {results[0].data.glossary_boxes.map((item, i) => (
              <>
                <div
                  key={i}
                  className='w-full border-3 border-yellow-500 flex-grow p-2 md:p-2 my-8'>
                  <div className='flex h-full items-center'>
                    <div className='bg-yellow-500 px-3 py-1 flex items-center justify-start ml-2'>
                      <a
                        onClick={() => setOpen(!open)}
                        className='text-white text-3xl cursor-pointer'>
                        {open ? '-' : '+'}
                      </a>
                    </div>
                    <div className='flex flex-col items-start'>
                      <p className='text-gray-500 font-sansbold text-md md:text-xl px-12'>
                        {item.question}
                      </p>

                      <p
                        className={`text-xl gray-500 font-quote text-md md:text-lg px-12 ${
                          open ? 'block' : 'hidden'
                        }`}>
                        {item.answer}
                      </p>
                    </div>
                  </div>
                </div>
              </>
            ))}
          </div>
</code>```

When the state is true, it also displays a '-' in place of where the '+' was until clicked again to set to false (hide the answer).

Thanks in advance!

答:
You could keep an array with all the revealed questions. Once a question gets revealed, you add that question to the array.</p>
```<code>const [revealedQuestions, setReveleadQuestions] = useState([]);

// Receives the question as a string and checks if its in the array
const toggleAnswer = (question) => {
    // if its in the array, then remove it
    if(revealedQuestions.includes(question)){
         var index = revealedQuestions.indexOf(value);
         if (index > -1) {
             setReveleadQuestions(revealedQuestions.splice(index, 1));
         }
    }
    // if not in the array, then add it to the array
    else {
         setReveleadQuestions([...revealedQuestions, question]);
    }
}

{results[0].data.glossary_boxes.map((item, i) => (
     <div key={i}>
         // if the question is in the array show '-' else show '+'
         <a onClick={() => toggleAnswer(item.question)} >
             {revealedQuestions.includes(item.question) ? '-' : '+'}
         </a>
         <p>
             {item.question}
         </p>
         // if the question is in the array, show the answer
         {revealedQuestions.includes(item.question) && (
             <p>{item.answer}</p>
         )}
    </div>
)}
</code>```

Body:
I have an array of questions that I'm mapping through and displaying them in the UI, there is about 70+ questions.

Each question has a '+' button that reveals an answer when clicked, I want to reveal the answer using state but only for the specific question that is clicked, not the entire list. Currently I have it so when a button is clicked, it reveals all 70+ answers, what's the best way to do this so it only reveals one?

This is my code:

  const [open, setOpen] = useState(false);

            {results[0].data.glossary_boxes.map((item, i) => (
              <>

                       setOpen(!open)}
                        className='text-white text-3xl cursor-pointer'>
                        {open ? '-' : '+'}

                        {item.question}

                        {item.answer}

              </>
            ))}

When the state is true, it also displays a '-' in place of where the '+' was until clicked again to set to false (hide the answer).

Thanks in advance!

Body:
You could keep an array with all the revealed questions. Once a question gets revealed, you add that question to the array.

const [revealedQuestions, setReveleadQuestions] = useState([]);

// Receives the question as a string and checks if its in the array
const toggleAnswer = (question) => {
    // if its in the array, then remove it
    if(revealedQuestions.includes(question)){
         var index = revealedQuestions.indexOf(value);
         if (index > -1) {
             setReveleadQuestions(revealedQuestions.splice(index, 1));
         }
    }
    // if not in the array, then add it to the array
    else {
         setReveleadQuestions([...revealedQuestions, question]);
    }
}

{results[0].data.glossary_boxes.map((item, i) => (
     <div key={i}>
         // if the question is in the array show '-' else show '+'
         <a onClick={() => toggleAnswer(item.question)} >
             {revealedQuestions.includes(item.question) ? '-' : '+'}
         </a>
         <p>
             {item.question}
         </p>
         // if the question is in the array, show the answer
         {revealedQuestions.includes(item.question) && (
             <p>{item.answer}</p>
         )}
    </div>
)}


问:
When using Remix Ethereum get Error types/value length mismatch (previously run was ok.)
creation of meatFarm errored: Error encoding arguments: Error: types/values length mismatch (count={"types":2,"values":4}, value={"types":["address","address"],"values":["0xd9145CCE52D386f254917e481eB44e9943F39138","0xd8b934580fcE35a11B58C6D73aDeE468a2833fa8","",""]}, code=INVALID_ARGUMENT, version=abi/5.5.0)

i encounter above error which require 4 values but types is only 2. wondering what have I missing.

```<code>pragma solidity ^0.8.4;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract meatFarm {

    mapping(address => uint256[]) public stakingBalance;
    mapping(address => bool) public isStaking;
    mapping(address => uint256) public startTime;
    mapping(address => uint256) public meatBalance;

    string public name = "MeatFarm";

    IERC721 public cdnoToken;
    IERC20 public meatToken;

    event Stake(address indexed from, uint256 indexed);
    event Unstake(address indexed from, uint256 indexed);
    event YieldWithdraw(address indexed to, uint256 amount);

    constructor(
        IERC721 _cdnoToken,
        IERC20 _meatToken
        ) {
            cdnoToken = _cdnoToken;
            meatToken = _meatToken;
        }
}
</code>```

答: Not code probelm is remix version updated bugged!</p>

Body:
creation of meatFarm errored: Error encoding arguments: Error: types/values length mismatch (count={"types":2,"values":4}, value={"types":["address","address"],"values":["0xd9145CCE52D386f254917e481eB44e9943F39138","0xd8b934580fcE35a11B58C6D73aDeE468a2833fa8","",""]}, code=INVALID_ARGUMENT, version=abi/5.5.0)

i encounter above error which require 4 values but types is only 2. wondering what have I missing.

pragma solidity ^0.8.4;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract meatFarm {

    mapping(address => uint256[]) public stakingBalance;
    mapping(address => bool) public isStaking;
    mapping(address => uint256) public startTime;
    mapping(address => uint256) public meatBalance;

    string public name = "MeatFarm";

    IERC721 public cdnoToken;
    IERC20 public meatToken;

    event Stake(address indexed from, uint256 indexed);
    event Unstake(address indexed from, uint256 indexed);
    event YieldWithdraw(address indexed to, uint256 amount);

    constructor(
        IERC721 _cdnoToken,
        IERC20 _meatToken
        ) {
            cdnoToken = _cdnoToken;
            meatToken = _meatToken;
        }
}


问:
Django Registration - Checks if a user already exists
The web app currently should be able to register new users. However, should a user already exists, it should redirect user to the login page with a message of "User already exists!".

The Django views:

from django.contrib.auth.models import User

def registerPage(request):
     form = CreateUserForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            username = form.cleaned_data['username']
            if User.objects.filter(username=username).exists():
                messages.info(
                    request, 'User already exists! Try logging in.')
                return redirect('login')
            else:
                user = form.save(commit=False)
                raw_password = User.objects.make_random_password()
                user.set_password(raw_password)
                user.save()
                ...
```

I filter the user by his/her username and checks if it already exists by using the exists() method. This doesn't seem to work though. Is there something I'm missing?

UPDATE

What's not working is that the check I believe is not working. Because if it successfully checks that a user exists, then it should redirect('login') instead of running the else statement.

SOLUTION

Turns out that because I'm using Django's built in CreateUserForm and is doing validation using form.is_valid(), hence it is already built in for Django to check whether the user already exists or not. So what I did was to just add an else statement after the if form.is_valid() and redirect my user to the login page.

答: username already marked unique=True in auth/models.py so simply you can use try/catch.

Body:
The web app currently should be able to register new users. However, should a user already exists, it should redirect user to the login page with a message of "User already exists!".

The Django views:

from django.contrib.auth.models import User

def registerPage(request):
     form = CreateUserForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            username = form.cleaned_data['username']
            if User.objects.filter(username=username).exists():
                messages.info(
                    request, 'User already exists! Try logging in.')
                return redirect('login')
            else:
                user = form.save(commit=False)
                raw_password = User.objects.make_random_password()
                user.set_password(raw_password)
                user.save()
                ...

I filter the user by his/her username and checks if it already exists by using the exists() method. This doesn't seem to work though. Is there something I'm missing?

UPDATE

What's not working is that the check I believe is not working. Because if it successfully checks that a user exists, then it should redirect('login') instead of running the else statement.

SOLUTION

Turns out that because I'm using Django's built in CreateUserForm and is doing validation using form.is_valid(), hence it is already built in for Django to check whether the user already exists or not. So what I did was to just add an else statement after the if form.is_valid() and redirect my user to the login page.


问:
Selecting specific column value with condition
I want to get a specific column from User table in yii2 using active record below is my code

```<code>$model = User::findOne(['id' => 1]);
</code>```

this will return all  the column from the table with user id equal 1, but suppose i just want to get only username and email from this column how do i write the query with active record, i tried the below code but it wont work..`

```<code>$model = User::find('username','email')->where('id'=1)
</code>```

答:
If you need Model User, try this:

```<code>$user = User::find()
           ->select('column1, column2')
           ->where(['id' => $id])
           ->one();
</code>```

For getting few columns without Model use this:

```<code>$columns = User::find()
           ->select('column1, column2')
           ->where(['id' => $id])
           ->asArray()
           ->one();
</code>```

If you need single column without Model, use this:

```<code>$column = User::find()
           ->select('column1')
           ->where(['id' => $id])
           ->column();
</code>```

OR

```<code>$column = User::find()
           ->select('column1')
           ->where(['id' => $id])
           ->scalar();
</code>```

Body:
I want to get a specific column from User table in yii2 using active record below is my code

$model = User::findOne(['id' => 1]);

this will return all  the column from the table with user id equal 1, but suppose i just want to get only username and email from this column how do i write the query with active record, i tried the below code but it wont work..`

$model = User::find('username','email')->where('id'=1)

Body:
If you need Model User, try this:

$user = User::find()
           ->select('column1, column2')
           ->where(['id' => $id])
           ->one();

For getting few columns without Model use this:

$columns = User::find()
           ->select('column1, column2')
           ->where(['id' => $id])
           ->asArray()
           ->one();

If you need single column without Model, use this:

$column = User::find()
           ->select('column1')
           ->where(['id' => $id])
           ->column();

OR

$column = User::find()
           ->select('column1')
           ->where(['id' => $id])
           ->scalar();


问:
What is the trick for swap_pointers to work?
I am doing an exercise where the task is to fix swap_pointer().

Two string should be swapped.

```<code>s1 = "I should print second.";
s2 = "I should print first.";
</code>```

My work so far:

```<code>#include <stdio.h>

void swap_nums(int *, int *);
void swap_pointers(char *x, char *y);

int main(void) {

    int a = 3, b = 4;
    char *s1, *s2;

    swap_nums(&a, &b);

    printf("a is %d\n", a);
    printf("b is %d\n", b);

    s1 = "I should be printed second.";
    s2 = "I should be printed first.";

    /* swap_pointers(s1, s2); */

    printf("s1 is %s\n", s1);
    printf("s2 is %s\n", s2);

    return 0;
}

void swap_nums(int *x, int *y) {

    int tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}

void swap_pointers(char *x, char *y) {

    char tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}
</code>```

I think that not appending & to s1 and s2 before I pass them to the function for swap_pointers is the error?

If anyone can fix my issue here, please don't give the whole solution! I want to use what you give me as a tool to fix it by my own. If I really can't fix it by my own I will adress this later.

Ty in advance!

答:
Your pass the pointers to the first characters of two null-terminated strings to the swap_pointers function.

Inside the function, when you use e.g. *x it's the same as x[0].

So you're swapping the first character of x with the first character of y.

If you want to switch pointers, you need to emulate pass-by-reference like you do with swap_nums, and pass pointers to the pointers, i.e. char **. And use the pointer-to operator & in the call.

So it should be

```<code>void swap_ponters(char **x, char **y);
</code>```

and

```<code>swap_pointers(&s1, &s2);
</code>```

Body:
I am doing an exercise where the task is to fix swap_pointer().

Two string should be swapped.

s1 = "I should print second.";
s2 = "I should print first.";

My work so far:

#include <stdio.h>

void swap_nums(int *, int *);
void swap_pointers(char *x, char *y);

int main(void) {

    int a = 3, b = 4;
    char *s1, *s2;

    swap_nums(&a, &b);

    printf("a is %d\n", a);
    printf("b is %d\n", b);

    s1 = "I should be printed second.";
    s2 = "I should be printed first.";

    /* swap_pointers(s1, s2); */

    printf("s1 is %s\n", s1);
    printf("s2 is %s\n", s2);

    return 0;
}

void swap_nums(int *x, int *y) {

    int tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}

void swap_pointers(char *x, char *y) {

    char tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}

I think that not appending & to s1 and s2 before I pass them to the function for swap_pointers is the error?

If anyone can fix my issue here, please don't give the whole solution! I want to use what you give me as a tool to fix it by my own. If I really can't fix it by my own I will adress this later.

Ty in advance!

Body:
Your pass the pointers to the first characters of two null-terminated strings to the swap_pointers function.

Inside the function, when you use e.g. *x it's the same as x[0].

So you're swapping the first character of x with the first character of y.

If you want to switch pointers, you need to emulate pass-by-reference like you do with swap_nums, and pass pointers to the pointers, i.e. char **. And use the pointer-to operator & in the call.

So it should be

void swap_ponters(char **x, char **y);

and

swap_pointers(&s1, &s2);


问:
long time cron in App Engine
I want to rewrite a webapp to Python and to use App Engine but I have several cron scripts that can be long running. Some time ago I used App Engine and wanted to know if there are now methods to run these scripts because App Engine has its limits.
If you want to get an idea of one of the scripts there is one that calculates the karma users based on what has been done on the website, so there are mathematical calculations, many executions SQL... and can take much time.

Thanks!

答:
If it's just the scheduling scripts that you're asking about, then there is cron for App Engine, for both Python and Java

Edit: you can now use Google Cloud SQL with Google App Engine

Title: long time cron in App Engine


问:
find with multiple greps
I need to find lines of code after malloc that does not contain the word null,
so that I can understand if the malloc was properly checked or not.

For example the following lines should be printed:

```<code>obj = (boolean *) malloc(DAYS_IN_WEEK * sizeof(boolean));
    for(int i = 0; i < DAYS_IN_WEEK; i++){
</code>```

This command partially works since it prints out the lines containing malloc

```<code>find . -type f -name '*.c' \( -exec grep -HnA2 'malloc' {}  \;
</code>```

should I add another grep? Not sure how to do it.

答:
There must be something easier but this seems close:

```<code>find . -name "*.c" -exec grep -nHA1 malloc {} \; |
   awk '/^--/ {next} /malloc/{f=1; p=$0; next} f==1 && !/NULL/{f=0; print p; print $0}'
</code>```

Explanation:

/^---/ {next} ignores all lines starting with dashes that grep generates

/malloc/{f=1;p=$0;next} sets a flag f if the line contains malloc then remembers the line in p and moves to the next

f=1... checks if the flag is set (i.e. the previous line contained malloc) and the current line doesn't contain NULL, and if so, prints the previous and current lines

Title: find with multiple greps

Body:
I need to find lines of code after malloc that does not contain the word null,
so that I can understand if the malloc was properly checked or not.

For example the following lines should be printed:

obj = (boolean *) malloc(DAYS_IN_WEEK * sizeof(boolean));
    for(int i = 0; i < DAYS_IN_WEEK; i++){

This command partially works since it prints out the lines containing malloc

find . -type f -name '*.c' \( -exec grep -HnA2 'malloc' {}  \;

should I add another grep? Not sure how to do it.

Body:
There must be something easier but this seems close:

find . -name "*.c" -exec grep -nHA1 malloc {} \; |
   awk '/^--/ {next} /malloc/{f=1; p=$0; next} f==1 && !/NULL/{f=0; print p; print $0}'

Explanation:

/^---/ {next} ignores all lines starting with dashes that grep generates

/malloc/{f=1;p=$0;next} sets a flag f if the line contains malloc then remembers the line in p and moves to the next

f=1... checks if the flag is set (i.e. the previous line contained malloc) and the current line doesn't contain NULL, and if so, prints the previous and current lines


问:
Is there a way to get all combinations of overlap between values in dictionary, or from within a list
I have a few lists

```<code>A =['D','KIT','SAP'],
B= ['F','G','LUFT','SAP'],
C= ['I','SAP'],
D= ['SAP','LUF','KIT'],
F= ['SAP','LUF','KIT','HASS']
</code>```

I passed them in combinations to a dictionary. For example, I joined lists A and B as a key 'AB' in my new dictionary and appended the values from both lists like the list of values to that key 'AB'.

```<code>my_dict={"AB":[['D','KIT','SAP'],['F','G','LUFT','SAP']]}
</code>```

My aim to get the overlap between the lists in multiple combination. For that, I could get with the following one liner.

```<code>   for k,v in my_dict.items():
        print(k,list(set.intersection(*[set(x) for x in v])))
</code>```

AB ['SAP']

However, the problem here is that when I have more lists and more combinations it is tedious to define manually a dictionary with all possible combinations.

The aim is to achieve all possible combinations of lists. From the above-mentioned example, I have the following combination of lists. In this case that would be 5*5 +1 = 26 combinations. And in the end, I would like to get the overlap for each of the following combinations.

```<code>   AB, AC, AD, AF
    ABC, ABD, ABF
    ABCD, ABCDF
    ABCDF
BC, BD, BF
DF, DC
FC
</code>```

The question is how could I achieve that in a pythonic way. Any suggestions are much appreciated.

As a side note, I do not want a dictionary in between if this combination of overlap is possible from the lists itself.

Thanks

答:
Have a look at itertools.combinations. It returns all possible combinations of a given length for a given iterable. You'll have to loop over all possible lengths.

```<code>import itertools

lists = [A, B, C, D, E, F]

combinations = []

for l in range(2, len(lists) + 1):
    combinations += itertools.combinations(lists, l)
</code>```

combinations will be a list of tuples with all possible combinations of at least two lists.

Body:
I have a few lists

A =['D','KIT','SAP'],
B= ['F','G','LUFT','SAP'],
C= ['I','SAP'],
D= ['SAP','LUF','KIT'],
F= ['SAP','LUF','KIT','HASS']

I passed them in combinations to a dictionary. For example, I joined lists A and B as a key 'AB' in my new dictionary and appended the values from both lists like the list of values to that key 'AB'.

my_dict={"AB":[['D','KIT','SAP'],['F','G','LUFT','SAP']]}

My aim to get the overlap between the lists in multiple combination. For that, I could get with the following one liner.

   for k,v in my_dict.items():
        print(k,list(set.intersection(*[set(x) for x in v])))

AB ['SAP']

However, the problem here is that when I have more lists and more combinations it is tedious to define manually a dictionary with all possible combinations.

The aim is to achieve all possible combinations of lists. From the above-mentioned example, I have the following combination of lists. In this case that would be 5*5 +1 = 26 combinations. And in the end, I would like to get the overlap for each of the following combinations.

   AB, AC, AD, AF
    ABC, ABD, ABF
    ABCD, ABCDF
    ABCDF
BC, BD, BF
DF, DC
FC

The question is how could I achieve that in a pythonic way. Any suggestions are much appreciated.

As a side note, I do not want a dictionary in between if this combination of overlap is possible from the lists itself.

Thanks

Body:
Have a look at itertools.combinations. It returns all possible combinations of a given length for a given iterable. You'll have to loop over all possible lengths.

import itertools

lists = [A, B, C, D, E, F]

combinations = []

for l in range(2, len(lists) + 1):
    combinations += itertools.combinations(lists, l)

combinations will be a list of tuples with all possible combinations of at least two lists.