问:
pydantic: Using property.getter decorator for a field with an alias
scroll all the way down for a tl;dr, I provide context which I think is important but is not directly relevant to the question asked

A bit of context

I'm in the making of an API for a webapp and some values are computed based on the values of others in a pydantic BaseModel. These are used for user validation, data serialization and definition of database (NoSQL) documents.

Specifically, I have nearly all resources inheriting from a OwnedResource class, which defines, amongst irrelevant other properties like creation/last-update dates:

object_key -- The key of the object using a nanoid of length 6 with a custom alphabet

owner_key -- This key references the user that owns that object -- a nanoid of length 10.

_key -- this one is where I'm bumping into some problems, and I'll explain why.

So arangodb -- the database I'm using -- imposes _key as the name of the property by which resources are identified.

Since, in my webapp, all resources are only accessed by the users who created them, they can be identified in URLs with just the object's key (eg. /subject/{object_key}). However, as _key must be unique, I intend to construct the value of this field using f"{owner_key}/{object_key}", to store the objects of every user in the database and potentially allow for cross-user resource sharing in the future.

The goal is to have the shortest per-user unique identifier, since the owner_key part of the full _key used to actually access and act upon the document stored in the database is always the same: the currently-logged-in user's _key.

My attempt

My thought was then to define the _key field as a @property-decorated function in the class. However, Pydantic does not seem to register those as model fields.

Moreover, the attribute must actually be named key and use an alias (with Field(... alias="_key"), as pydantic treats underscore-prefixed fields as internal and does not expose them.

Here is the definition of OwnedResource:

class OwnedResource(BaseModel):
    """
    Base model for resources owned by users
    """

    object_key: ObjectBareKey = nanoid.generate(ID_CHARSET, OBJECT_KEY_LEN)
    owner_key: UserKey
    updated_at: Optional[datetime] = None
    created_at: datetime = datetime.now()

    @property
    def key(self) -> ObjectKey:
        return objectkey(self.owner_key)

    class Config:
        fields = {"key": "_key"} # [1]
```
<p>[1] Since Field(..., alias="...") cannot be used, I use this property of the Config subclass (see pydantic's documentation)</p>
<p>However, this does not work, as shown in the following example:</p>
<pre class="lang-py prettyprint-override"><code>@router.post("/subjects/")
def create_a_subject(subject: InSubject):
    print(subject.dict(by_alias=True))
</code>```

with InSubject defining properties proper to Subject, and Subject being an empty class inheriting from both InSubject and OwnedResource:

class InSubject(BaseModel):
    name: str
    color: Color
    weight: Union[PositiveFloat, Literal[0]] = 1.0
    goal: Primantissa # This is just a float constrained in a [0, 1] range
    room: str

class Subject(InSubject, OwnedResource):
    pass
```
<p>When I perform a <code>POST /subjects/</code>, the following is printed in the console:</p>
<pre class="lang-py prettyprint-override"><code>{'name': 'string', 'color': Color('cyan', rgb=(0, 255, 255)), 'weight': 0, 'goal': 0.0, 'room': 'string'}
</code>```

As you can see, _key or key are nowhere to be seen.

Please ask for details and clarification, I tried to make this as easy to understand as possible, but I'm not sure if this is clear enough.

tl;dr

A context-less and more generic example without insightful context:

With the following class:

from pydantic import BaseModel

class SomeClass(BaseModel):

    spam: str

    @property
    def eggs(self) -> str:
        return self.spam + " bacon"

    class Config:
        fields = {"eggs": "_eggs"}
```
<p>I would like the following to be true:</p>
<pre class="lang-py prettyprint-override"><code>a = SomeClass(spam="I like")
d = a.dict(by_alias=True)
d.get("_eggs") == "I like bacon"
</code>```

答:
You might be able to serialize your _key field using a pydantic validator with the always option set to True.

Using your example:

```<code>from typing import Optional
from pydantic import BaseModel, Field, validator

class SomeClass(BaseModel):

    spam: str
    eggs: Optional[str] = Field(alias="_eggs")

    @validator("eggs", always=True)
    def set_eggs(cls, v, values, **kwargs):
        """Set the eggs field based upon a spam value."""
        return v or values.get("spam") + " bacon"

a = SomeClass(spam="I like")
my_dictionary = a.dict(by_alias=True)
print(my_dictionary)
> {'spam': 'I like', '_eggs': 'I like bacon'}
print(my_dictionary.get("_eggs"))
> "I like bacon"
</code>```

So to serialize your _eggs field, instead of appending a string, you'd insert your serialization function there and return the output of that.

Body:
scroll all the way down for a tl;dr, I provide context which I think is important but is not directly relevant to the question asked

A bit of context

I'm in the making of an API for a webapp and some values are computed based on the values of others in a pydantic BaseModel. These are used for user validation, data serialization and definition of database (NoSQL) documents.

Specifically, I have nearly all resources inheriting from a OwnedResource class, which defines, amongst irrelevant other properties like creation/last-update dates:

object_key -- The key of the object using a nanoid of length 6 with a custom alphabet

owner_key -- This key references the user that owns that object -- a nanoid of length 10.

_key -- this one is where I'm bumping into some problems, and I'll explain why.

So arangodb -- the database I'm using -- imposes _key as the name of the property by which resources are identified.

Since, in my webapp, all resources are only accessed by the users who created them, they can be identified in URLs with just the object's key (eg. /subject/{object_key}). However, as _key must be unique, I intend to construct the value of this field using f"{owner_key}/{object_key}", to store the objects of every user in the database and potentially allow for cross-user resource sharing in the future.

The goal is to have the shortest per-user unique identifier, since the owner_key part of the full _key used to actually access and act upon the document stored in the database is always the same: the currently-logged-in user's _key.

My attempt

My thought was then to define the _key field as a @property-decorated function in the class. However, Pydantic does not seem to register those as model fields.

Moreover, the attribute must actually be named key and use an alias (with Field(... alias="_key"), as pydantic treats underscore-prefixed fields as internal and does not expose them.

Here is the definition of OwnedResource:

class OwnedResource(BaseModel):
    """
    Base model for resources owned by users
    """

    object_key: ObjectBareKey = nanoid.generate(ID_CHARSET, OBJECT_KEY_LEN)
    owner_key: UserKey
    updated_at: Optional[datetime] = None
    created_at: datetime = datetime.now()

    @property
    def key(self) -> ObjectKey:
        return objectkey(self.owner_key)

    class Config:
        fields = {"key": "_key"} # [1]

[1] Since Field(..., alias="...") cannot be used, I use this property of the Config subclass (see pydantic's documentation)

However, this does not work, as shown in the following example:

@router.post("/subjects/")
def create_a_subject(subject: InSubject):
    print(subject.dict(by_alias=True))

with InSubject defining properties proper to Subject, and Subject being an empty class inheriting from both InSubject and OwnedResource:

class InSubject(BaseModel):
    name: str
    color: Color
    weight: Union[PositiveFloat, Literal[0]] = 1.0
    goal: Primantissa # This is just a float constrained in a [0, 1] range
    room: str

class Subject(InSubject, OwnedResource):
    pass

When I perform a POST /subjects/, the following is printed in the console:

{'name': 'string', 'color': Color('cyan', rgb=(0, 255, 255)), 'weight': 0, 'goal': 0.0, 'room': 'string'}

As you can see, _key or key are nowhere to be seen.

Please ask for details and clarification, I tried to make this as easy to understand as possible, but I'm not sure if this is clear enough.

tl;dr

A context-less and more generic example without insightful context:

With the following class:

from pydantic import BaseModel

class SomeClass(BaseModel):

    spam: str

    @property
    def eggs(self) -> str:
        return self.spam + " bacon"

    class Config:
        fields = {"eggs": "_eggs"}

I would like the following to be true:

a = SomeClass(spam="I like")
d = a.dict(by_alias=True)
d.get("_eggs") == "I like bacon"

Body:
You might be able to serialize your _key field using a pydantic validator with the always option set to True.

Using your example:

from typing import Optional
from pydantic import BaseModel, Field, validator

class SomeClass(BaseModel):

    spam: str
    eggs: Optional[str] = Field(alias="_eggs")

    @validator("eggs", always=True)
    def set_eggs(cls, v, values, **kwargs):
        """Set the eggs field based upon a spam value."""
        return v or values.get("spam") + " bacon"

a = SomeClass(spam="I like")
my_dictionary = a.dict(by_alias=True)
print(my_dictionary)
> {'spam': 'I like', '_eggs': 'I like bacon'}
print(my_dictionary.get("_eggs"))
> "I like bacon"

So to serialize your _eggs field, instead of appending a string, you'd insert your serialization function there and return the output of that.


来源: stackexchange

问:
React - Updating state (array of objects). Do I need to deep copy the array?
I have the following state:

```<code>const[images,setImages] = useState([
  {src: 'stringSRC1', selected: false},
  {src: 'stringSRC2', selected: false},
  {src: 'stringSRC3', selected: false}
]);
</code>```

I'm updating it (toggling selected state) with this code:

```<code>function handleImageClick(index) {
  props.setImages((prevState)=>{
    const aux = Array.from(prevState);
    aux[index].selected = !aux[index].selected;
    return aux;
  });
}
</code>```

It works as intended. But I've thought of one thing.

When I'm copying the array from prevState, I'm creating a new array, but the objects (stored as references) will remain the same. I've tested and they do not change when you copy the array like that.

QUESTION

Is this a bad practice? Should I bother to deep copy the array, as in create a new array and create brand new objects? Or this is just fine?

答:
TL;DR - You still need to make deep copies.

The official docs recommend making deep copies:

State can hold any kind of JavaScript value, including objects. But you shouldn’t change objects that you hold in the React state directly. Instead, when you want to update an object, you need to create a new one (or make a copy of an existing one), and then set the state to use that copy.

They also suggest making your state objects as flat as possible to make deep copying easier and if that's not an option, using something like immer to handle the deep-copying for you.

If your state is deeply nested, you might want to consider flattening it. But, if you don’t want to change your state structure, you might prefer a shortcut to nested spreads. Immer is a popular library that lets you write using the convenient but mutating syntax and takes care of producing the copies for you.

ContentLicense: CC BY-SA 4.0

Body:
I have the following state:

const[images,setImages] = useState([
  {src: 'stringSRC1', selected: false},
  {src: 'stringSRC2', selected: false},
  {src: 'stringSRC3', selected: false}
]);

I'm updating it (toggling selected state) with this code:

function handleImageClick(index) {
  props.setImages((prevState)=>{
    const aux = Array.from(prevState);
    aux[index].selected = !aux[index].selected;
    return aux;
  });
}

It works as intended. But I've thought of one thing.

When I'm copying the array from prevState, I'm creating a new array, but the objects (stored as references) will remain the same. I've tested and they do not change when you copy the array like that.

QUESTION

Is this a bad practice? Should I bother to deep copy the array, as in create a new array and create brand new objects? Or this is just fine?


问:
Kotlin: Is there a tool that allows me to control parallelism when executing suspend functions?
I'm trying to execute certain suspend function multiple times, in such a way that never more than N of these are being executed at the same time.

For those acquainted with Akka and Scala Streaming libraries, something like mapAsync.

I did my own implementation using one input channel (as in kotlin channels) and N output channels. But it seems cumbersome and not very efficient.

The code I'm currently using is somewhat like this:

val inChannel = Channel<T>()
val outChannels = (0..n).map{
  Channel<T>()
}
launch{
   var i = 0
   for(t in inChannel){

     outChannels[i].offer(t)
     i = ((i+1)%n)
   }
}
outChannels.forEach{outChannel ->
  launch{
     for(t in outChannel){
        fn(t)
     }
  }
}
```
<p>Of course it has error management and everything, but still...</p>
<p>Edit: I did the following test, and it failed.</p>
<pre class="lang-kotlin prettyprint-override"><code>test("Parallelism is correctly capped") {
            val scope = CoroutineScope(Dispatchers.Default.limitedParallelism(3))
            var num = 0
            (1..100).map {
                scope.launch {
                    num ++
                    println("started $it")
                    delay(Long.MAX_VALUE)
                }
            }

            delay(500)
            assertEquals(3,num)

        }
</code>```

答:
Your question, as asked, calls for @marstran's answer. If what you want is that no more than N coroutines are being actively executed at any given time (in parallel), then limitedParallelism is the way to go:

val maxThreads: Int = TODO("some max number of threads")
val limitedDispatcher = Dispatchers.Default.limitedParallelism(maxThreads)

elements.forEach { elt ->
    scope.launch(limitedDispatcher) {
        doSomething(elt)
    }
}
```
<p>Now, if what you want is to even limit <em>concurrency</em>, so that at most N coroutines are run concurrently (potentially interlacing), regardless of threads, you could use a Semaphore instead:</p>
<pre class="lang-kotlin prettyprint-override"><code>val maxConcurrency: Int = TODO("some max number of concurrency coroutines")
val semaphore = Semaphore(maxConcurrency)

elements.forEach { elt ->
    scope.async {
        semaphore.withPermit {
            doSomething(elt)
        }
    }
}
</code>```

You can also combine both approaches.

Body:
I'm trying to execute certain suspend function multiple times, in such a way that never more than N of these are being executed at the same time.

For those acquainted with Akka and Scala Streaming libraries, something like mapAsync.

I did my own implementation using one input channel (as in kotlin channels) and N output channels. But it seems cumbersome and not very efficient.

The code I'm currently using is somewhat like this:

val inChannel = Channel<T>()
val outChannels = (0..n).map{
  Channel<T>()
}
launch{
   var i = 0
   for(t in inChannel){

     outChannels[i].offer(t)
     i = ((i+1)%n)
   }
}
outChannels.forEach{outChannel ->
  launch{
     for(t in outChannel){
        fn(t)
     }
  }
}

Of course it has error management and everything, but still...

Edit: I did the following test, and it failed.

test("Parallelism is correctly capped") {
            val scope = CoroutineScope(Dispatchers.Default.limitedParallelism(3))
            var num = 0
            (1..100).map {
                scope.launch {
                    num ++
                    println("started $it")
                    delay(Long.MAX_VALUE)
                }
            }

            delay(500)
            assertEquals(3,num)

        }

Body:
Your question, as asked, calls for @marstran's answer. If what you want is that no more than N coroutines are being actively executed at any given time (in parallel), then limitedParallelism is the way to go:

val maxThreads: Int = TODO("some max number of threads")
val limitedDispatcher = Dispatchers.Default.limitedParallelism(maxThreads)

elements.forEach { elt ->
    scope.launch(limitedDispatcher) {
        doSomething(elt)
    }
}

Now, if what you want is to even limit concurrency, so that at most N coroutines are run concurrently (potentially interlacing), regardless of threads, you could use a Semaphore instead:

val maxConcurrency: Int = TODO("some max number of concurrency coroutines")
val semaphore = Semaphore(maxConcurrency)

elements.forEach { elt ->
    scope.async {
        semaphore.withPermit {
            doSomething(elt)
        }
    }
}

You can also combine both approaches.


问:
OVS Flows - Ping working, other traffic not
Could someone kindly explain why the following flow config (these flows are the only flows on the bridge) does not work as expected ?

I can ping the hosts on each side, but other traffic (e.g. web/ssh etc. does not pass).

```<code>ovs-ofctl add-flow xl1 dl_type=0x800,nw_src=10.2.0.0/20,nw_dst=10.2.1.0/24,actions=output:73
ovs-ofctl add-flow xl1 dl_type=0x800,nw_src=10.2.0.0/20,nw_dst=10.2.2.0/24,actions=output:76
ovs-ofctl add-flow xl1 arp,nw_dst=10.2.1.0/24,actions=output:73
ovs-ofctl add-flow xl1 arp,nw_dst=10.2.2.0/24,actions=output:76
</code>```

The traces certainly seem to suggest the traffic should pass:

```<code>ovs-appctl ofproto/trace xl1 in_port=73,tcp,nw_src=10.
2.1.1,nw_dst=10.2.2.1,tcp_dst=22
Bridge: xl1
Flow: tcp,metadata=0,in_port=73,vlan_tci=0x0000,dl_src=00:00:00:00:00:00,dl_dst=00:00:00:00:00:00,nw_src=10.2.1.1,nw_dst=10.2.2.1,nw_tos=0,nw_ecn=0,nw_ttl=0,tp_src=0,tp_dst=22,tcp_flags=0x000
Rule: table=0 cookie=0 ip,nw_src=10.2.0.0/20,nw_dst=10.2.2.0/24
OpenFlow actions=output:76

Final flow: unchanged
Megaflow: skb_priority=0,ip,in_port=73,nw_src=10.2.0.0/20,nw_dst=10.2.2.1,nw_frag=no
Datapath actions: 76

ovs-appctl ofproto/trace xl1 in_port=76,tcp,nw_src=10.
2.2.1,nw_dst=10.2.1.1,tcp_dst=22
Bridge: xl1
Flow: tcp,metadata=0,in_port=76,vlan_tci=0x0000,dl_src=00:00:00:00:00:00,dl_dst=00:00:00:00:00:00,nw_src=10.2.2.1,nw_dst=10.2.1.1,nw_tos=0,nw_ecn=0,nw_ttl=0,tp_src=0,tp_dst=22,tcp_flags=0x000
Rule: table=0 cookie=0 ip,nw_src=10.2.0.0/20,nw_dst=10.2.1.0/24
OpenFlow actions=output:73

Final flow: unchanged
Megaflow: skb_priority=0,ip,in_port=76,nw_src=10.2.0.0/20,nw_dst=10.2.1.1,nw_frag=no
Datapath actions: 73
</code>```

答:
One issue is that,
10.2.1.0/24 and 10.2.2.0/24 are not in the same network.
So, if a host, like 10.10.1.1 is looking for 2.0. It may not send out an arp for 2.0. It may send out an arp for its own gateway in the 1.0 network.
You can use this command:

arp -n

on the hosts on 1.0 network to look into the arp table of these hosts.
You can also use:

tcpdump -i "eth-name"

on the openvSwitch to see what you can get if you are sending out a non-icmp packet on 1.0 or 2.0 network.

Body:
Could someone kindly explain why the following flow config (these flows are the only flows on the bridge) does not work as expected ?

I can ping the hosts on each side, but other traffic (e.g. web/ssh etc. does not pass).

ovs-ofctl add-flow xl1 dl_type=0x800,nw_src=10.2.0.0/20,nw_dst=10.2.1.0/24,actions=output:73
ovs-ofctl add-flow xl1 dl_type=0x800,nw_src=10.2.0.0/20,nw_dst=10.2.2.0/24,actions=output:76
ovs-ofctl add-flow xl1 arp,nw_dst=10.2.1.0/24,actions=output:73
ovs-ofctl add-flow xl1 arp,nw_dst=10.2.2.0/24,actions=output:76

The traces certainly seem to suggest the traffic should pass:

ovs-appctl ofproto/trace xl1 in_port=73,tcp,nw_src=10.
2.1.1,nw_dst=10.2.2.1,tcp_dst=22
Bridge: xl1
Flow: tcp,metadata=0,in_port=73,vlan_tci=0x0000,dl_src=00:00:00:00:00:00,dl_dst=00:00:00:00:00:00,nw_src=10.2.1.1,nw_dst=10.2.2.1,nw_tos=0,nw_ecn=0,nw_ttl=0,tp_src=0,tp_dst=22,tcp_flags=0x000
Rule: table=0 cookie=0 ip,nw_src=10.2.0.0/20,nw_dst=10.2.2.0/24
OpenFlow actions=output:76

Final flow: unchanged
Megaflow: skb_priority=0,ip,in_port=73,nw_src=10.2.0.0/20,nw_dst=10.2.2.1,nw_frag=no
Datapath actions: 76

ovs-appctl ofproto/trace xl1 in_port=76,tcp,nw_src=10.
2.2.1,nw_dst=10.2.1.1,tcp_dst=22
Bridge: xl1
Flow: tcp,metadata=0,in_port=76,vlan_tci=0x0000,dl_src=00:00:00:00:00:00,dl_dst=00:00:00:00:00:00,nw_src=10.2.2.1,nw_dst=10.2.1.1,nw_tos=0,nw_ecn=0,nw_ttl=0,tp_src=0,tp_dst=22,tcp_flags=0x000
Rule: table=0 cookie=0 ip,nw_src=10.2.0.0/20,nw_dst=10.2.1.0/24
OpenFlow actions=output:73

Final flow: unchanged
Megaflow: skb_priority=0,ip,in_port=76,nw_src=10.2.0.0/20,nw_dst=10.2.1.1,nw_frag=no
Datapath actions: 73


问:
trying to find Prime numbers in an array
I'm wanting to remove the non-prime numbers from an Array, the following is only removing the even numbers instead of the prime numbers.

```<code>function sumPrimes(num) {
  //Produce an array containing all number of to and including num
  let numArray = [];
  for (let i = 1; i <= num; i++) {
    numArray.push(i);
  }

  //Remove non-prime numbers from the array
  numArray.map((number) => {
    for (let i = 2; i < number; i++) {
        if(number % i === 0) {
            let index = numArray.indexOf(number);
            return numArray.splice(index, 1);
        }
    }
  });

 return numArray;

}

sumPrimes(10);
</code>```

This is currently returning:

```<code>[1, 2, 3, 5, 7, 9]
</code>```

However, prime numbers are 1, 2, 3, 5, 7 (not include 9);

答:
My solution for find prime numbers in an  array in javascript using forEach().

let num = [-1,-2,-3,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
let result = [];
function isPrime(num) {
  if(num < 2) return false;

  for (let k = 2; k < num; k++){
    if(num % k == 0){
      return false;
    }
  }
  return true;
}
num.forEach(function (element) {
  const item = isPrime(element);
  if (item) {
    result.push(element);
  }
});
console.log(result); // [ 2, 3, 5, 7, 11, 13, 17, 19]```

ContentLicense: CC BY-SA 3.0

Body:
I'm wanting to remove the non-prime numbers from an Array, the following is only removing the even numbers instead of the prime numbers.

function sumPrimes(num) {
  //Produce an array containing all number of to and including num
  let numArray = [];
  for (let i = 1; i <= num; i++) {
    numArray.push(i);
  }

  //Remove non-prime numbers from the array
  numArray.map((number) => {
    for (let i = 2; i < number; i++) {
        if(number % i === 0) {
            let index = numArray.indexOf(number);
            return numArray.splice(index, 1);
        }
    }
  });

 return numArray;

}

sumPrimes(10);

This is currently returning:

[1, 2, 3, 5, 7, 9]

However, prime numbers are 1, 2, 3, 5, 7 (not include 9);


问:
how to use Date instead dateComponents swift
I'm very new to the world of programming. I've started work as intern, where I need to learn Swift. I have an exercise to create a class of soccer players.

I have this code below and I'm using DateComponents to get the birthday, there is a way to just use the Date instead?
I was told to convert the Date to DateComponents but I couldn't figure it out.

Here's the code I tried:

```<code>let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
dateFormater.string(from: birthday)
</code>```

But I can't define the Date in my object

```<code>import UIKit
import Darwin
import Foundation
class SoccerPlayer {
    let name: String
    var position: String
    var birthday: DateComponents
    let nationality: String
    var height: Double
    var weight: Int
    init(name: String, position: String, birthday: DateComponents, nationality: String, height: Double, weight: Int) {
        self.name = name
        self.position = position
        self.birthday = birthday
        self.nationality = nationality
        self.height = height
        self.weight = weight
    }
    func printInfo() {
        let printOut: String = "name:\(name), position:\(position), birthday:\(birthday), nationality:\(nationality),height:\(height),weight:\(weight)"
        print(printOut)
    }
    func calculationAge() -> Int {
        let calendar = Calendar.current
        let now = calendar.dateComponents([.year, .month, .day], from: Date())
        let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
        let age = ageComponents.year!
        return age
    }
    func calculateRetire() -> Int {
        var yearsToRetire = 0
        if (self.position == "defense") {
            yearsToRetire = 40 - self.calculationAge()
        }
        else if(self.position == "halfField") {
            yearsToRetire = 38 - self.calculationAge()
        }
        else if(self.position == "attacker") {
            yearsToRetire = 35 - self.calculationAge()
        }
        return yearsToRetire
    }
}
enum PlayerPosition: String {
    case attacker = "Attacker"
    case halfField = "HalfField"
    case defense = "Defense"
    var description: String {
        get {
            return self.rawValue
        }
    }
}

var player1: SoccerPlayer = SoccerPlayer(name: "Andre", position: PlayerPosition.defense.description, birthday: DateComponents(year: 1998, month: 7, day: 1), nationality: "Brazilian", height: 1.70, weight: 70)

        player1.printInfo()
</code>```

It prints:

name:Andre, position:Defense, birthday:year: 1998 month: 7 day: 1 isLeapMonth: false , nationality:Brazilian,height:1.7,weight:70

答:
If you need to create a date using date components you need to pass the calendar component as well:

```<code>DateComponents(calendar: Calendar(identifier: .iso8601), year: 1998, month: 7, day: 1).date!
</code>```

Besides that there is many points to improve in your code. Position property should be your existing enumeration. You can move the age calculation method to an instance computed property of Date. I would also create a DateFormatter to display the birthday. Note also that if you would like to create a custom description to the player you can make it conform to CustomStringConvertible and it already does when you add a description to your model/class.

You would need to add those extensions to your project:

```<code>extension Formatter {
    static let birthday: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = .current
        formatter.locale = .init(identifier: "pt_BR") // or en_US or current if you want to localize your date description
        formatter.setLocalizedDateFormatFromTemplate("MMMMd")  // if you would like to include the year use yyyyMMMMd
        return formatter
    }()
}
</code>```

```<code>extension Date {
    var age: Int {
        Calendar(identifier: .iso8601).dateComponents([.year], from: self, to: Date()).year ?? .zero
    }
    var birthday: String {
        Formatter.birthday.string(from: self)
    }
}
</code>```

And your code should look something like:

```<code>class SoccerPlayer {
    let name: String
    var position: Position
    var dob: Date
    let nationality: String
    var height: Double
    var weight: Int
    init(name: String, position: Position, dob: Date, nationality: String, height: Double, weight: Int) {
        self.name = name
        self.position = position
        self.dob = dob
        self.nationality = nationality
        self.height = height
        self.weight = weight
    }
    var yearsToRetire: Int {
        switch position {
        case .defense:
            return 40 - dob.age
        case .halfField:
            return 38 - dob.age
        case .attacker:
            return 35 - dob.age
        }
    }
}
</code>```

```<code>extension SoccerPlayer: CustomStringConvertible {
    var description: String {
        "Name: \(name), Position: \(position), Birthday: \(dob.birthday), Nationality: \(nationality), Height: \(height), Weight: \(weight)"
    }
}
</code>```

```<code>extension SoccerPlayer {
    enum Position: String {
        case attacker, halfField, defense
    }
}
</code>```

```<code>extension SoccerPlayer.Position: CustomStringConvertible {
    var description: String { rawValue.capitalized }
}
</code>```

Usage:

```<code>let player1Dob = DateComponents(calendar: Calendar(identifier: .iso8601), year: 1998, month: 7, day: 1).date!
var player1: SoccerPlayer = .init(
    name: "Andre",
    position: .defense,
    dob: player1Dob,
    nationality: "Brazilian",
    height: 1.7,
    weight: 70
)
player1.yearsToRetire  // 17
print(player1)
</code>```

This will print:

Name: Andre, Position: Defense, Birthday: 1 de julho, Nationality: Brazilian, Height: 1.7, Weight: 70

Body:
I'm very new to the world of programming. I've started work as intern, where I need to learn Swift. I have an exercise to create a class of soccer players.

I have this code below and I'm using DateComponents to get the birthday, there is a way to just use the Date instead?
I was told to convert the Date to DateComponents but I couldn't figure it out.

Here's the code I tried:

let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
dateFormater.string(from: birthday)

But I can't define the Date in my object

import UIKit
import Darwin
import Foundation
class SoccerPlayer {
    let name: String
    var position: String
    var birthday: DateComponents
    let nationality: String
    var height: Double
    var weight: Int
    init(name: String, position: String, birthday: DateComponents, nationality: String, height: Double, weight: Int) {
        self.name = name
        self.position = position
        self.birthday = birthday
        self.nationality = nationality
        self.height = height
        self.weight = weight
    }
    func printInfo() {
        let printOut: String = "name:\(name), position:\(position), birthday:\(birthday), nationality:\(nationality),height:\(height),weight:\(weight)"
        print(printOut)
    }
    func calculationAge() -> Int {
        let calendar = Calendar.current
        let now = calendar.dateComponents([.year, .month, .day], from: Date())
        let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
        let age = ageComponents.year!
        return age
    }
    func calculateRetire() -> Int {
        var yearsToRetire = 0
        if (self.position == "defense") {
            yearsToRetire = 40 - self.calculationAge()
        }
        else if(self.position == "halfField") {
            yearsToRetire = 38 - self.calculationAge()
        }
        else if(self.position == "attacker") {
            yearsToRetire = 35 - self.calculationAge()
        }
        return yearsToRetire
    }
}
enum PlayerPosition: String {
    case attacker = "Attacker"
    case halfField = "HalfField"
    case defense = "Defense"
    var description: String {
        get {
            return self.rawValue
        }
    }
}

var player1: SoccerPlayer = SoccerPlayer(name: "Andre", position: PlayerPosition.defense.description, birthday: DateComponents(year: 1998, month: 7, day: 1), nationality: "Brazilian", height: 1.70, weight: 70)

        player1.printInfo()

It prints:

name:Andre, position:Defense, birthday:year: 1998 month: 7 day: 1 isLeapMonth: false , nationality:Brazilian,height:1.7,weight:70

Body:
If you need to create a date using date components you need to pass the calendar component as well:

DateComponents(calendar: Calendar(identifier: .iso8601), year: 1998, month: 7, day: 1).date!

Besides that there is many points to improve in your code. Position property should be your existing enumeration. You can move the age calculation method to an instance computed property of Date. I would also create a DateFormatter to display the birthday. Note also that if you would like to create a custom description to the player you can make it conform to CustomStringConvertible and it already does when you add a description to your model/class.

You would need to add those extensions to your project:

extension Formatter {
    static let birthday: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = .current
        formatter.locale = .init(identifier: "pt_BR") // or en_US or current if you want to localize your date description
        formatter.setLocalizedDateFormatFromTemplate("MMMMd")  // if you would like to include the year use yyyyMMMMd
        return formatter
    }()
}

extension Date {
    var age: Int {
        Calendar(identifier: .iso8601).dateComponents([.year], from: self, to: Date()).year ?? .zero
    }
    var birthday: String {
        Formatter.birthday.string(from: self)
    }
}

And your code should look something like:

class SoccerPlayer {
    let name: String
    var position: Position
    var dob: Date
    let nationality: String
    var height: Double
    var weight: Int
    init(name: String, position: Position, dob: Date, nationality: String, height: Double, weight: Int) {
        self.name = name
        self.position = position
        self.dob = dob
        self.nationality = nationality
        self.height = height
        self.weight = weight
    }
    var yearsToRetire: Int {
        switch position {
        case .defense:
            return 40 - dob.age
        case .halfField:
            return 38 - dob.age
        case .attacker:
            return 35 - dob.age
        }
    }
}

extension SoccerPlayer: CustomStringConvertible {
    var description: String {
        "Name: \(name), Position: \(position), Birthday: \(dob.birthday), Nationality: \(nationality), Height: \(height), Weight: \(weight)"
    }
}

extension SoccerPlayer {
    enum Position: String {
        case attacker, halfField, defense
    }
}

extension SoccerPlayer.Position: CustomStringConvertible {
    var description: String { rawValue.capitalized }
}

Usage:

let player1Dob = DateComponents(calendar: Calendar(identifier: .iso8601), year: 1998, month: 7, day: 1).date!
var player1: SoccerPlayer = .init(
    name: "Andre",
    position: .defense,
    dob: player1Dob,
    nationality: "Brazilian",
    height: 1.7,
    weight: 70
)
player1.yearsToRetire  // 17
print(player1)

This will print:

Name: Andre, Position: Defense, Birthday: 1 de julho, Nationality: Brazilian, Height: 1.7, Weight: 70


问:
Show more logs in kubernetes dashboard
I am using the official kubernetes dashboard in Version kubernetesui/dashboard:v2.4.0 to manage my cluster and I've noticed that, when I select a pod and look into the logs, the length of the displayed logs is quite short. It's like 50 lines or something?

If an exception occurs, the logs are pretty much useless because the original cause is hidden by lots of other lines. I would have to download the logs or shell to the kubernetes server and use kubectl logs in order to see whats going on.

Is there any way to configure the dashboard in a way so that more lines of logs get displayed?

答: If anyone is interested: As the feature that i was looking for does not exist yet, i have submitted a feature request in GitHub. You can see it here: https://github.com/kubernetes/dashboard/issues/6700</p>

Title: Show more logs in kubernetes dashboard


问:
IIS and .NET 5 ASP.NET MVC 5 App, HttpsRedirect not working outside IIS Server
I have an ASP.NET Core 5 MVC app, running fine on a IIS 10 server.

I've been asked to enable HTTPS and enforce it on port 6443. I have been given the certificate and configured it on IIS.

When going into Chrome locally on the server and going to http://localhost, you get correctly redirected to https://localhost:6443

Binding is configured:

Certificate is ok and locally it works.

When from another location in the network i visit the ip address of the server, if I visit it in https, it works.

If I visit in http, I get this chrome error:

ERR_CONNECTION_REFUSED, check connection or proxy.

This does not make any sense, before enabling https, it was working fine on http:80, and locally, the redirection works.

This is how it's done in code (Startup.cs):

```<code>public void Configure(IApplicationBuilder app)
{
     if (appOptions.HttpsRedirectionEnabled)
     {
         app.UseHttpsRedirection();
     }

     // The default HSTS value is 30 days. You may want to change
     // this for production scenarios, see https://aka.ms/aspnetcore-hsts.
     app.UseHsts();
}
</code>```

and

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpsRedirection(options =>
                {
                    options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
                    options.HttpsPort = 6443;
                });
}
</code>```

Also, visiting https://serverip seems to not work aswell, kinda like redirecting on 443 instead of 6443. So I get it working only locally.

I don't want to install any url rewrite stuff, this has to work normally.

What config I am missing on IIS or whatever else?

EDIT: been asked to add trace from chrome dev tools, here it is:

More detailed trace

Chrome hsts section:

But querying this finds stuff

答:
As discussed in the comments, the browser had cached an HSTS response for the server, telling it to always request the secure version of the site. As per RFC 6797, this will only ever redirect to port 443.

Disabling the HSTS headers and clearing the cached response from Chrome (using the chrome://net-internals/#hsts settings page) resolved the issue.

Body:
I have an ASP.NET Core 5 MVC app, running fine on a IIS 10 server.

I've been asked to enable HTTPS and enforce it on port 6443. I have been given the certificate and configured it on IIS.

When going into Chrome locally on the server and going to http://localhost, you get correctly redirected to https://localhost:6443

Binding is configured:

Certificate is ok and locally it works.

When from another location in the network i visit the ip address of the server, if I visit it in https, it works.

If I visit in http, I get this chrome error:

ERR_CONNECTION_REFUSED, check connection or proxy.

This does not make any sense, before enabling https, it was working fine on http:80, and locally, the redirection works.

This is how it's done in code (Startup.cs):

public void Configure(IApplicationBuilder app)
{
     if (appOptions.HttpsRedirectionEnabled)
     {
         app.UseHttpsRedirection();
     }

     // The default HSTS value is 30 days. You may want to change
     // this for production scenarios, see https://aka.ms/aspnetcore-hsts.
     app.UseHsts();
}

and

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpsRedirection(options =>
                {
                    options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
                    options.HttpsPort = 6443;
                });
}

Also, visiting https://serverip seems to not work aswell, kinda like redirecting on 443 instead of 6443. So I get it working only locally.

I don't want to install any url rewrite stuff, this has to work normally.

What config I am missing on IIS or whatever else?

EDIT: been asked to add trace from chrome dev tools, here it is:

More detailed trace

Chrome hsts section:

But querying this finds stuff


问:
How to display loading message during the execution of my function?
Some functions take a long time to execute. I want to make the user wait with a progress bar.
Unfortunately, when I run this one, it runs but only at the end of my function and not when I would like.
Let me explain, I launch my progress bar with the "sendloading()" method but during my tests this bar is only displayed after the processing of the other functions "copyAssets" or "createOnClicBtnInsert()".
Can someone explain to me why?

Here is my code :

```<code> @Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    view.findViewById(R.id.btnInsertDataset2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(!hasPermissions(getContext(),Permissions)){
                lay_dataset2 = view.findViewById(R.id.lay_dataset2);
                messagePerm();
            }else {
                sendLoading(); //MY PROGRESS BAR
                btnInsert = view.findViewById(R.id.btnInsertDataset2);
                /** if perm ok -> insert*/
                copyAssets();
                createOnClicBtnInsert();
                view.findViewById(R.id.btnDeleteDataset2).setEnabled(true);
                Toast.makeText(getContext(), "Insert Success", Toast.LENGTH_SHORT).show();
            }

        }
    });
}
</code>```

Here is my code for the progress bar :

```<code>    public void sendLoading() {
    int llPadding = 30;
    LinearLayout ll = new LinearLayout(getContext());
    ll.setOrientation(LinearLayout.HORIZONTAL);
    ll.setPadding(llPadding, llPadding, llPadding, llPadding);
    ll.setGravity(Gravity.CENTER);
    LinearLayout.LayoutParams llParam = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    llParam.gravity = Gravity.CENTER;
    ll.setLayoutParams(llParam);

    ProgressBar progressBar = new ProgressBar(getContext());
    progressBar.setIndeterminate(true);
    progressBar.setPadding(0, 0, llPadding, 0);
    progressBar.setLayoutParams(llParam);

    llParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    llParam.gravity = Gravity.CENTER;
    TextView tvText = new TextView(getContext());
    tvText.setText("Loading ...");
    tvText.setTextColor(Color.parseColor("#000000"));
    tvText.setTextSize(20);
    tvText.setLayoutParams(llParam);

    ll.addView(progressBar);
    ll.addView(tvText);

    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setCancelable(true);
    builder.setView(ll);

    AlertDialog dialog = builder.create();
    dialog.show();
    Window window = dialog.getWindow();
    if (window != null) {
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.copyFrom(dialog.getWindow().getAttributes());
        layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
        layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(layoutParams);
    }

}
</code>```

答:
You should use an AsyncTask to execute your task in a separated Thread and update the progressbar in the UI thread. Here below a short example of it:</p>
```<code>private class VeryLongTask extends AsyncTask<String, Integer, String> {

    private final Context context;

    public VeryLongTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {
        for (int i = 0; i < 255; i++) {
            // do your long task;
            // in this simple example is made by 255 iteraction
            if (anErrorOccured()) return "ERROR";
            publishProgress(i);
        }
        return "OK";
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Initialize your progressbar to zero
        yourSetProgressMethod(0);
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        yourSetProgressMethod(progress[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        if (getActivity() != null) {
            if (result != null)
                Toast.makeText(context, result, Toast.LENGTH_LONG).show();
            }
        }
    }
}
</code>```

Body:
Some functions take a long time to execute. I want to make the user wait with a progress bar.
Unfortunately, when I run this one, it runs but only at the end of my function and not when I would like.
Let me explain, I launch my progress bar with the "sendloading()" method but during my tests this bar is only displayed after the processing of the other functions "copyAssets" or "createOnClicBtnInsert()".
Can someone explain to me why?

Here is my code :

 @Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    view.findViewById(R.id.btnInsertDataset2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(!hasPermissions(getContext(),Permissions)){
                lay_dataset2 = view.findViewById(R.id.lay_dataset2);
                messagePerm();
            }else {
                sendLoading(); //MY PROGRESS BAR
                btnInsert = view.findViewById(R.id.btnInsertDataset2);
                /** if perm ok -> insert*/
                copyAssets();
                createOnClicBtnInsert();
                view.findViewById(R.id.btnDeleteDataset2).setEnabled(true);
                Toast.makeText(getContext(), "Insert Success", Toast.LENGTH_SHORT).show();
            }

        }
    });
}

Here is my code for the progress bar :

    public void sendLoading() {
    int llPadding = 30;
    LinearLayout ll = new LinearLayout(getContext());
    ll.setOrientation(LinearLayout.HORIZONTAL);
    ll.setPadding(llPadding, llPadding, llPadding, llPadding);
    ll.setGravity(Gravity.CENTER);
    LinearLayout.LayoutParams llParam = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    llParam.gravity = Gravity.CENTER;
    ll.setLayoutParams(llParam);

    ProgressBar progressBar = new ProgressBar(getContext());
    progressBar.setIndeterminate(true);
    progressBar.setPadding(0, 0, llPadding, 0);
    progressBar.setLayoutParams(llParam);

    llParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    llParam.gravity = Gravity.CENTER;
    TextView tvText = new TextView(getContext());
    tvText.setText("Loading ...");
    tvText.setTextColor(Color.parseColor("#000000"));
    tvText.setTextSize(20);
    tvText.setLayoutParams(llParam);

    ll.addView(progressBar);
    ll.addView(tvText);

    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setCancelable(true);
    builder.setView(ll);

    AlertDialog dialog = builder.create();
    dialog.show();
    Window window = dialog.getWindow();
    if (window != null) {
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.copyFrom(dialog.getWindow().getAttributes());
        layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
        layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(layoutParams);
    }

}

Body:
You should use an AsyncTask to execute your task in a separated Thread and update the progressbar in the UI thread. Here below a short example of it:

private class VeryLongTask extends AsyncTask<String, Integer, String> {

    private final Context context;

    public VeryLongTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {
        for (int i = 0; i < 255; i++) {
            // do your long task;
            // in this simple example is made by 255 iteraction
            if (anErrorOccured()) return "ERROR";
            publishProgress(i);
        }
        return "OK";
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Initialize your progressbar to zero
        yourSetProgressMethod(0);
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        yourSetProgressMethod(progress[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        if (getActivity() != null) {
            if (result != null)
                Toast.makeText(context, result, Toast.LENGTH_LONG).show();
            }
        }
    }
}


问:
FormControl from Material UI React
hi
What's special about FormControl from Material UI? Does it mean that child element is controlled?</p>
```<code><FormControl>
  <InputLabel htmlFor="my-input">Email address</InputLabel>
  <Input id="my-input" aria-describedby="my-helper-text" />
</FormControl>
</code>```

答:
If you use FormControl you can pass some props like error and it's gonna make styles for all children we need to show error. You don't have to make styles for every child it's enough to pass some prop to FormControl.
Thnx to Francesco Cipolla for examples

Title: FormControl from Material UI React

Body:
hi
What's special about FormControl from Material UI? Does it mean that child element is controlled?

<FormControl>
  <InputLabel htmlFor="my-input">Email address</InputLabel>
  <Input id="my-input" aria-describedby="my-helper-text" />
</FormControl>


问:
Swift: understanding pointers
I'm trying to create a CoreGraphics Context using the following MacOS Quartz API:

CGContext.init?(_ url: CFURL,
                mediaBox: UnsafePointer<CGRect>?,
                _ auxiliaryInfo: CFDictionary?)
```
<p>, but I'm having trouble with the concept of pointers. I can initiate the context thus:</p>
```var mypointer: UnsafeMutablePointer<CGRect>!
mypointer.pointee = myCGRectangle
var writeContext = CGContext.init(outURL, mediaBox: mypointer, nil)
```
<p>But it says that <code>pointee</code> is a get-only property. I've tried:</p>
```var mypointer: UnsafePointer<CGRect>! = UnsafePointer(myCGRectangle)
```

, based on this, but I get cannot convert CGRect to expected type, amongst other errors.

I have looked at several other questions here about pointers, but I can't find anything useful within them.

答:
Just pass a reference to your myCGRectangle variable, this will create the needed UnsafeMutablePointer:

var writeContext = CGContext(outURL, mediaBox: &myCGRectangle, nil)
```

Make sure the rectangle variable is declared as var, otherwise the & won't work.

More details can be found on this excellent Apple documentation page about passing pointers to functions that require ones.

Title: Swift: understanding pointers

Body:
I'm trying to create a CoreGraphics Context using the following MacOS Quartz API:

CGContext.init?(_ url: CFURL,
                mediaBox: UnsafePointer<CGRect>?,
                _ auxiliaryInfo: CFDictionary?)

, but I'm having trouble with the concept of pointers. I can initiate the context thus:

var mypointer: UnsafeMutablePointer<CGRect>!
mypointer.pointee = myCGRectangle
var writeContext = CGContext.init(outURL, mediaBox: mypointer, nil)

But it says that pointee is a get-only property. I've tried:

var mypointer: UnsafePointer<CGRect>! = UnsafePointer(myCGRectangle)

, based on this, but I get cannot convert CGRect to expected type, amongst other errors.

I have looked at several other questions here about pointers, but I can't find anything useful within them.

Body:
Just pass a reference to your myCGRectangle variable, this will create the needed UnsafeMutablePointer:

var writeContext = CGContext(outURL, mediaBox: &myCGRectangle, nil)

Make sure the rectangle variable is declared as var, otherwise the & won't work.

More details can be found on this excellent Apple documentation page about passing pointers to functions that require ones.


问:
check duration of audio files on the command-line
I need to check the duration of a group of audio files.
Is there a simple way to do this on the unix command-line?

```<code>> duration *
</code>```

I have the amazing SoX app which has an option called stats that generates a set of audio info including duration. I am looking for a way to get only duration.
I am flexible on output format, could be any of sample length, hh:mm:ss, or seconds.
The latter would be my preference.

答:
Very simple single-liner for FLAC on Debian/Ubuntu, useful for almost any audio container files and SoX:

```<code>for i in *.flac ; do echo -ne "${i} - " ; soxi -d "${i}" ;  done
</code>```

Also

```<code>soxi -V
</code>```

could be used instead, but then you will need sed or awk and grep to turn the output in the compact form.

Body:
I need to check the duration of a group of audio files.
Is there a simple way to do this on the unix command-line?

> duration *

I have the amazing SoX app which has an option called stats that generates a set of audio info including duration. I am looking for a way to get only duration.
I am flexible on output format, could be any of sample length, hh:mm:ss, or seconds.
The latter would be my preference.

Body:
Very simple single-liner for FLAC on Debian/Ubuntu, useful for almost any audio container files and SoX:

for i in *.flac ; do echo -ne "${i} - " ; soxi -d "${i}" ;  done

Also

soxi -V

could be used instead, but then you will need sed or awk and grep to turn the output in the compact form.


问:
How to mock StorageOptions.newBuilder()
Can you help me in mocking StorageOptions.newBuilder()

Code to be Mocked:

```<code>StorageOptions.newBuilder.setProjectId("Test").build().getService()
</code>```

Code I have written:

```<code>Storage mockStorage = Mockito.mock(Storage.class);

MockedStatic<StorageOptions> storageOptionsMock = Mockito.mockStorage(StorageOptions.class);
storageOptionsMock.when( ()-> StorageOptions.newBuilder().setProjectId("Test").build().getService()).thenReturn(mockStorage);

</code>```

Error:

```<code>org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Storage$MockitoMock$1939527098 cannot be returned by newBuilder()
newBuilder() should return Builder
</code>```

答:
Since you are chaining a lot of method calls, you can use Mockito.RETURNS_DEEP_STUBS to instruct Mockito to return all the required intermediate stubs/mocks.

Storage mockStorage = Mockito.mock(Storage.class);
MockedStatic<StorageOptions> storageOptionsMock =
    Mockito.mockStatic(StorageOptions.class, Mockito.RETURNS_DEEP_STUBS);

storageOptionsMock.when(()->
    StorageOptions.newBuilder()
                  .setProjectId("Test")
                  .build()
                  .getService())
.thenReturn(mockStorage);

assertThat(StorageOptions.newBuilder()
    .setProjectId("Test")
    .build()
    .getService())
.isEqualTo(mockStorage);
```

But since this is considered an anti pattern, you may want to refactor your code to avoid this.

Title: How to mock StorageOptions.newBuilder()

Body:
Can you help me in mocking StorageOptions.newBuilder()

Code to be Mocked:

StorageOptions.newBuilder.setProjectId("Test").build().getService()

Code I have written:

Storage mockStorage = Mockito.mock(Storage.class);

MockedStatic<StorageOptions> storageOptionsMock = Mockito.mockStorage(StorageOptions.class);
storageOptionsMock.when( ()-> StorageOptions.newBuilder().setProjectId("Test").build().getService()).thenReturn(mockStorage);

Error:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Storage$MockitoMock$1939527098 cannot be returned by newBuilder()
newBuilder() should return Builder

Body:
Since you are chaining a lot of method calls, you can use Mockito.RETURNS_DEEP_STUBS to instruct Mockito to return all the required intermediate stubs/mocks.

Storage mockStorage = Mockito.mock(Storage.class);
MockedStatic<StorageOptions> storageOptionsMock =
    Mockito.mockStatic(StorageOptions.class, Mockito.RETURNS_DEEP_STUBS);

storageOptionsMock.when(()->
    StorageOptions.newBuilder()
                  .setProjectId("Test")
                  .build()
                  .getService())
.thenReturn(mockStorage);

assertThat(StorageOptions.newBuilder()
    .setProjectId("Test")
    .build()
    .getService())
.isEqualTo(mockStorage);

But since this is considered an anti pattern, you may want to refactor your code to avoid this.


问:
Couple of questions about .htaccess and friendly urls
I've always been bad at apache and used very simple solutions. Right now I have built a cms software.. but the .htaccess is starting to be a huge downsize.

I will first explain, how my friendly-urls work and look like. My language-switch is url based and always contains two characters. And it looks like this: stackoverflow.com/en/ this makes the switching really easy and since its url based.. it works well in the SEO terms. Also, if no language-id is set, then the default language will be used (stackoverflow.com/).

There are no page-ids in numbers. I have unique page-ids in text: stackoverflow.com/services.html and for SEO and folder-directories-anti-conflict purposes .html at the end..

For subpages I have "$current_page" and "$parent_page" style variables: stackoverflow.com/services/translating.html Services being the parent and translating being the current page.

Some sample code too (I nerfed it alot, so you don't think its incomplete):

```<code>RewriteRule ^(et|en|fi)\/(.+)\/(.+)\.html  index.php?language=$1&pagelink=$3&parentlink=$2 [L,NC,QSA]

RewriteRule ^(.+)\/(.+)\.html  index.php?language=0&pagelink=$2&parentlink=$1 [L,NC,QSA]
RewriteRule ^(.+)\.html  index.php?language=0&pagelink=$1&parentlink=0 [L,NC,QSA]
</code>```

How can I make the language-switch part more dynamic?

This method ..^(et|en|fi)\/.. means, that when I set up the cms, I must manually set the languages list. Best bet would be to set it somehow from the cms settings. Because, this way there are no conflicts related to folders. Is it possible global apace variable via php and then display it the .htaccess file? Something like this: ..^(LANGUAGELISTS)\/..? If this isn't possible, then next best thing would be to match 2 characters in that location and pass it as $_GET['language'].

How can I have unlimited parents dynamically?

Meaning, that the "$parent_page" is not set statically and I have unlimited children, similar to this: stackoverflow.com/services/translating/english/somesubpage.html. If that is possible, then also, how will it be used in the php, with an array?

Bounty edit

First part of the question is basically solved, unless somebody comes up with some php -> apache-array -> .htaccess way.

However, the second part of the question is still not solved. Since this is been the problem with all my projects and could possibly help somebody else in the future, I decided to add bounty to this question.

答:
To answer your first question:
You could use RewriteRule ^([a-zA-Z]{2})([/]?)(.*)$ path/file.php?language=$1
This limits the first string to two characters and passes it on to $_GET['language']

Edit: adding RewriteCond %{REQUEST_FILENAME} !-f
and RewriteCond %{REQUEST_FILENAME} !-d will prevent conflicts with existing directories / files

Second question is much more difficult..

Update:

What Shad and toopay say is a good start in my opinion.
Using explode() to seperate levels and comparing it to the slug is quite simple.
But it's getting complicated once you want to add flexibility to the script.

```<code>function get_URL_items() {
$get_URL_items_url = $_SERVER['REQUEST_URI'];
$get_URL_items_vars = explode("/",$get_URL_items_url);
for ($get_URL_items_i = 0; $get_URL_items_i < count($get_URL_items_vars) ; $get_URL_items_i++) {
    if(strlen(trim($get_URL_items_vars[$get_URL_items_i])) == 0) {
        unset($get_URL_items_vars[$get_URL_items_i]);
    }
}
return $get_URL_items_vars;
</code>```

Let's say you you've got a website with a sub-section called "Festival" and a database filled with info for 100+ artist and you want your URLs to look like website.com/festival/<artistgenre>/<artistname>/.
You don't want to create 100+ pages in your CMS so <artistgenre> and <artistname> are some kind of wildcards.

I found it hard to achieve this without a lot of if/else statements like:

```<code>$item = get_URL_items();
if(is_user($item[2]) && is_genre($item[1]) && is_festival($item[0])) {
  // do mysql stuff here
}
</code>```

Body:
I've always been bad at apache and used very simple solutions. Right now I have built a cms software.. but the .htaccess is starting to be a huge downsize.

I will first explain, how my friendly-urls work and look like. My language-switch is url based and always contains two characters. And it looks like this: stackoverflow.com/en/ this makes the switching really easy and since its url based.. it works well in the SEO terms. Also, if no language-id is set, then the default language will be used (stackoverflow.com/).

There are no page-ids in numbers. I have unique page-ids in text: stackoverflow.com/services.html and for SEO and folder-directories-anti-conflict purposes .html at the end..

For subpages I have "$current_page" and "$parent_page" style variables: stackoverflow.com/services/translating.html Services being the parent and translating being the current page.

Some sample code too (I nerfed it alot, so you don't think its incomplete):

RewriteRule ^(et|en|fi)\/(.+)\/(.+)\.html  index.php?language=$1&pagelink=$3&parentlink=$2 [L,NC,QSA]

RewriteRule ^(.+)\/(.+)\.html  index.php?language=0&pagelink=$2&parentlink=$1 [L,NC,QSA]
RewriteRule ^(.+)\.html  index.php?language=0&pagelink=$1&parentlink=0 [L,NC,QSA]

How can I make the language-switch part more dynamic?

This method ..^(et|en|fi)\/.. means, that when I set up the cms, I must manually set the languages list. Best bet would be to set it somehow from the cms settings. Because, this way there are no conflicts related to folders. Is it possible global apace variable via php and then display it the .htaccess file? Something like this: ..^(LANGUAGELISTS)\/..? If this isn't possible, then next best thing would be to match 2 characters in that location and pass it as $_GET['language'].

How can I have unlimited parents dynamically?

Meaning, that the "$parent_page" is not set statically and I have unlimited children, similar to this: stackoverflow.com/services/translating/english/somesubpage.html. If that is possible, then also, how will it be used in the php, with an array?

Bounty edit

First part of the question is basically solved, unless somebody comes up with some php -> apache-array -> .htaccess way.

However, the second part of the question is still not solved. Since this is been the problem with all my projects and could possibly help somebody else in the future, I decided to add bounty to this question.

Body:
To answer your first question:
You could use RewriteRule ^([a-zA-Z]{2})([/]?)(.*)$ path/file.php?language=$1
This limits the first string to two characters and passes it on to $_GET['language']

Edit: adding RewriteCond %{REQUEST_FILENAME} !-f
and RewriteCond %{REQUEST_FILENAME} !-d will prevent conflicts with existing directories / files

Second question is much more difficult..

Update:

What Shad and toopay say is a good start in my opinion.
Using explode() to seperate levels and comparing it to the slug is quite simple.
But it's getting complicated once you want to add flexibility to the script.

function get_URL_items() {
$get_URL_items_url = $_SERVER['REQUEST_URI'];
$get_URL_items_vars = explode("/",$get_URL_items_url);
for ($get_URL_items_i = 0; $get_URL_items_i < count($get_URL_items_vars) ; $get_URL_items_i++) {
    if(strlen(trim($get_URL_items_vars[$get_URL_items_i])) == 0) {
        unset($get_URL_items_vars[$get_URL_items_i]);
    }
}
return $get_URL_items_vars;

Let's say you you've got a website with a sub-section called "Festival" and a database filled with info for 100+ artist and you want your URLs to look like website.com/festival/<artistgenre>/<artistname>/.
You don't want to create 100+ pages in your CMS so <artistgenre> and <artistname> are some kind of wildcards.

I found it hard to achieve this without a lot of if/else statements like:

$item = get_URL_items();
if(is_user($item[2]) && is_genre($item[1]) && is_festival($item[0])) {
  // do mysql stuff here
}


问:
Python Requests and SSLContext
I'm trying to figure out how to specify an SSLContext with Request.

I have two functions which in theory should do the same, however the one with Requests doesn't work.

```<code>def func_OK(token):
    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='myCA.crt.pem')
    ctx.load_cert_chain(certfile='myprivate.pem')
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    req = urllib.request.Request(url, headers=hdr)
    resp = urllib.request.urlopen(req, data=bdata, context=ctx)
    content = resp.read()
    data = json.loads(content.decode('utf-8'))
</code>```
```<code>def func_NOK(token):
    import requests
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    resp = requests.post(url,headers=hdr, data={"filterList":[{}]})
</code>```

The only the difference between the two functions are the sslContext.
In the func_NOK, I try :

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify=False) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, cert=('myCA.crt.pem','myprivate.pem')) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify="concat_file.crt") with "concat_file.crt" file a concatenation of 'myCA.crt.pem' and 'myprivate.pem'

In any cases I have an SSL error.
For example, on my last example the error msg is :

```<code>requests.exceptions.ConnectionError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1131)
</code>```

I'm just trying to use an SSLContext with Requests.

答:
```<code>ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='myCA.crt.pem')
ctx.load_cert_chain(certfile='myprivate.pem')
</code>```

load_cert_chain loads the cert and private key for use as client certificate - which would be the cert argument with requests. cafile describes the CA it should use to verify the server certificate - which would be the verify argument for requests. Combined this would result in:

```<code>requests.post(..., cert='myprivate.pem', verify='myCA.crt.pem')
</code>```

Title: Python Requests and SSLContext

Body:
I'm trying to figure out how to specify an SSLContext with Request.

I have two functions which in theory should do the same, however the one with Requests doesn't work.

def func_OK(token):
    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='myCA.crt.pem')
    ctx.load_cert_chain(certfile='myprivate.pem')
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    req = urllib.request.Request(url, headers=hdr)
    resp = urllib.request.urlopen(req, data=bdata, context=ctx)
    content = resp.read()
    data = json.loads(content.decode('utf-8'))

def func_NOK(token):
    import requests
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    resp = requests.post(url,headers=hdr, data={"filterList":[{}]})

The only the difference between the two functions are the sslContext.
In the func_NOK, I try :

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify=False) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, cert=('myCA.crt.pem','myprivate.pem')) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify="concat_file.crt") with "concat_file.crt" file a concatenation of 'myCA.crt.pem' and 'myprivate.pem'

In any cases I have an SSL error.
For example, on my last example the error msg is :

requests.exceptions.ConnectionError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1131)

I'm just trying to use an SSLContext with Requests.

Body:
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='myCA.crt.pem')
ctx.load_cert_chain(certfile='myprivate.pem')

load_cert_chain loads the cert and private key for use as client certificate - which would be the cert argument with requests. cafile describes the CA it should use to verify the server certificate - which would be the verify argument for requests. Combined this would result in:

requests.post(..., cert='myprivate.pem', verify='myCA.crt.pem')


问:
R, dplyr split dataframe by string in columns
I've seen examples here that show how to split a dataframe using column index ranges but how do I split my dataframe with dplyr using strings found in the column? I've purposely created my dataframes so the columns have certain strings in them for future splitting.

Example data:

```<code>Site   A_Argas   A_Arachnicea   A_Brus   B_Burkoll   B_Brielle  B_Bact
 1       10        0              0         0           0         0
 2       0         0              0         10          22        123
 3       1         2              3         88          12        546
</code>```

I want to split this dataframe up based on strings such as "A_" or "B_" and assign them to new  dataframes.

For example the output would be:

```<code> dataframeA
 Site   A_Argas   A_Arachnicea   A_Brus
 1       10        0              0
 2       0         0              0
 3       1         2              3

 dataframeB
 Site   B_Burkoll   B_Brielle  B_Bact
  1       0           0         0
  2      10          22        123
  3      88          12        546
</code>```

Because this data is not in long format, I can't seem to figure how to change my old code that I used to split the longform dataframes (for a different analysis).

```<code>dataframeA <- data %>% filter("GroupID" == "Arachnids") # where "A_" in column headers signify arachnid species
dataframeB <- data %>% filter("GroupID" == "Bacteria") # where all "B_" in the column headers are bacterial species
</code>```

答:
Another possible solution, based on group_split, pivot_longer, pivot_wider and map:

library(tidyverse)

df <- structure(list(Site = c(1, 2, 3), A_Argas = c(10, 0, 1), A_Arachnicea = c(0,
0, 2), A_Brus = c(0, 0, 3), B_Burkoll = c(0, 10, 88), B_Brielle = c(0,
22, 12), B_Bact = c(0, 123, 546)), row.names = c(NA, -3L), class = "data.frame")

df %>%
  pivot_longer(-1) %>%
  group_split(str_extract(name, "^[A-Z]\\_")) %>%
  map(~ pivot_wider(.x, id_cols = Site))

#> [[1]]
#> # A tibble: 3 × 4
#>    Site A_Argas A_Arachnicea A_Brus
#>   <dbl>   <dbl>        <dbl>  <dbl>
#> 1     1      10            0      0
#> 2     2       0            0      0
#> 3     3       1            2      3
#>
#> [[2]]
#> # A tibble: 3 × 4
#>    Site B_Burkoll B_Brielle B_Bact
#>   <dbl>     <dbl>     <dbl>  <dbl>
#> 1     1         0         0      0
#> 2     2        10        22    123
#> 3     3        88        12    546
```

Body:
I've seen examples here that show how to split a dataframe using column index ranges but how do I split my dataframe with dplyr using strings found in the column? I've purposely created my dataframes so the columns have certain strings in them for future splitting.

Example data:

Site   A_Argas   A_Arachnicea   A_Brus   B_Burkoll   B_Brielle  B_Bact
 1       10        0              0         0           0         0
 2       0         0              0         10          22        123
 3       1         2              3         88          12        546

I want to split this dataframe up based on strings such as "A_" or "B_" and assign them to new  dataframes.

For example the output would be:

 dataframeA
 Site   A_Argas   A_Arachnicea   A_Brus
 1       10        0              0
 2       0         0              0
 3       1         2              3

 dataframeB
 Site   B_Burkoll   B_Brielle  B_Bact
  1       0           0         0
  2      10          22        123
  3      88          12        546

Because this data is not in long format, I can't seem to figure how to change my old code that I used to split the longform dataframes (for a different analysis).

dataframeA <- data %>% filter("GroupID" == "Arachnids") # where "A_" in column headers signify arachnid species
dataframeB <- data %>% filter("GroupID" == "Bacteria") # where all "B_" in the column headers are bacterial species


问:
if typeOf f == io then f else return . f in Haskell?
Related to

https://stackoverflow.com/a/71020780/17053359

We can lift non-IO functions : f to IO ones with return, as in

```<code>return . f
</code>```

and now, I want to make this f generic including IO

```<code>f :: A -> IO A -- not IO to IO
f :: IO a -> IO a -- (no change, `id` instead of `return`)
</code>```

in other words:

if typeOf f == io then f

else return . f

What would the code be in Haskell?

EDIT:

console.log(
 Object(1)
);

console.log(
 Object(Object(1))
);

console.log(
 Object(Object(Object(1)))
);```

答:
You almost definitely do not actually want to do this. The amount of type level hackery required for this should already scare you away and this is really not how Monads are supposed to be used.

Purely for educational purposes, this is how you could define a function pureish, that behaves just like return if the argument is not of type IO a and just like id if the argument is of type IO a.

type family PureishResult a where
    PureishResult (IO a) = a
    PureishResult a = a

class Pureish p where
    pureish :: p -> IO (PureishResult p)

instance {-# OVERLAPPABLE #-} (PureishResult a ~ a) => Pureish a where
    pureish = pure

instance Pureish (IO a) where
    pureish = id
```

Don't say I didn't warn you!

Body:
Related to

https://stackoverflow.com/a/71020780/17053359

We can lift non-IO functions : f to IO ones with return, as in

return . f

and now, I want to make this f generic including IO

f :: A -> IO A -- not IO to IO
f :: IO a -> IO a -- (no change, `id` instead of `return`)

in other words:

if typeOf f == io then f

else return . f

What would the code be in Haskell?

EDIT:

console.log(
 Object(1)
);

console.log(
 Object(Object(1))
);

console.log(
 Object(Object(Object(1)))
);

Body:
You almost definitely do not actually want to do this. The amount of type level hackery required for this should already scare you away and this is really not how Monads are supposed to be used.

Purely for educational purposes, this is how you could define a function pureish, that behaves just like return if the argument is not of type IO a and just like id if the argument is of type IO a.

type family PureishResult a where
    PureishResult (IO a) = a
    PureishResult a = a

class Pureish p where
    pureish :: p -> IO (PureishResult p)

instance {-# OVERLAPPABLE #-} (PureishResult a ~ a) => Pureish a where
    pureish = pure

instance Pureish (IO a) where
    pureish = id

Don't say I didn't warn you!


问:
Use named scope with has_many_through
I have the following model:

```<code>class Board < ActiveRecord::Base

has_many   :users, :through => :participants do
                 def manager
                     where("participants.role = ?", "Manager").first
                 end
               end
</code>```

This allows me to do the following in my controller and views

```<code>@board.users.manager
</code>```

Is there a way to use a named_scope to be able to get the manager for a board as follows:

```<code>@board.manager
</code>```

答:
Here's a sample solution:</p>

```<code>class Board < ActiveRecord::Base

  has_many   :users, :through => :participants do
    def manager
      where("participants.role = ?", "Manager").first
    end
  end

  delegate :manager, :to => :users

end
</code>```

Title: Use named scope with has_many_through

Body:
I have the following model:

class Board < ActiveRecord::Base

has_many   :users, :through => :participants do
                 def manager
                     where("participants.role = ?", "Manager").first
                 end
               end

This allows me to do the following in my controller and views

@board.users.manager

Is there a way to use a named_scope to be able to get the manager for a board as follows:

@board.manager

Body:
Here's a sample solution:

class Board < ActiveRecord::Base

  has_many   :users, :through => :participants do
    def manager
      where("participants.role = ?", "Manager").first
    end
  end

  delegate :manager, :to => :users

end


问:
How to access the values in nested dictionary sent to django template
I'm sending a nested custom dictionary through my views, that nested dictionary is 'history'

```<code>def update_participation(request,user_id,event_id):
    ev=Event.objects.get(id=event_id)
    data=Participated(user=user_id,event=event_id)
    data.save()
    participated=Participated.objects.filter(user=user_id)
    i=0

    #Declared the dictionary history
    history={}

    #Adding values to dictionary
    for partcipate in participated:
        name=Event.objects.get(id=partcipate.event)
        name1=name.name
        fest=Fest.objects.get(id=name.fest_id.id)
        fest1=fest.name
        clg=College.objects.get(id=fest.clg_id.id).name
        history[i]={'event':name1,'fest':fest1,'college':clg}
        i+=1
    messages.success(request,f'You have registered for {ev.name}')

    #sending the dictionary to template
    return render(request,'webpage/my_events.html',history)
</code>```

Example of dictionary will look

```<code>history={0={'event':'css battle','fest':'verve','college':'jss'},
         1={'event':'code wars','fest':'verve','college':'jss'},
         2={'event':'hangman','fest':'phase shift','college':'bms'}}
</code>```

I'm trying to access the values css battle, verve, jss like

```<code>{%extends 'webpage/base.html'%}
{%block content%}
<h2 style="margin:5px 30px;"><u>My Event History</u></h2>
<div style="margin:50px 0px 0px 270px" class='table'>
    <table border='5'>
        <tr>
            <th>Event</th>
            <th>Fest</th>
            <th>College</th>
        </tr>
        {%for key,value in history.items%}
            <tr>
                <td>{{value.event}}</td>
                <td>{{value.fest}}</td>
                <td>{{value.college}}</td>
            </tr>
        {%endfor%}
    </table>
</div>
{%endblock content%}
</code>```

How am I supposed to iterate through the dictionary?

答:
Aside from some query optimization you can do, you should change your data structure. That makes it easier to access as well. See below:

method.py

   def update_participation(request, user_id, event_id):
        event = Event.objects.get(id=event_id)
        data = Participated(user=user_id, event=event_id)
        data.save()

        participated = Participated.objects.filter(user=user_id)

        history = []
        for partcipate in participated:
            name=Event.objects.get(id=partcipate.event)
            name1=name.name

            fest=Fest.objects.get(id=name.fest_id.id)
            fest1=fest.name

            clg=College.objects.get(id=fest.clg_id.id).name
            history.append({'event':name1,'fest':fest1,'college':clg})

        messages.success(request,f'You have registered for {ev.name}')
        #sending the dictionary to template
        return render(request, 'webpage/my_events.html', context={'history': history})
```
<p>template.html:</p>
<pre class="lang-html prettyprint-override"><code>{% for item in history %}
    <tr>
        <td>{{item.event}}</td>
        <td>{{item.fest}}</td>
        <td>{{item.college}}</td>
    </tr>
{% endfor %}
</code>```

Also, please give your variables proper names instead of name1 and fest1.

Body:
I'm sending a nested custom dictionary through my views, that nested dictionary is 'history'

def update_participation(request,user_id,event_id):
    ev=Event.objects.get(id=event_id)
    data=Participated(user=user_id,event=event_id)
    data.save()
    participated=Participated.objects.filter(user=user_id)
    i=0

    #Declared the dictionary history
    history={}

    #Adding values to dictionary
    for partcipate in participated:
        name=Event.objects.get(id=partcipate.event)
        name1=name.name
        fest=Fest.objects.get(id=name.fest_id.id)
        fest1=fest.name
        clg=College.objects.get(id=fest.clg_id.id).name
        history[i]={'event':name1,'fest':fest1,'college':clg}
        i+=1
    messages.success(request,f'You have registered for {ev.name}')

    #sending the dictionary to template
    return render(request,'webpage/my_events.html',history)

Example of dictionary will look

history={0={'event':'css battle','fest':'verve','college':'jss'},
         1={'event':'code wars','fest':'verve','college':'jss'},
         2={'event':'hangman','fest':'phase shift','college':'bms'}}

I'm trying to access the values css battle, verve, jss like

{%extends 'webpage/base.html'%}
{%block content%}

My Event History

            Event
            Fest
            College

        {%for key,value in history.items%}

                {{value.event}}
                {{value.fest}}
                {{value.college}}

        {%endfor%}

{%endblock content%}

How am I supposed to iterate through the dictionary?

Body:
Aside from some query optimization you can do, you should change your data structure. That makes it easier to access as well. See below:

method.py

   def update_participation(request, user_id, event_id):
        event = Event.objects.get(id=event_id)
        data = Participated(user=user_id, event=event_id)
        data.save()

        participated = Participated.objects.filter(user=user_id)

        history = []
        for partcipate in participated:
            name=Event.objects.get(id=partcipate.event)
            name1=name.name

            fest=Fest.objects.get(id=name.fest_id.id)
            fest1=fest.name

            clg=College.objects.get(id=fest.clg_id.id).name
            history.append({'event':name1,'fest':fest1,'college':clg})

        messages.success(request,f'You have registered for {ev.name}')
        #sending the dictionary to template
        return render(request, 'webpage/my_events.html', context={'history': history})

template.html:

{% for item in history %}
    <tr>
        <td>{{item.event}}</td>
        <td>{{item.fest}}</td>
        <td>{{item.college}}</td>
    </tr>
{% endfor %}

Also, please give your variables proper names instead of name1 and fest1.


问:
Strange TyperError put() missing 1 required positional argument: 'path'
I've been trying to test my PUT method in the following APITestcase:

```<code>    def test_story_delete(self):
    c = APIRequestFactory
    user = User.objects.get(username='test1')
    payload = {'storyName': 'changetest'}
    request = c.put(reverse('storyFunctions',args=[self.room.pk,self.story.pk]), format='json')
    force_authenticate(request,user=user)
</code>```

My URL:

```<code>    path('room/<int:pk>/story/<int:idStory>/adm', APIHstory.as_view(),name='storyFunctions'),
</code>```

And I'm keep receiving this error:

```<code>TypeError: put() missing 1 required positional argument: 'path'
</code>```

I don't understand what is going on because i declared the path inside request. Can someone help me?

Edit: sharing the view that I'm testing

```<code>class APIstory(APIView):
permission_classes = [IsAuthenticated]

def put(self,request, pk, idStory):
    data = self.request.data
    pk = self.kwargs['pk']

    id = self.kwargs['idStory']
    name = data['storyName'].strip()
    if name == "" or str.isspace(name) or len(name) < 4:
            return Response({"error": "minimum of 4 words"}, status=400)

    if PokerRoom.objects.filter(id=pk).exists():
        session = PokerRoom.objects.filter(id=pk)

        if session[0].status == 'Finished':
            return Response({'error': 'Session already ended'}, status=400)
        else:
            session = PokerRoom(id=pk)
            if Story.objects.filter(id=id, idRoom=session).exists():
                if not Story.objects.filter(idRoom=session, storyName=name).exists():
                    for hist in Story.objects.filter(id=id, idRoom=session):
                        if  hist.status == 'Pending':
                            if hist.storyName == name:
                                return Response({'error':'story with the same name'}, status=400)
                            hist.storyName = name
                            hist.save()
                            status = hist.status
                            body = {"id":id,"storyName":name,"status":status}
                            message_socket("STORY_UPDATE", pk, body)
                            return Response({'success': 'story {} edited, status is {}.'.format(hist.id,hist.status)})
                        else:
                            return Response({'error': 'story already ended'}, status= 400)
                else:
                    return Response({'error': 'story with the same name'}, status= 400)

        return Response({'error': 'session doesnt exists.'}, status=400)
    else:
        return Response({'error': 'session doesnt exists.'}, status=400)
</code>```

Edit2: I was forgetting to put the body in my request, but now I'm getting the following error: TypeError: super(type, obj): obj must be an instance or subtype of type

答:
Shouldn't you add the request body also in a put request?
Something like this?

```<code>request = c.put(reverse('storyFunctions', kwargs={'pk': self.room.pk, 'idStory': self.story.pk}), payload, format='json')
</code>```

As per the docs

Body:
I've been trying to test my PUT method in the following APITestcase:

    def test_story_delete(self):
    c = APIRequestFactory
    user = User.objects.get(username='test1')
    payload = {'storyName': 'changetest'}
    request = c.put(reverse('storyFunctions',args=[self.room.pk,self.story.pk]), format='json')
    force_authenticate(request,user=user)

My URL:

    path('room/<int:pk>/story/<int:idStory>/adm', APIHstory.as_view(),name='storyFunctions'),

And I'm keep receiving this error:

TypeError: put() missing 1 required positional argument: 'path'

I don't understand what is going on because i declared the path inside request. Can someone help me?

Edit: sharing the view that I'm testing

class APIstory(APIView):
permission_classes = [IsAuthenticated]

def put(self,request, pk, idStory):
    data = self.request.data
    pk = self.kwargs['pk']

    id = self.kwargs['idStory']
    name = data['storyName'].strip()
    if name == "" or str.isspace(name) or len(name) < 4:
            return Response({"error": "minimum of 4 words"}, status=400)

    if PokerRoom.objects.filter(id=pk).exists():
        session = PokerRoom.objects.filter(id=pk)

        if session[0].status == 'Finished':
            return Response({'error': 'Session already ended'}, status=400)
        else:
            session = PokerRoom(id=pk)
            if Story.objects.filter(id=id, idRoom=session).exists():
                if not Story.objects.filter(idRoom=session, storyName=name).exists():
                    for hist in Story.objects.filter(id=id, idRoom=session):
                        if  hist.status == 'Pending':
                            if hist.storyName == name:
                                return Response({'error':'story with the same name'}, status=400)
                            hist.storyName = name
                            hist.save()
                            status = hist.status
                            body = {"id":id,"storyName":name,"status":status}
                            message_socket("STORY_UPDATE", pk, body)
                            return Response({'success': 'story {} edited, status is {}.'.format(hist.id,hist.status)})
                        else:
                            return Response({'error': 'story already ended'}, status= 400)
                else:
                    return Response({'error': 'story with the same name'}, status= 400)

        return Response({'error': 'session doesnt exists.'}, status=400)
    else:
        return Response({'error': 'session doesnt exists.'}, status=400)

Edit2: I was forgetting to put the body in my request, but now I'm getting the following error: TypeError: super(type, obj): obj must be an instance or subtype of type

Body:
Shouldn't you add the request body also in a put request?
Something like this?

request = c.put(reverse('storyFunctions', kwargs={'pk': self.room.pk, 'idStory': self.story.pk}), payload, format='json')

As per the docs


问:
i am tryin to create a method decorator in angular but this error shows up
```<code>export class IceCreamComponent {
  @Emoji()
  flavor = 'vanilla';
}

// Property Decorator
function Emoji() {
  return function(target: Object, key: string | symbol) {

    let val = target[key];

    const getter = () =>  {
        return val;
    };
    const setter = (next:any) => {
        console.log('updating flavor...');
        val = ` ${next} `;
    };

    Object.defineProperty(target, key, {
      get: getter,
      set: setter,
      enumerable: true,
      configurable: true,
    });

  };
}
</code>```

i got error:

error TS7053: Element implicitly has an 'any' type because expression
of type 'string | symbol' can't be used to index type 'Object'.   No
index signature with a parameter of type 'string' was found on type
'Object'.

11     let val = target[key];

答:
```<code>let val = (<any>target)[key];
</code>```

Body:
export class IceCreamComponent {
  @Emoji()
  flavor = 'vanilla';
}

// Property Decorator
function Emoji() {
  return function(target: Object, key: string | symbol) {

    let val = target[key];

    const getter = () =>  {
        return val;
    };
    const setter = (next:any) => {
        console.log('updating flavor...');
        val = ` ${next} `;
    };

    Object.defineProperty(target, key, {
      get: getter,
      set: setter,
      enumerable: true,
      configurable: true,
    });

  };
}

i got error:

error TS7053: Element implicitly has an 'any' type because expression
of type 'string | symbol' can't be used to index type 'Object'.   No
index signature with a parameter of type 'string' was found on type
'Object'.

11     let val = target[key];

Body: let val = (<any>target)[key];


问:
How to validate for ObjectID
Using Joi schema validation, is it possible to validate against MongoDB ObjectID's?

Something like this could be great:

```<code>_id: Joi.ObjectId().required().error(errorParser),
</code>```

答:
If you want a TypeScript version of the above library integrated with Express without installing anything:</p>
```<code>import Joi from '@hapi/joi';
import { createValidator } from 'express-joi-validation';

export const JoiObjectId = (message = 'valid id') => Joi.string().regex(/^[0-9a-fA-F]{24}$/, message)

const validator = createValidator({
    passError: true,
});

const params = Joi.object({
    id: JoiObjectId().required(),
});

router.get<{ id: string }>(
    '/:id',
    validator.params(params),
    (req, res, next) => {
       const { id } = req.params; // id has string type
       ....
    }
);
</code>```

Title: How to validate for ObjectID

Body:
Using Joi schema validation, is it possible to validate against MongoDB ObjectID's?

Something like this could be great:

_id: Joi.ObjectId().required().error(errorParser),

Body:
If you want a TypeScript version of the above library integrated with Express without installing anything:

import Joi from '@hapi/joi';
import { createValidator } from 'express-joi-validation';

export const JoiObjectId = (message = 'valid id') => Joi.string().regex(/^[0-9a-fA-F]{24}$/, message)

const validator = createValidator({
    passError: true,
});

const params = Joi.object({
    id: JoiObjectId().required(),
});

router.get<{ id: string }>(
    '/:id',
    validator.params(params),
    (req, res, next) => {
       const { id } = req.params; // id has string type
       ....
    }
);


问:
CloudFront-served CSS files not rendered
This is an odd issue, but I assume I've done something boneheaded somewhere along the line to end up with this current situation.

When trying to serve static files (images, css & js) from CloudFront, they don't seem to be rendering properly. For example, one of my stylesheets is available here: http://d21uvxjmc903qz.cloudfront.net/stylesheets/hf.4fabc9c719f8.css, but it doesn't seem to be "applied" to the DOM as I would expect. (For example, looking in developer tools in Chrome or Firefox in Firebug the relevant styles aren't applied to the  element.

Looking at the response headers, it looks like the Content-Type is set properly, so I'm pretty much out of ideas.

Any suggestions on where to look next?

答: I know this is a super old question but I found a solution that worked for me with the same problem: in the CloudFront console, I created a new 'invalidation' for /* which as I understand it forces requests for the static files to go to the origin instead of the CloudFront cache, and this fixed my css rendering issues as I had recently changed the location of css files in my project.


问:
Pyspark : Convert nested JSON struct to pyspark dataframe
Is there an easy way to convert the below sample json into Pyspark dataframe ?

Input :

{
"user": {
  "1": {
    "name": "Joe",
    "age": 28
  },
  "2" :{
    "name": "Chris",
    "age": 14
  },
  "3" :{
    "name": "Hally",
    "age": 21
  }
}
}
```
<p>Expected output (dataframe):</p>
<pre class="lang-json prettyprint-override"><code>root
 |-- age: long (nullable = true)
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)

+---+---+-----+
|age|id |name |
+---+---+-----+
|28 |1  |Joe  |
|14 |2  |Chris|
|21 |3  |Hally|
+---+---+-----+
</code>```

答:
You can just chain with DataFrame and apply Series

```<code>out = pd.DataFrame(input).user.apply(pd.Series).rename_axis('id').reset_index()
Out[110]:
  id   name  age
0  1    Joe   28
1  2  Chris   14
2  3  Hally   21
</code>```

Body:
Is there an easy way to convert the below sample json into Pyspark dataframe ?

Input :

{
"user": {
  "1": {
    "name": "Joe",
    "age": 28
  },
  "2" :{
    "name": "Chris",
    "age": 14
  },
  "3" :{
    "name": "Hally",
    "age": 21
  }
}
}

Expected output (dataframe):

root
 |-- age: long (nullable = true)
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)

+---+---+-----+
|age|id |name |
+---+---+-----+
|28 |1  |Joe  |
|14 |2  |Chris|
|21 |3  |Hally|
+---+---+-----+

Body:
You can just chain with DataFrame and apply Series

out = pd.DataFrame(input).user.apply(pd.Series).rename_axis('id').reset_index()
Out[110]:
  id   name  age
0  1    Joe   28
1  2  Chris   14
2  3  Hally   21


问:
select2 library I want when entering the search input to convert to uppercase letter
If you can help me, I want that when writing in the select2 search box it automatically changes to uppercase
I have no code to teach because I have searched and found nothing about it
I attach an image

I put the inputs in automatic capital letters with onkeyup and I call the following function and I would like to do it in the select2

```<code> function mayus(e) {
  e.value = e.value.toUpperCase();
 }
</code>```

example

答:
You can't use onkeyup property on the select2 search input. You should instead use "event delegation". Try this

```<code>$(document).on('keyup', '.select2-search__field', function(e){
    e.target.value = e.target.value.toUpperCase()
});
</code>```

Body:
If you can help me, I want that when writing in the select2 search box it automatically changes to uppercase
I have no code to teach because I have searched and found nothing about it
I attach an image

I put the inputs in automatic capital letters with onkeyup and I call the following function and I would like to do it in the select2

 function mayus(e) {
  e.value = e.value.toUpperCase();
 }

example

Body:
You can't use onkeyup property on the select2 search input. You should instead use "event delegation". Try this

$(document).on('keyup', '.select2-search__field', function(e){
    e.target.value = e.target.value.toUpperCase()
});