问:
SQLAlchemy models column multiple option
I'm using FastAPI + SQLAlchemy + Postgresql to build an api service's backend database, which uses AWS and GCP's resource as resource provider.

I want use an ApiService db model to wrapp both cloud provider, like this:

```<code>from sqlalchemy import Boolean, Column, Integer, String
from sqlalchemy.orm import relationship
from .database import Base

# Base service model for all models
class BaseService(Base):
    id = Column(Integer, primary_key=True)
    type = Column(String(80))

# API Service (AWS, GCP, Azure, etc.)
class ApiService(BaseService):
    __tablename__ = 'api_services'

    id = Column(Integer, primary_key=True)
    name = Column(String(80))
    is_active = Column(Boolean, default=True)
    provider = Column(String(80))
    provider_detail = relationship("AwsProvider", uselist=False, backref="api_service")
    # provider_detail = relationship("GcpProvider", uselist=False, backref="api_service")

# AWS Provider
class AwsProvider(Base):
    __tablename__ = 'aws_providers'

    id = Column(Integer, primary_key=True)
    aws_region = Column(String(80))
    aws_api_id = Column(String(80))
    endpoint = Column(String(80))
    service = relationship("ApiService", uselist=False, backref="aws_provider")

# Google Cloud Provider
class GcpProvider(Base):
    __tablename__ = 'gcp_providers'

    id = Column(Integer, primary_key=True)
    gcp_region = Column(String(80))
    gcp_api_id = Column(String(80))
    endpoint = Column(String(80))
    service = relationship("ApiService", uselist=False, backref="gcp_provider")
</code>```

I want table api_services contains all services, which include aws or gcp as resource provider, and table aws_providers or gcp_providers contains their hosted record only .

What is the best pratice to do that?

I think maybe it's possible to set ApiService.provider_detail as an Union type, or it's value is depends on ApiService.provider column, which can be one of AwsProvider or GcpProvider, but not sure whether SQLAlchemy can do this.

Body:
I'm using FastAPI + SQLAlchemy + Postgresql to build an api service's backend database, which uses AWS and GCP's resource as resource provider.

I want use an ApiService db model to wrapp both cloud provider, like this:

from sqlalchemy import Boolean, Column, Integer, String
from sqlalchemy.orm import relationship
from .database import Base

# Base service model for all models
class BaseService(Base):
    id = Column(Integer, primary_key=True)
    type = Column(String(80))

# API Service (AWS, GCP, Azure, etc.)
class ApiService(BaseService):
    __tablename__ = 'api_services'

    id = Column(Integer, primary_key=True)
    name = Column(String(80))
    is_active = Column(Boolean, default=True)
    provider = Column(String(80))
    provider_detail = relationship("AwsProvider", uselist=False, backref="api_service")
    # provider_detail = relationship("GcpProvider", uselist=False, backref="api_service")

# AWS Provider
class AwsProvider(Base):
    __tablename__ = 'aws_providers'

    id = Column(Integer, primary_key=True)
    aws_region = Column(String(80))
    aws_api_id = Column(String(80))
    endpoint = Column(String(80))
    service = relationship("ApiService", uselist=False, backref="aws_provider")

# Google Cloud Provider
class GcpProvider(Base):
    __tablename__ = 'gcp_providers'

    id = Column(Integer, primary_key=True)
    gcp_region = Column(String(80))
    gcp_api_id = Column(String(80))
    endpoint = Column(String(80))
    service = relationship("ApiService", uselist=False, backref="gcp_provider")

I want table api_services contains all services, which include aws or gcp as resource provider, and table aws_providers or gcp_providers contains their hosted record only .

What is the best pratice to do that?

I think maybe it's possible to set ApiService.provider_detail as an Union type, or it's value is depends on ApiService.provider column, which can be one of AwsProvider or GcpProvider, but not sure whether SQLAlchemy can do this.


来源: stackexchange

问:
Get apparent type of NewExpression using ts-morph
I am currently trying to get the type of such declarations:

```<code>const x = new BehaviourSubject<string>(); // Should be of type BehaviourSubject<string>
</code>```

Using ts-morph i tried:

```<code>const declX = sourceFile.getVariableDeclarationOrThrow("x");
declX.getType().getText();
declX.getApparentType().getText();
</code>```

but in both cases i just get any as type. I suspect that i need to evaluate the NewExpression in some form using the ts-typechecker but can not find any references on how to do this.

Any input would be appreciated.

ContentLicense: CC BY-SA 4.0

Body:
I am currently trying to get the type of such declarations:

const x = new BehaviourSubject<string>(); // Should be of type BehaviourSubject<string>

Using ts-morph i tried:

const declX = sourceFile.getVariableDeclarationOrThrow("x");
declX.getType().getText();
declX.getApparentType().getText();

but in both cases i just get any as type. I suspect that i need to evaluate the NewExpression in some form using the ts-typechecker but can not find any references on how to do this.

Any input would be appreciated.


问:
Check if a user has sent an iMessage (iOS) or an SMS (Android) to validate something on an App
I'm building a hybrid mobile application and wanted to allow the user to get access to a feature only if the user had successfully invited another user through an SMS on both Android and iOS.

From the Android documentation, I can see that Android doesn't work the same as iOS regarding message status:
Android does not provide information about the status of the SMS message, so on Android devices the Promise will always resolve with { result: 'unknown' }.

Does someone have any idea if that's possible on Android and how it's done in Apple?

I've seen it done on another app on iOS with iMessage but don't know how it's possible to implement this flow on Android.


问:
Using optimizer.minimize() in tensorflow with var_list
I'm trying to use optimizer.minimize in tensorflow to train a model. My longterm intention is to implement an optimizer by inheriting from 'optimizer.Optimizer'.

However at the moment I'm not sure what to pass to var_list as for me the documentation is not straight forward. Can someone explain me what it does and what it has to be passed to?

Here is a minimal example:

```<code>x1 = np.random.randint(0,255,(10,10,10,1))
y1 = np.random.randint(0,10,(10,1))

def network(x2_shape):
    #xone = layers.Input(shape=x1_shape.shape[1:])
    xtwo = layers.Input(shape=x2_shape.shape[1:])

    xtwo_ = layers.Conv2D(32,(3,3))(xtwo)
    xtwo_ = layers.Conv2D(32,(3,3))(xtwo_)
    xtwo_ = layers.Flatten()(xtwo_)

    x = layers.Dense(16)(xtwo_)

    output1 = layers.Dense(10, 'softmax')(x)

    model = keras.Model(inputs=[xtwo], outputs=[output1])
    return model

model = network(x1)

y_pred = model([x1])
cross_entropy_loss = tf.keras.metrics.sparse_categorical_crossentropy([y1],y_pred)

optimizer = tf.optimizers.Adam()
train_op = optimizer.minimize(cross_entropy_loss, var_list=model.trainable_weights)
</code>```

I have also tried to using GradientTape() and using the keras API via compile and fit withouth having any errors.

For GradientTape() the code is:

```<code>for _ in range(2):
    with tf.GradientTape() as tape:
        y_pred = model(x1)
        cross_entropy_loss = tf.keras.metrics.sparse_categorical_crossentropy(y1,y_pred)
    grads = tape.gradient(cross_entropy_loss, model.trainable_weights)
    optimizer.apply_gradients(zip(grads, model.trainable_weights))
    print('Loss: {}'.format(cross_entropy_loss.numpy()))
</code>```

By using the keras API we get:

```<code>optimizer = tf.keras.optimizers.Adam() #wrap your favorite optimizer
loss = tf.keras.metrics.sparse_categorical_crossentropy(y1,y_pred)
model.compile(optimizer=optimizer,
                        loss = "sparse_categorical_crossentropy",
                        metrics="accuracy")
history = model.fit(x1, y1, batch_size=128, epochs=10)
</code>```

Body:
I'm trying to use optimizer.minimize in tensorflow to train a model. My longterm intention is to implement an optimizer by inheriting from 'optimizer.Optimizer'.

However at the moment I'm not sure what to pass to var_list as for me the documentation is not straight forward. Can someone explain me what it does and what it has to be passed to?

Here is a minimal example:

x1 = np.random.randint(0,255,(10,10,10,1))
y1 = np.random.randint(0,10,(10,1))

def network(x2_shape):
    #xone = layers.Input(shape=x1_shape.shape[1:])
    xtwo = layers.Input(shape=x2_shape.shape[1:])

    xtwo_ = layers.Conv2D(32,(3,3))(xtwo)
    xtwo_ = layers.Conv2D(32,(3,3))(xtwo_)
    xtwo_ = layers.Flatten()(xtwo_)

    x = layers.Dense(16)(xtwo_)

    output1 = layers.Dense(10, 'softmax')(x)

    model = keras.Model(inputs=[xtwo], outputs=[output1])
    return model

model = network(x1)

y_pred = model([x1])
cross_entropy_loss = tf.keras.metrics.sparse_categorical_crossentropy([y1],y_pred)

optimizer = tf.optimizers.Adam()
train_op = optimizer.minimize(cross_entropy_loss, var_list=model.trainable_weights)

I have also tried to using GradientTape() and using the keras API via compile and fit withouth having any errors.

For GradientTape() the code is:

for _ in range(2):
    with tf.GradientTape() as tape:
        y_pred = model(x1)
        cross_entropy_loss = tf.keras.metrics.sparse_categorical_crossentropy(y1,y_pred)
    grads = tape.gradient(cross_entropy_loss, model.trainable_weights)
    optimizer.apply_gradients(zip(grads, model.trainable_weights))
    print('Loss: {}'.format(cross_entropy_loss.numpy()))

By using the keras API we get:

optimizer = tf.keras.optimizers.Adam() #wrap your favorite optimizer
loss = tf.keras.metrics.sparse_categorical_crossentropy(y1,y_pred)
model.compile(optimizer=optimizer,
                        loss = "sparse_categorical_crossentropy",
                        metrics="accuracy")
history = model.fit(x1, y1, batch_size=128, epochs=10)


问:
What type of merging/release strategy to follow in Git/GitHub with multiple deployment branches?
I have 3 types of branches in my GitHub repo.

main -> deploys to production environment

staging -> deploys to staging environment

develop -> is the branch where most of the PRs are created to

When anyone works on the project they create a feature branch as feat/new-feature. Now, what will be the correct way of getting these new branches to the main production branch through develop and staging.

Should I merge those feature branches to develop, test things locally, merge develop to staging, test on the staging environment, and finally merge staging to main. Or should I merge the feature branches to develop, test it, and create a PR from feature branch to staging, test on the staging environment, and finally create a PR from the feature branch to main?

Please suggest me on the workflows that would make things easier.

For now I'm trying the initial approach described here.


问:
How to parse batches of flagged rows and keep the row sastisfying some conditions in a Pandas dataframes?
I have a dataframe containing duplicates, that are flagged by a specific variable. The df looks like this:

enter image description here

The idea is that the rows to keep and its duplicates are stacked in batches (a pair or more if many duplicates)and identified by the "duplicate" column. I would like, for each batch, to keep the row depending on one conditions: it has to be the row with the smallest number of empty cells. For Alice for instance, it should be the second row (and not the one flagged "keep").
The difficulty lies also in the fact that I cannot group by on the "name", "lastname" or "phone" column, because they are not always filled (the duplicates are computed on these 3 concatenated columns by a ML algo).

Unlike already posted questions I've seen (how do I remove rows with duplicate values of columns in pandas data frame?), here the conditions to select the row to keep is not fixed (like keeping the first row or the last withing the batch of duplicates) but depends on the rows completion in each batch.

How can I parse the dataframe according to this column "duplicate", and among each batch extract the row I want ?

I tried to assign an unique label for each batch, in order to iterate over these label, but it fails.


问:
How to convert base64 of svg into base64 of png format
I'm getting svg flag from the json api and converting it into base64 svg but I want the result base64 in png format, is this possible to get base64 in png from svg image url?

Here is my code

```<code>let tabsCol = document.createElement('div');
tabsCol.className = 'tabsColumn';
function countries(){
    let fetchRes = fetch(
        "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/index.json");
        // fetchRes is the promise to resolve
        // it by using.then() method
        fetchRes.then(res =>
        res.json()).then(d => {
        // console.log(d)
        for(let i=0;i<d.length;i++){
            // console.log(`${d[i]['image']}`)
            flag += `<fieldset id="orientationform">
            <div>
              <input type="radio" id="${d[i]['code']}" class="orientation-input" name="orientation4" value="${d[i]['name']}" onchange="getSelectedFlag('${d[i]['image']}')">
              <label for="${d[i]['code']}"><span></span></label>
            </div>
            <div>
                <strong>${d[i]['name']}</strong> <br>
            </div>
            <img src="${d[i]['image']}" srcset="${d[i]['image']},
            ${d[i]['image']}" width="40" height="40" alt="${d[i]['value']}">
          </fieldset>
            `
        }
        })

}

flagTab.onclick = function(){
    flag = ``;
    countries()
    setTimeout(() => {
        // console.log('flag',flag)
        if(flagTabContent.children.length == 0){
            tabsCol.innerHTML = flag;
            flagTabContent.append(tabsCol);
        }
    }, 100);
}

function getSelectedFlag(url){
    // console.log(url)
    getBase64FromUrl(url).then(data=>{
        console.log(`flag:${data}`);
        app.contentWindow.postMessage(`flag:${data}`,'*');
    });
}
</code>```

The data variable returns the base64 in svg format but I want base64 in png format.

How can I do this?

Any help will be highly appriciated.

Thank you.

Body:
I'm getting svg flag from the json api and converting it into base64 svg but I want the result base64 in png format, is this possible to get base64 in png from svg image url?

Here is my code

let tabsCol = document.createElement('div');
tabsCol.className = 'tabsColumn';
function countries(){
    let fetchRes = fetch(
        "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/index.json");
        // fetchRes is the promise to resolve
        // it by using.then() method
        fetchRes.then(res =>
        res.json()).then(d => {
        // console.log(d)
        for(let i=0;i<d.length;i++){
            // console.log(`${d[i]['image']}`)
            flag += `<fieldset id="orientationform">

              <input type="radio" id="${d[i]['code']}" class="orientation-input" name="orientation4" value="${d[i]['name']}" onchange="getSelectedFlag('${d[i]['image']}')">

                ${d[i]['name']}

          </fieldset>
            `
        }
        })

}

flagTab.onclick = function(){
    flag = ``;
    countries()
    setTimeout(() => {
        // console.log('flag',flag)
        if(flagTabContent.children.length == 0){
            tabsCol.innerHTML = flag;
            flagTabContent.append(tabsCol);
        }
    }, 100);
}

function getSelectedFlag(url){
    // console.log(url)
    getBase64FromUrl(url).then(data=>{
        console.log(`flag:${data}`);
        app.contentWindow.postMessage(`flag:${data}`,'*');
    });
}

The data variable returns the base64 in svg format but I want base64 in png format.

How can I do this?

Any help will be highly appriciated.

Thank you.


问:
How can I check if the folder exists on a virtual machine when using jenkins pipeline?
I have a python file which will run on a virtual machine inside a jenkins pipeline during the CI operation.

In this file I have written a line

```<code>os.path.exists("C:\\")
</code>```

Now, this works fine on my local machine because, the C-Drive exists. But, will it create problem when it is run on the Jenkins?

And if I want to replace the "C:\" with location such that the new location should not create a problem during the Jenkins run, how can I do it?

I tried finding how the Jenkins virtual machine filing system works but, I did not find any satisfying answers to my question. I am using GitHub as source control for the project.

Body:
I have a python file which will run on a virtual machine inside a jenkins pipeline during the CI operation.

In this file I have written a line

os.path.exists("C:\\")

Now, this works fine on my local machine because, the C-Drive exists. But, will it create problem when it is run on the Jenkins?

And if I want to replace the "C:\" with location such that the new location should not create a problem during the Jenkins run, how can I do it?

I tried finding how the Jenkins virtual machine filing system works but, I did not find any satisfying answers to my question. I am using GitHub as source control for the project.


问:
Add a sample "CAMM" data to specific PTS in a MP4 file
For testing purpose, I need to add programatically some samples to an existing MP4 video file but I can't understand how.
My goal is to add some CAMM1 records (exposure data) associated to each PTS multiple of 33366, that's to say : PTS=0, PTS=33366, PTS=66732, ...

I already have an existing camm track atom in my file, so the idea is to duplicate all the existing CAMM samples (CAMM2 and CAMM3 data), add my CAMM1 samples to the existing CAMM data, and write all the samples again at the end of the mdat atom (moov atom is located after mdat atom in my case). Next I'll update the CAMM track atom (stts, stsc, stsz and stco) to index all the samples correctly.

But I have 1 question I can't understand. STSC and STCO are dealing with offsets and STTS with time and delta, how can I do to link my CAMM1 records to PTS multiple of 33366 ?

Thanks


问:
How to push data in the table to axios.post
I am trying to post the data in the table but I keep getting the following in my console.log testing, undefined. What am I missing? or is there a better way to get the data to axios.post?

export default {
  props: {
    table: {
      type:Array,
      required: true,
      default: null
    }
  },
  data() {
  },
  methods: {
    submit(item) {
      axios.post('/newitem/${netId}', item)
        .then(response => {
          console.log("testing", response);
        })
        .catch(error => {
          // handle the error
        });
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr v-for="(item, index) in table" :key="index">
    <td> {{ item.name }} </td>
    <td> {{ item.source }} </td>
    <td> {{ item.accountId }} </td>
  </tr>
</table>
<div>
  <b-button @click="submit(item)">add</b-button>
</div></code>```

example of data:

```<code>  table: [{
      name: 'John',
      source: 'john@example.com',
      accountId: 30
    },
    {
      name: 'Sam',
      source: 'sam@example.com',
      accountId: 25
    },
  ]
</code>```

Body:
I am trying to post the data in the table but I keep getting the following in my console.log testing, undefined. What am I missing? or is there a better way to get the data to axios.post?

export default {
  props: {
    table: {
      type:Array,
      required: true,
      default: null
    }
  },
  data() {
  },
  methods: {
    submit(item) {
      axios.post('/newitem/${netId}', item)
        .then(response => {
          console.log("testing", response);
        })
        .catch(error => {
          // handle the error
        });
    }
  }
}

     {{ item.name }}
     {{ item.source }}
     {{ item.accountId }}

  add

example of data:

  table: [{
      name: 'John',
      source: 'john@example.com',
      accountId: 30
    },
    {
      name: 'Sam',
      source: 'sam@example.com',
      accountId: 25
    },
  ]


问:
i want the class social to be visible to class tob- bar-selection
I want some help.
When  @media screen and (max-width: 640px) then my div with name social to be visible to class tob- bar-selection down from ul.
my html:

@media screen and (max-width: 640px):

.top-bar-section ul{
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: stretch;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="social">
<div class="instagram">

<img src="  https://www.testdomain.gr/test.gr/assets/img/in.png">

</div>
<div class="facebook">

<img src="  https://www.testdomain.gr/test.gr/assets/img/fb.png">

</div>
</div>

<div class="top-bar-section">
<ul class="left home-active" data-position="2">
<ul class="center">
<li>Κεντρική</li>
<li>Η Εταιρία</li>
<li>Υπηρεσίες</li>
<li>Προϊόντα </li>
<li>Κατάστημα</li>
<li>Επικοινωνία</li>
</ul>
</ul>
</div></code>```

In our cms the hamburger menu created by befault.

I search if i can do this with js but i dont find something to help me

Body:
I want some help.
When  @media screen and (max-width: 640px) then my div with name social to be visible to class tob- bar-selection down from ul.
my html:

@media screen and (max-width: 640px):

.top-bar-section ul{
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: stretch;
}

Κεντρική

Η Εταιρία

Υπηρεσίες

Προϊόντα

Κατάστημα

Επικοινωνία

In our cms the hamburger menu created by befault.

I search if i can do this with js but i dont find something to help me


问:
run a loop inside an array WooCommerce
I am trying to excute some inpute fields if items are in woocommerce cart, using the code below I am getting amn extra array which i don't need, I want to to add First name and Last name and put them in this loop so I can repeat these 2 fields (first/last name) for each item in cart.

```<code>function vicode_custom_checkout_fields($fields){
$counter=0;
$fields = array();
foreach(WC()->cart->get_cart() as $cart_item ){

    $fields['vicodemedia_extra_fields'] = array(

    'vicodemedia_add_field' => array(
        'type' => 'text',
        'label' => __( 'First Name' ),
        'class' => 'form-row-first'
        ),
    );
    $counter++;
}
</code>```

}
add_filter( 'woocommerce_checkout_fields', 'vicode_custom_checkout_fields' );

Title: run a loop inside an array WooCommerce

Body:
I am trying to excute some inpute fields if items are in woocommerce cart, using the code below I am getting amn extra array which i don't need, I want to to add First name and Last name and put them in this loop so I can repeat these 2 fields (first/last name) for each item in cart.

function vicode_custom_checkout_fields($fields){
$counter=0;
$fields = array();
foreach(WC()->cart->get_cart() as $cart_item ){

    $fields['vicodemedia_extra_fields'] = array(

    'vicodemedia_add_field' => array(
        'type' => 'text',
        'label' => __( 'First Name' ),
        'class' => 'form-row-first'
        ),
    );
    $counter++;
}

}
add_filter( 'woocommerce_checkout_fields', 'vicode_custom_checkout_fields' );


问:
how to collect data in list from alerts with flutter?
I'm trying to collect data in list from alertDialogs.
In every alert there's some data that I have to retrive it. I have to retrive the data from each alert and then put all the data that is retrived from all the alertDialogs in one list.
For now, I arrived juste to retrive the data of every alert but I don't know how to save all the data on one list.
this is my code:</p>
```<code>Future.delayed(const Duration(milliseconds: 500), () {
                    List list1 = [
                      data.x,
                      data.y,

                    ];

                    List list2 = [];

                    list2.add(list1);

                  });
</code>```
```<code>return AlertDialog(
                    contentPadding: EdgeInsets.zero,
                    clipBehavior: Clip.antiAlias,
                    content: Row(
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(15),
                          child: RichText(
                            text: TextSpan(
                              text:
                                  '${data.x}\n',
</code>```

Body:
I'm trying to collect data in list from alertDialogs.
In every alert there's some data that I have to retrive it. I have to retrive the data from each alert and then put all the data that is retrived from all the alertDialogs in one list.
For now, I arrived juste to retrive the data of every alert but I don't know how to save all the data on one list.
this is my code:

Future.delayed(const Duration(milliseconds: 500), () {
                    List list1 = [
                      data.x,
                      data.y,

                    ];

                    List list2 = [];

                    list2.add(list1);

                  });

return AlertDialog(
                    contentPadding: EdgeInsets.zero,
                    clipBehavior: Clip.antiAlias,
                    content: Row(
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(15),
                          child: RichText(
                            text: TextSpan(
                              text:
                                  '${data.x}\n',


问:
Reaching a certain data with the navigation view in a SwiftUI
I make a navigation view and then I want to get some data from the list that it defines as Rosette. But I could not. I will be grateful if you could help me.
My code is like this:

```<code>struct UserProfileResponse {
    let userName : String
    let level : Int
    let photo : String
    let followerCount : Int
    let followCount : Int
    let name : String
    let title : String
    let bio : String
    let height : Float
    let weight : Float
    let dateOfBirth : Int
    let rosette : [Rosette]
    let activities : [ActivityModel]
    let docId : String
}
</code>```

Rosette is like this:

```<code>struct Rosette {
    let sıra: Int
    let rosetteImage : String
    let goldStep : Int
    let rosetteName : String
    let rosetteLevel : Int
    let rosetteDone : Int
    let percentageComplete : Double
    var shouldShowTitle:Bool{
        percentageComplete <= 1
    }
}
struct CircleLevelList {
    static let four = [
        Rosette(sıra: 1, rosetteImage: "Football", goldStep: 25, rosetteName: "Football Star", rosetteLevel: 12, rosetteDone: 12, percentageComplete: 1),
        Rosette(sıra: 2, rosetteImage: "voleybol", goldStep: 25 ,rosetteName: "Voleybol Star", rosetteLevel: 16, rosetteDone: 8, percentageComplete: 0.50),
        Rosette(sıra: 3, rosetteImage: "Tabletennis", goldStep: 25, rosetteName: "Tabletennis Star", rosetteLevel: 12, rosetteDone: 4, percentageComplete: 0.33),
        Rosette(sıra: 4, rosetteImage: "Basketball", goldStep: 25, rosetteName: "Basketball Star", rosetteLevel: 10, rosetteDone: 1, percentageComplete: 1)
     ]
}
</code>```

While accessing all the information in the UserProfile Response on the detail screen, I also want to see the rosetteLevel and rosetteDone data inside the Rosette on the detail screen. Thank you in advance for your help

Body:
I make a navigation view and then I want to get some data from the list that it defines as Rosette. But I could not. I will be grateful if you could help me.
My code is like this:

struct UserProfileResponse {
    let userName : String
    let level : Int
    let photo : String
    let followerCount : Int
    let followCount : Int
    let name : String
    let title : String
    let bio : String
    let height : Float
    let weight : Float
    let dateOfBirth : Int
    let rosette : [Rosette]
    let activities : [ActivityModel]
    let docId : String
}

Rosette is like this:

struct Rosette {
    let sıra: Int
    let rosetteImage : String
    let goldStep : Int
    let rosetteName : String
    let rosetteLevel : Int
    let rosetteDone : Int
    let percentageComplete : Double
    var shouldShowTitle:Bool{
        percentageComplete <= 1
    }
}
struct CircleLevelList {
    static let four = [
        Rosette(sıra: 1, rosetteImage: "Football", goldStep: 25, rosetteName: "Football Star", rosetteLevel: 12, rosetteDone: 12, percentageComplete: 1),
        Rosette(sıra: 2, rosetteImage: "voleybol", goldStep: 25 ,rosetteName: "Voleybol Star", rosetteLevel: 16, rosetteDone: 8, percentageComplete: 0.50),
        Rosette(sıra: 3, rosetteImage: "Tabletennis", goldStep: 25, rosetteName: "Tabletennis Star", rosetteLevel: 12, rosetteDone: 4, percentageComplete: 0.33),
        Rosette(sıra: 4, rosetteImage: "Basketball", goldStep: 25, rosetteName: "Basketball Star", rosetteLevel: 10, rosetteDone: 1, percentageComplete: 1)
     ]
}

While accessing all the information in the UserProfile Response on the detail screen, I also want to see the rosetteLevel and rosetteDone data inside the Rosette on the detail screen. Thank you in advance for your help


问:
OpenLayers keyboard zoom not working in electron environment
I have a electron app that is used to do network graph analysis based on real world graphs such as electric networks. At the moment I'm trying to implement an option where I layer the graph over a map and one can see the exact position of the nodes on the map. It looks like this:

Adding the map is done by open layers. I also want to be able to pan and zoom in while the map is shown. For this the map and graph have to move together. This should be possible with keyboard commands of the arrow keys and + and - .

When I use the arrow keys to direct up ,down ,left ,right everything works apart from open layers loading the map slower than the graph moves sometimes. But when I zoom with the keyboard the map from open layers is not zooming at all. I also tried every key on the keyboard and apparently there is not a single key that zooms the map eventho I activated the keyboard in the options.

The + and - keys generally work in the electron app so this is not a problem. Furthermore, the graph also zooms. It's just the map that does not.

Is there a way to fix this? If not what would be the best option to find a different solution than using the keyboard buttons?


问:
How to change background of elements inside tonal card in Vuetify3?
I would like to be able to fully control the background color of an element inside a Vuetify3 card with variant=tonal.

In the example below, I want the Inside component to be white in both cases. The inner component does not have to be a `, just anything, that allows full color control.

How do I do this?

```<code><v-card class="ma-5" color="red" variant="tonal">
    Test
    <v-sheet class="ma-5" color="white" variant="tonal">
        Inside
    </v-sheet>
</v-card>
<v-card class="ma-5" color="red">
    Test
    <v-sheet class="ma-5" color="white" variant="tonal">
        Inside
    </v-sheet>
</v-card>
</code>```

Body:
I would like to be able to fully control the background color of an element inside a Vuetify3 card with variant=tonal.

In the example below, I want the Inside component to be white in both cases. The inner component does not have to be a `, just anything, that allows full color control.

How do I do this?

<v-card class="ma-5" color="red" variant="tonal">
    Test
    <v-sheet class="ma-5" color="white" variant="tonal">
        Inside
    </v-sheet>
</v-card>
<v-card class="ma-5" color="red">
    Test
    <v-sheet class="ma-5" color="white" variant="tonal">
        Inside
    </v-sheet>
</v-card>


问:
SwiftUI ScrollView - How to scroll up and down using arrow keys?
I have a SwiftUI view I wrap in a NSHostingController in a mac app. This view consists of a vertical ScrollView with LazyVStack in it with various content (divided into Section). This content is long so the view is always scrollable.

I'm trying to implement better keyboard navigation, I can navigate buttons using Tab key, but I also want to support basic scrolling using up and down arrow keys.

This is something that works out-of-the-box in AppKit when e.g. using NSTextView in NSScrollView.

How do I enable scrolling up and down using arrow keys for SwiftUI.ScrollView on macOS?

I'm to looking for scrolling to an identifiable element but rather to scroll by x points up and down. Like the NSScrollView works.

Ideally, including modifier keys ALT+Up to page up and CMD+Up to scroll to the top.

struct ContentView: View {

    var body: some View {
        ScrollView(.vertical) {
            LazyVStack {
                Image(systemName: "globe")
                    .imageScale(.large)
                    .foregroundColor(.accentColor)

                Text("Hello, world!")

                Section("Lorem Ipsum") {
                    Text(Strings.longText)
                }
            }
            .padding()
        }
    }
}
```


问:
Matplotlib: how to fix label width independent of label content
I want the position of the graph to be consistent over multiple plots. However the position depends on the width of the tick labels on the y-axis.
I can limit the text length to e.g. 8 characters, however due to the different character width the position of the graphs origin still changes.

How can I fix the tick label width or the plots origin position?

```<code>import matplotlib.pyplot as plt
import numpy as np

# Insert a line break #EVERY characters
def insert_linebreak(string, every=8):
    lines = []
    for i in range(0, len(string), every):
        lines.append(string[i:i+every])
    return '\n'.join(lines)

# Fixing random state for reproducibility
np.random.seed(19680801)

plt.rcdefaults()
fig, ax = plt.subplots()
# Example data
people = ('.........', 'Dick', 'Harry', 'Slim', 'Jim')
people_fixed_length=[]
for i in range(len(people)):
    people_fixed_length.append(insert_linebreak(people[i]))
people=people_fixed_length

y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos, labels=people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()

plt.rcdefaults()
fig, ax = plt.subplots()
# Example data
people = ('MMMMMMMMMM', 'Dick', 'Harry', 'Slim', 'Jim')
people_fixed_length=[]
for i in range(len(people)):
    people_fixed_length.append(insert_linebreak(people[i]))
people=people_fixed_length

y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos, labels=people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()
</code>```

Body:
I want the position of the graph to be consistent over multiple plots. However the position depends on the width of the tick labels on the y-axis.
I can limit the text length to e.g. 8 characters, however due to the different character width the position of the graphs origin still changes.

How can I fix the tick label width or the plots origin position?

import matplotlib.pyplot as plt
import numpy as np

# Insert a line break #EVERY characters
def insert_linebreak(string, every=8):
    lines = []
    for i in range(0, len(string), every):
        lines.append(string[i:i+every])
    return '\n'.join(lines)

# Fixing random state for reproducibility
np.random.seed(19680801)

plt.rcdefaults()
fig, ax = plt.subplots()
# Example data
people = ('.........', 'Dick', 'Harry', 'Slim', 'Jim')
people_fixed_length=[]
for i in range(len(people)):
    people_fixed_length.append(insert_linebreak(people[i]))
people=people_fixed_length

y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos, labels=people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()

plt.rcdefaults()
fig, ax = plt.subplots()
# Example data
people = ('MMMMMMMMMM', 'Dick', 'Harry', 'Slim', 'Jim')
people_fixed_length=[]
for i in range(len(people)):
    people_fixed_length.append(insert_linebreak(people[i]))
people=people_fixed_length

y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos, labels=people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()


问:
How to implement observer pattern the way django signals implements it
there's a design issue i have with a problem i'm currently working that will require a certain observable to emit values whenever it reaches a computation milestone,so i need values emitted intermediately,i discovered django implements something similar with signals which is just an implementation of the observer pattern but i really wanted to implement it the way django signals is implemented because observers subscribing to an observable( e.g after saving a model to the db i.e post_save signal) is very much decoupled in the sense that the observing function only needs to be annotated with the @receiver decorator.

So i took a look at django's source code and tried creating a simple version of the signal mechanism i created a signals class in one module with the decorator :

```<code>class Signal:
    def __init__(self):
        self.observers=[]
    def connect(self,receiver):
        self.observers.append(receiver.__name__)
    def send(self,sender,**named):
        return [
            (receiver,mem_dec(signal=self,sender=sender,**named))
            for receiver in self.observers
            ]

class Child(Signal):
    def __init__(self):
        super().__init__()

def mem_dec(signal,**kwargs):
    def wrapper(func):
        signal.connect(func, **kwargs)
        return func
    return wrapper

if __name__ == "__main__":
    send_signal=Child()
    send_signal.send(sender="class_child",a="henry")
</code>```

and i placed the decorated function in another module to serve as the observer:

```<code>from .signals import mem_dec
from .signals import Child

@mem_dec(Child,sender=Child)
def hello(a,**kwargs):
    print(f'hey {a}')

</code>```

i noticed in my implementation doesn't work which i expected but the issue is that's what i could reproduce from the source code,i'm very confused about how they implemented their send() and connect()  mechanism,all i want to achieve with this is for the signal subclass call all decorated functions, i made the Child class the signal and sender at the same time cause i'm just trying to reproduce the simplest example.

Body:
there's a design issue i have with a problem i'm currently working that will require a certain observable to emit values whenever it reaches a computation milestone,so i need values emitted intermediately,i discovered django implements something similar with signals which is just an implementation of the observer pattern but i really wanted to implement it the way django signals is implemented because observers subscribing to an observable( e.g after saving a model to the db i.e post_save signal) is very much decoupled in the sense that the observing function only needs to be annotated with the @receiver decorator.

So i took a look at django's source code and tried creating a simple version of the signal mechanism i created a signals class in one module with the decorator :

class Signal:
    def __init__(self):
        self.observers=[]
    def connect(self,receiver):
        self.observers.append(receiver.__name__)
    def send(self,sender,**named):
        return [
            (receiver,mem_dec(signal=self,sender=sender,**named))
            for receiver in self.observers
            ]

class Child(Signal):
    def __init__(self):
        super().__init__()

def mem_dec(signal,**kwargs):
    def wrapper(func):
        signal.connect(func, **kwargs)
        return func
    return wrapper

if __name__ == "__main__":
    send_signal=Child()
    send_signal.send(sender="class_child",a="henry")

and i placed the decorated function in another module to serve as the observer:

from .signals import mem_dec
from .signals import Child

@mem_dec(Child,sender=Child)
def hello(a,**kwargs):
    print(f'hey {a}')

i noticed in my implementation doesn't work which i expected but the issue is that's what i could reproduce from the source code,i'm very confused about how they implemented their send() and connect()  mechanism,all i want to achieve with this is for the signal subclass call all decorated functions, i made the Child class the signal and sender at the same time cause i'm just trying to reproduce the simplest example.


问:
StringGrid to Database Table
I am using a program which shows data in tabular form that uses StringGrid.

As you may know that you cannot copy and past the data in StringGrid as whole but induvidually.

So, my question is, is there any code that allows me to select all data in StringGrid and paste them to Excel or export to Excel?

I haven't tried as my knowledge is limited on this matter.

Title: StringGrid to Database Table


问:
special character values getting trim down on parsing
I have special characters in the urlsearch params, so when parsing and getting the property value i am not getting the right value instead it breaks.

var params = new URLSearchParams("a=2%15&b=balloon");

console.log(params.get('a')) // 2% => need to get 2%15

 ```


问:
Increase Number of rows by numeric input i R shiny Handsontable without resetting the table to the initial values
I have created the following R shiny app with a handsonontable

```<code>library(shiny)
library(rhandsontable)

 ui <- fluidPage(
 sidebarLayout(sidebarPanel = "Inputparameter",numericInput(inputId = "RowNo", label = "No Of
 rows",7, value = 7, step = 1)),mainPanel (rHandsontableOutput(outputId = 'Adjusttable', width
 ='100%', height = '100%')))

server <- function(input, output, session) {
output$Adjusttable<-renderRHandsontable({
DF = data.frame(ID = 1:input$RowNo,'Column2' = 0, Start = "D",FM="",stringsAsFactors = FALSE)
#names(DF)[names(DF)=='Column2']<- input$Name
#names(DF)[names(DF)=='FM']<-'FM'
DF$ID<-NULL
rhandsontable(DF, width = 280, height = 677,stretchH = "all")  %>%
hot_col(col = "Start", type = "dropdown", source = c("Fw", "Sw"), fillHandle =
list(direction='vertical', autoInsertRow=TRUE))%>%
hot_context_menu(allowRowEdit = TRUE, allowColEdit = FALSE)}, quoted = FALSE )}

shinyApp(ui, server)
</code>```

This creates a shiny app with a handsontable. I can add new rows to the app by right clicking on the handsontable and inserting rows. This doesnt alter the values in the table. However, when I chnage rows by using the number of rows box, the table entries are reset to zero. Is there a way to add new rows dynamically without losing the values already entered. I request someone to take a look

Body:
I have created the following R shiny app with a handsonontable

library(shiny)
library(rhandsontable)

 ui <- fluidPage(
 sidebarLayout(sidebarPanel = "Inputparameter",numericInput(inputId = "RowNo", label = "No Of
 rows",7, value = 7, step = 1)),mainPanel (rHandsontableOutput(outputId = 'Adjusttable', width
 ='100%', height = '100%')))

server <- function(input, output, session) {
output$Adjusttable<-renderRHandsontable({
DF = data.frame(ID = 1:input$RowNo,'Column2' = 0, Start = "D",FM="",stringsAsFactors = FALSE)
#names(DF)[names(DF)=='Column2']<- input$Name
#names(DF)[names(DF)=='FM']<-'FM'
DF$ID<-NULL
rhandsontable(DF, width = 280, height = 677,stretchH = "all")  %>%
hot_col(col = "Start", type = "dropdown", source = c("Fw", "Sw"), fillHandle =
list(direction='vertical', autoInsertRow=TRUE))%>%
hot_context_menu(allowRowEdit = TRUE, allowColEdit = FALSE)}, quoted = FALSE )}

shinyApp(ui, server)

This creates a shiny app with a handsontable. I can add new rows to the app by right clicking on the handsontable and inserting rows. This doesnt alter the values in the table. However, when I chnage rows by using the number of rows box, the table entries are reset to zero. Is there a way to add new rows dynamically without losing the values already entered. I request someone to take a look


问:
Does StartMonitoringSignificantLocationChanges works in Low Power Mode
I want to add StartmonitoringSignificantLocationChanges in my app, but does it work in low power mode?

Apple's documentation says that the background activity will turn off, does this apply to StartmonitoringSignificantLocationChanges?


问:
Python: Utility function to determine when to roll over to next year (or roll back to previous year) for a given date and grace period
I'm writing code for a birthday gift website. I have a routine that given a birthdate (in mm/dd/yyyy date format) needs to return back the birthdate for the current year, based on when someone purchases the gift.

It seems simple enough, but there is a complication. The routine needs to effectively account for the fact that people buy gifts a few months in advance, or a few months late, and that the year changes over in the meantime.

For example, if someone's birthdate is 12/29/1975 (Dec 29th) and the current date is 01/01/2023 (1st Jan), it is more likely someone is buying the gift for last year's birthday (i.e. 12/29/2022) than for this year's birthday (12/29/2023). Similarly if someone's birthday is on Jan 5th, and today's date happens to be November 29th, 2022, it is more likely I am buying the gift for that person's next birthday (i.e. 01/05/2023) than the current year's past birthday.

So you need to be able to clock the year forward in certain cases, as well as back in certain cases, and need to incorporate some kind of arbitrary grace period that determines when to clock forward or back.

By creating lots of different use cases and through trial and error I came up with the following function. It works (or at least passes all my use cases) but I'm struggling for an intuitive understanding of why it works, or whether there is a more elegant / intuitive way to do this. Also I happen to be paranoid that there may be cases for which this may fail and produce faulty results!

Any thoughts / insight would be much appreciated!

```<code>
def determine_correct_year_to_use_for_birthdays(birthday, today=None, grace_period=120):
    """
    Determine the correct year to use for a date.  After grace_period number of days, you can assume the birthday is for the
    next year. Have to account for year changeovers also.
    :param birthday:
    :param grace_period: in days
    :return:
    # covert birthdate to this year's birthday
    # if (birthday - current date) is positive AND diff > (365 - grace period), go back one year
    # if (birthday - current date) is positive AND diff < (365 - grace period), keep current year
    # if (birthday - current date) is negative AND abs(diff) < (365 - grace period), keep current year
    # if (birthday - current date) is negative AND abs(diff) > (365 - grace period), move to next year

    """
    if not today:
        today = datetime.now()
    birthday = birthday.replace(year=today.year)
    diff = (birthday - today).days

    if diff > 0 and abs(diff) > (365 - grace_period):
        birthday = birthday.replace(year=today.year - 1)
    if diff < 0 and abs(diff) > (365 - grace_period):
        birthday = birthday.replace(year=today.year + 1)
    return birthday

</code>```

Body:
I'm writing code for a birthday gift website. I have a routine that given a birthdate (in mm/dd/yyyy date format) needs to return back the birthdate for the current year, based on when someone purchases the gift.

It seems simple enough, but there is a complication. The routine needs to effectively account for the fact that people buy gifts a few months in advance, or a few months late, and that the year changes over in the meantime.

For example, if someone's birthdate is 12/29/1975 (Dec 29th) and the current date is 01/01/2023 (1st Jan), it is more likely someone is buying the gift for last year's birthday (i.e. 12/29/2022) than for this year's birthday (12/29/2023). Similarly if someone's birthday is on Jan 5th, and today's date happens to be November 29th, 2022, it is more likely I am buying the gift for that person's next birthday (i.e. 01/05/2023) than the current year's past birthday.

So you need to be able to clock the year forward in certain cases, as well as back in certain cases, and need to incorporate some kind of arbitrary grace period that determines when to clock forward or back.

By creating lots of different use cases and through trial and error I came up with the following function. It works (or at least passes all my use cases) but I'm struggling for an intuitive understanding of why it works, or whether there is a more elegant / intuitive way to do this. Also I happen to be paranoid that there may be cases for which this may fail and produce faulty results!

Any thoughts / insight would be much appreciated!

def determine_correct_year_to_use_for_birthdays(birthday, today=None, grace_period=120):
    """
    Determine the correct year to use for a date.  After grace_period number of days, you can assume the birthday is for the
    next year. Have to account for year changeovers also.
    :param birthday:
    :param grace_period: in days
    :return:
    # covert birthdate to this year's birthday
    # if (birthday - current date) is positive AND diff > (365 - grace period), go back one year
    # if (birthday - current date) is positive AND diff < (365 - grace period), keep current year
    # if (birthday - current date) is negative AND abs(diff) < (365 - grace period), keep current year
    # if (birthday - current date) is negative AND abs(diff) > (365 - grace period), move to next year

    """
    if not today:
        today = datetime.now()
    birthday = birthday.replace(year=today.year)
    diff = (birthday - today).days

    if diff > 0 and abs(diff) > (365 - grace_period):
        birthday = birthday.replace(year=today.year - 1)
    if diff < 0 and abs(diff) > (365 - grace_period):
        birthday = birthday.replace(year=today.year + 1)
    return birthday


问:
How to reduce space during the ray/pytorch HPO process?
Could I ask,

When I run pytorch lightning with ray HPO it creates a lot of directories like this:

```<code>'train_fn_ff307114_1350_activation_function=nn_ReLU_inplace_True,c_hidden=64,dp_rate_linear=0.6747,learning_rate=0.0002,num_layers=_2022-12-21_17-51-28'
'train_fn_ff4d9f16_599_activation_function=nn_LeakyReLU_inplace_True,c_hidden=2056,dp_rate_linear=0.5871,learning_rate=0.0035,num_l_2022-12-21_13-26-00'
'train_fn_ffa6c2a4_892_activation_function=nn_ReLU_inplace_True,c_hidden=512,dp_rate_linear=0.6173,learning_rate=0.0116,num_layers=_2022-12-21_15-06-17'
'train_fn_ffe7cd72_1684_activation_function=nn_Tanh,c_hidden=2056,dp_rate_linear=0.6520,learning_rate=0.0032,num_layers=4,optimizer_2022-12-21_19-45-25'
</code>```

Each dir containing a checkpoint, log etc.

Is there a way to optimize this for space? For example, if a directory is found to have a better val_acc (my metric of interest for HPO) then we don't need to keep the less better val_acc HPO attempt, so can I delete these as I go through the HPO process, so I'm only left with the data for the best HPO attempt at the end (and there is never an excessively large amount of info saved)?

My code for running HPO is:

```<code>
def run_ray(metric='val_acc', mode='max',num_samples=4000,config_dict={}, checkpoint_file_name="full_run_2_ray_ckpt",config_file='full_run_2/best_config.txt',local_dir='full_run_2/runs/'):

    hyperopt_search = HyperOptSearch(metric=metric, mode=mode)

    #change from gpu {"gpu": 1}
    tuner = tune.Tuner(tune.with_resources(train_fn,{"gpu": 1}), tune_config=tune.TuneConfig(num_samples=num_samples,search_alg=hyperopt_search),param_space=config_dict,run_config= RunConfig(local_dir=local_dir))
    results = tuner.fit()
    best_result = results.get_best_result(metric=metric, mode=mode)

    config_file = open(config_file, 'a')
    config_file.write(str(best_result.config) + '\n')

    best_checkpoint = best_result.checkpoint
    path = os.path.join(str(best_checkpoint.to_directory()), checkpoint_file_name)
    print(path)

    model = GraphLevelGNN.load_from_checkpoint(path)
    config_file.write(str(best_result.log_dir))
    config_file.close()

    return best_result.log_dir,model
</code>```

Body:
Could I ask,

When I run pytorch lightning with ray HPO it creates a lot of directories like this:

'train_fn_ff307114_1350_activation_function=nn_ReLU_inplace_True,c_hidden=64,dp_rate_linear=0.6747,learning_rate=0.0002,num_layers=_2022-12-21_17-51-28'
'train_fn_ff4d9f16_599_activation_function=nn_LeakyReLU_inplace_True,c_hidden=2056,dp_rate_linear=0.5871,learning_rate=0.0035,num_l_2022-12-21_13-26-00'
'train_fn_ffa6c2a4_892_activation_function=nn_ReLU_inplace_True,c_hidden=512,dp_rate_linear=0.6173,learning_rate=0.0116,num_layers=_2022-12-21_15-06-17'
'train_fn_ffe7cd72_1684_activation_function=nn_Tanh,c_hidden=2056,dp_rate_linear=0.6520,learning_rate=0.0032,num_layers=4,optimizer_2022-12-21_19-45-25'

Each dir containing a checkpoint, log etc.

Is there a way to optimize this for space? For example, if a directory is found to have a better val_acc (my metric of interest for HPO) then we don't need to keep the less better val_acc HPO attempt, so can I delete these as I go through the HPO process, so I'm only left with the data for the best HPO attempt at the end (and there is never an excessively large amount of info saved)?

My code for running HPO is:

def run_ray(metric='val_acc', mode='max',num_samples=4000,config_dict={}, checkpoint_file_name="full_run_2_ray_ckpt",config_file='full_run_2/best_config.txt',local_dir='full_run_2/runs/'):

    hyperopt_search = HyperOptSearch(metric=metric, mode=mode)

    #change from gpu {"gpu": 1}
    tuner = tune.Tuner(tune.with_resources(train_fn,{"gpu": 1}), tune_config=tune.TuneConfig(num_samples=num_samples,search_alg=hyperopt_search),param_space=config_dict,run_config= RunConfig(local_dir=local_dir))
    results = tuner.fit()
    best_result = results.get_best_result(metric=metric, mode=mode)

    config_file = open(config_file, 'a')
    config_file.write(str(best_result.config) + '\n')

    best_checkpoint = best_result.checkpoint
    path = os.path.join(str(best_checkpoint.to_directory()), checkpoint_file_name)
    print(path)

    model = GraphLevelGNN.load_from_checkpoint(path)
    config_file.write(str(best_result.log_dir))
    config_file.close()

    return best_result.log_dir,model


问:
IIS CORS issues with windows authentication
I am using windows authentication, and I would like to get the name from the request in the form of domain\name. Currently I am using this: var name = HttpContext.Current.User.Identity.Name;, which has worked in the prior tests, but now I have CORS errors.

In IIS I have Windows Authentication enabled, and others disabled (anonymous authentication), but when I visit the website, I get CORS errors, saying the origins are not set. I then tried setting the headers in HTTP Response Headers in IIS, setting the allow origins to http://localhost:4200, allow credentials to true, and allowing all headers and methods, but then i get errors saying, that origins is set twice http://localhost:4200, http://localhost:4200, I also tried turning on anonymous authentication, but then the before mentioned var name = HttpContext.Current.User.Identity.Name; is an empty string.

This is how my cors setup looks like:

```<code>var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*")
{
    SupportsCredentials = true,
};
</code>```

And this is my web.config

```<code>...
<system.web>
    <authentication mode="Windows" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
</system.web>
...
</code>```

Body:
I am using windows authentication, and I would like to get the name from the request in the form of domain\name. Currently I am using this: var name = HttpContext.Current.User.Identity.Name;, which has worked in the prior tests, but now I have CORS errors.

In IIS I have Windows Authentication enabled, and others disabled (anonymous authentication), but when I visit the website, I get CORS errors, saying the origins are not set. I then tried setting the headers in HTTP Response Headers in IIS, setting the allow origins to http://localhost:4200, allow credentials to true, and allowing all headers and methods, but then i get errors saying, that origins is set twice http://localhost:4200, http://localhost:4200, I also tried turning on anonymous authentication, but then the before mentioned var name = HttpContext.Current.User.Identity.Name; is an empty string.

This is how my cors setup looks like:

var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*")
{
    SupportsCredentials = true,
};

And this is my web.config

...
<system.web>
    <authentication mode="Windows" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
</system.web>
...


问:
Decoding ArrayBuffer(5) from COMARK BT42
I am trying to read the temperature from a Comark BT42. The temperature can be retrieved from the device as an arraybuffer. However trying to turn that into a float has some odd results. My app is ionic angular, target device is a Datalogic Memor 10 (Android)

I have the below method

```<code>pullTemp(id, service, characteristic){
    this.ble.startNotification(id, service, characteristic).subscribe(data => {
      var myArray = new Uint8Array(data[0]);
    var temperatureData = myArray.slice(1,5); // getting bytes 2-5
    var temperature = new Float32Array(new Uint8Array(temperatureData.buffer).reverse().buffer)[0]; // reversing the bytes so as to convert it to little-endian
    console.log(temperature);
      this.readout = temperature + "°C";
  });
  }
</code>```

I get the output "-147578438597117740000" while the reading on the BT42 is "22.5"

Documentation for BT42: https://www.comarkinstruments.net/wp-content/uploads/2022/05/Bluetooth-API-Documentation-20836-3-1.pdf

Body:
I am trying to read the temperature from a Comark BT42. The temperature can be retrieved from the device as an arraybuffer. However trying to turn that into a float has some odd results. My app is ionic angular, target device is a Datalogic Memor 10 (Android)

I have the below method

pullTemp(id, service, characteristic){
    this.ble.startNotification(id, service, characteristic).subscribe(data => {
      var myArray = new Uint8Array(data[0]);
    var temperatureData = myArray.slice(1,5); // getting bytes 2-5
    var temperature = new Float32Array(new Uint8Array(temperatureData.buffer).reverse().buffer)[0]; // reversing the bytes so as to convert it to little-endian
    console.log(temperature);
      this.readout = temperature + "°C";
  });
  }

I get the output "-147578438597117740000" while the reading on the BT42 is "22.5"

Documentation for BT42: https://www.comarkinstruments.net/wp-content/uploads/2022/05/Bluetooth-API-Documentation-20836-3-1.pdf


问:
How CSRF is implemented in OAuth2-proxy?
I am new to OAuth2-proxy, I am using it with keyclock to secure our backend, ouath2-proxy generate CSRF token as cookie which is not recommended by OWSAP can anyone explain why it is implemented using cookie. Additionally, it isonly used in callback request and not in subsequent requests what is the logic behind that?


问:
How to Unit test a MutableStateFlow on Android
I have a class like below:

```<code>class ViewTrackingFlow : ViewTrackingFlowInterface {
private lateinit var onSuc: (input: Int) -> String
private var itemTrackingFlow: MutableStateFlow<Int> = MutableStateFlow(0)

@OptIn(FlowPreview::class)
override suspend fun init(onSuccess: (index: Int) -> String) {
    this.onSuc = onSuccess
    itemTrackingFlow.debounce(THRESHOLD_MS).distinctUntilChanged().flowOn(Dispatchers.Default)
        .collect { groupCardPosition ->
            onSuc(groupCardPosition)
        }
}

override fun postViewEvent(index: Int?) {
    if (index != null) {
        itemTrackingFlow.value = index
    }
}
</code>```

}

the init function is called in a fragment with viewLifecycleOwner.lifecycleScope.launch, it works in the fragment, but in the below unit test class, it does not invode the collect function, the unit test class as below:

```<code>internal class ViewTrackingFlowTest {
private lateinit var trackingFlow: ViewTrackingFlow

@OptIn(ExperimentalCoroutinesApi::class)
private val testCoroutineScope = TestScope(UnconfinedTestDispatcher())

@Before
fun setUp() {
    trackingFlow = ViewTrackingFlow()

}

@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun testOnPostViewEvent() {
    // Given
    val action = mock<(Int) -> String>()
    val job = testCoroutineScope.launch {
        trackingFlow.init(onSuccess = action)
    }

    // When
    job.run {
        trackingFlow.postViewEvent(5)
    }

    // Then
    verify(action).invoke(5)
}
</code>```

}

the action is not invoked in the test environment, I tried to put the trackingFlow.postViewEvent(5) in the testCoroutineScope.launch {:

```<code>  val job = testCoroutineScope.launch {
        trackingFlow.init(onSuccess = action)
        trackingFlow.postViewEvent(5)
    }
</code>```

it doesn't work neither, because the init is a suspend function, the postViewEvent will not be called.

I'm quite new to coroutines testing, can anybody help take a look, many thanks!

Body:
I have a class like below:

class ViewTrackingFlow : ViewTrackingFlowInterface {
private lateinit var onSuc: (input: Int) -> String
private var itemTrackingFlow: MutableStateFlow<Int> = MutableStateFlow(0)

@OptIn(FlowPreview::class)
override suspend fun init(onSuccess: (index: Int) -> String) {
    this.onSuc = onSuccess
    itemTrackingFlow.debounce(THRESHOLD_MS).distinctUntilChanged().flowOn(Dispatchers.Default)
        .collect { groupCardPosition ->
            onSuc(groupCardPosition)
        }
}

override fun postViewEvent(index: Int?) {
    if (index != null) {
        itemTrackingFlow.value = index
    }
}

}

the init function is called in a fragment with viewLifecycleOwner.lifecycleScope.launch, it works in the fragment, but in the below unit test class, it does not invode the collect function, the unit test class as below:

internal class ViewTrackingFlowTest {
private lateinit var trackingFlow: ViewTrackingFlow

@OptIn(ExperimentalCoroutinesApi::class)
private val testCoroutineScope = TestScope(UnconfinedTestDispatcher())

@Before
fun setUp() {
    trackingFlow = ViewTrackingFlow()

}

@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun testOnPostViewEvent() {
    // Given
    val action = mock<(Int) -> String>()
    val job = testCoroutineScope.launch {
        trackingFlow.init(onSuccess = action)
    }

    // When
    job.run {
        trackingFlow.postViewEvent(5)
    }

    // Then
    verify(action).invoke(5)
}

}

the action is not invoked in the test environment, I tried to put the trackingFlow.postViewEvent(5) in the testCoroutineScope.launch {:

  val job = testCoroutineScope.launch {
        trackingFlow.init(onSuccess = action)
        trackingFlow.postViewEvent(5)
    }

it doesn't work neither, because the init is a suspend function, the postViewEvent will not be called.

I'm quite new to coroutines testing, can anybody help take a look, many thanks!


问:
Increase Font Size of Axes: Piper Diagram
I am using the package 'hydrogeo' https://cran.r-project.org/web/packages/hydrogeo/hydrogeo.pdf to create piper plot diagrams.

How can I increase font size of axes

```<code>rm(list=ls())
library(hydrogeo)
l <- list( Ca = c(43,10,73,26,32),
           Mg = c(30,50,3,14,12),
           Cl = c(24,10,12,30,43),
           SO4 = c(24,10,12,30,43))

lp <- piper(l)
lp@pt.pch = c(15,17,18,15,17)
lp@pt.col = c(4,1,3,5,2)
plot( lp, main="Piper-Hill Diagram of Water Quality", cex=1.2)
</code>```

I try with a theme and cex.axis

Body:
I am using the package 'hydrogeo' https://cran.r-project.org/web/packages/hydrogeo/hydrogeo.pdf to create piper plot diagrams.

How can I increase font size of axes

rm(list=ls())
library(hydrogeo)
l <- list( Ca = c(43,10,73,26,32),
           Mg = c(30,50,3,14,12),
           Cl = c(24,10,12,30,43),
           SO4 = c(24,10,12,30,43))

lp <- piper(l)
lp@pt.pch = c(15,17,18,15,17)
lp@pt.col = c(4,1,3,5,2)
plot( lp, main="Piper-Hill Diagram of Water Quality", cex=1.2)

I try with a theme and cex.axis


问:
setOnTouchListener in PhotoView library in Android Studio
I'm using the PhotoView Library to zoom a image in my activity, but I want to use the setOnTouchListener and onTouch method to change the image if I touch in certain area of the screen.
The main problem is if I use fhese methods, I can't zoom anymore, what can I do?
I thinked to create a new class from the PhotoView one, but there isn't any easier way?</p>


问:
Python + Fpdf2: unicode encoding in text_annotation
I am using fpdf2 2.5 to dynamically create a pdf in python 3.6. The pdf contains unicode characters. So far I have handled it like this:

```<code>pdf.add_font('DejaVuSerif', '', FONT_PATH_FOR_PDF + '/DejaVuSerif.ttf', uni=True)
pdf.set_font('DejaVuSerif')
pdf.write_html("<h4><font face='DejaVuSerif'>Text containing unicode</font></h4>")
</code>```

Now I want to use text annotations, and there I am running into problems. I have tried:

```<code>pdf.text_annotation(x=currentX, y=currentY, text=u"καλημέρα")
</code>```

and

```<code>pdf.text_annotation(x=currentX, y=currentY, text=my_text_variable)
</code>```

In both cases I get an error:

```<code>UnicodeEncodeError: 'latin-1' codec can't encode characters in position 230-237: ordinal not in range(256)
</code>```

Does anyone know how to set the encoding for text annotations to Unicode?

Body:
I am using fpdf2 2.5 to dynamically create a pdf in python 3.6. The pdf contains unicode characters. So far I have handled it like this:

pdf.add_font('DejaVuSerif', '', FONT_PATH_FOR_PDF + '/DejaVuSerif.ttf', uni=True)
pdf.set_font('DejaVuSerif')
pdf.write_html("
Text containing unicode
")

Now I want to use text annotations, and there I am running into problems. I have tried:

pdf.text_annotation(x=currentX, y=currentY, text=u"καλημέρα")

and

pdf.text_annotation(x=currentX, y=currentY, text=my_text_variable)

In both cases I get an error:

UnicodeEncodeError: 'latin-1' codec can't encode characters in position 230-237: ordinal not in range(256)

Does anyone know how to set the encoding for text annotations to Unicode?


问:
Realistic p5.js DOM object collision simulation
I'm trying to build a physics simulation where DOM objects are subjected to gravity and can be dragged and thrown around while still colliding with each other and reaction to the collision in realistic ways.

As a reference: https://lovehotel.world/home

The main issue in doing such a thing is that checking for the collision of the DOM elements and having them to realistically react to it it gets super messy, mainly because we're talking about rectangles from a geometric point of view.

The issues I've been encountering are then many, mainly that it's quite easy to do with ellipses native to p5.js (codepen for that: https://codepen.io/giambrodo/pen/LYBxMZZ)

When it's about building it using links for instance it gets quite messy, I understand that checking for the rectangle collision is super messy compared to a perfect circle (where the distance from center to border is always the same).

I managed to get the links to replace the ellipses: https://editor.p5js.org/giampo/sketches/SzRduNmSm

```<code>{ "links": [
    {
        "label": "who are you?",
        "section_link": "who"
    },
    {
        "label": "what do you do?",
        "section_link": "what"
    },
    {
        "label": "how do you do that?",
        "section_link": "how?"
    },
    {
        "label": "why?",
        "section_link": "why"
    },
    {
        "label": "where?",
        "section_link": "where"
    }
]
}
</code>```
```<code>let numBalls = 13;
let spring = 0.05;
let gravity = 0.05;
let friction = -0.9;
let balls = [];
let menuData;

function preload() {
    menuData = loadJSON('menu.json');
}

function setup() {
    createCanvas(500, 500);
    for (let i = 0; i < menuData.links.length; i++) {
    balls[i] = new Ball(
      random(width),
      random(height),
      random(30, 40),
      i,
      balls
    );
  }
  noStroke();
  fill(255, 204);
}

function draw() {
  background(0);
  balls.forEach(ball => {
    ball.collide();
    ball.move();
    ball.display();
  });
}

function mousePressed() {
    balls.forEach(ball => {
        if ( ball.onBall(mouseX, mouseY))
        ball.startDrag();
      }
    );
  }

function mouseDragged() {
    balls.forEach(ball => {
      if (ball.dragging) {
        ball.x = mouseX;
        ball.y = mouseY;
      }
    });
  }

function mouseReleased() {
    balls.forEach(ball => {
      if (ball.dragging) {
        // Calculate the ball's new velocity based on how fast the mouse was moving when it was released
        ball.vx = (mouseX - ball.mousex) / 10;
        ball.vy = (mouseY - ball.mousey) / 10;

        // Set the ball's dragging property to false to indicate that it is no longer being dragged
        ball.dragging = false;
      }
    });
  }

class Ball {
  constructor(xin, yin, din, idin, oin) {
    this.x = xin;
    this.y = yin;
    this.vx = 0;
    this.vy = 0;
    this.diameter = din;
    this.id = idin;
    this.others = oin;
    this.dragging = false;
    this.anchor = createA(menuData.links[this.id].href, menuData.links[this.id].label);
  }

onBall(x, y) {
    // Get the bounding rect of the anchor element
    let rect = this.anchor.elt.getBoundingClientRect();

    // Check if the point (x, y) is within the bounding rect
    return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
  }

  startDrag() {
    this.dragging = true;
    this.mousex = mouseX;
    this.mousey = mouseY;
  }

  collide() {
    for (let i = this.id + 1; i < menuData.links.length; i++) {
      // Calculate distance and minimum distance between rectangles
      let dx = this.others[i].anchor.elt.getBoundingClientRect().x - this.anchor.elt.getBoundingClientRect().x;
      let dy = this.others[i].anchor.elt.getBoundingClientRect().y - this.anchor.elt.getBoundingClientRect().y;
      let distance = sqrt(dx * dx + dy * dy);
      let minDist = (this.others[i].anchor.elt.getBoundingClientRect().width + this.anchor.elt.getBoundingClientRect().width) / 2;

      // Check if rectangles are colliding
      if (distance < minDist) {
        // Calculate angle between rectangles
        let angle = atan2(dy, dx);
        // Calculate target position for rectangles to avoid overlap
        let targetX = this.anchor.elt.getBoundingClientRect().x + cos(angle) * minDist;
        let targetY = this.anchor.elt.getBoundingClientRect().y + sin(angle) * minDist;
        // Calculate force of collision using mass and elasticity
        let ax = (targetX - this.others[i].anchor.elt.getBoundingClientRect().x) * spring;
        let ay = (targetY - this.others[i].anchor.elt.getBoundingClientRect().y) * spring;
        this.vx -= ax;
        this.vy -= ay;
        this.others[i].vx += ax;
        this.others[i].vy += ay;
      }
    }
  }

  move() {

    if (this.dragging) {
        this.x = mouseX;
        this.y = mouseY;
    } else {
        // gravità
        this.vy += gravity;
        // update ball's position based on its velocity
        this.x += this.vx;
        this.y += this.vy;

        if (this.x + this.diameter / 2 > width) {
        this.x = width - this.diameter / 2;
        this.vx *= friction;
        } else if (this.x - this.diameter / 2 < 0) {
        this.x = this.diameter / 2;
        this.vx *= friction;
        }
        if (this.y + this.diameter / 2 > height) {
        this.y = height - this.diameter / 2;
        this.vy *= friction;
        } else if (this.y - this.diameter / 2 < 0) {
        this.y = this.diameter / 2;
        this.vy *= friction;
        }
    }
  }

  display() {
    this.anchor.style('position: relative');
    this.anchor.position(this.x, this.y);
    this.anchor.style('z-index: 3)');
    this.anchor.parent('maradona');
    this.anchor.style('border-style: solid');
    this.anchor.style('border-color: red');
  }
}

</code>```

Can someone help me in finding a better way to deal with this?

Body:
I'm trying to build a physics simulation where DOM objects are subjected to gravity and can be dragged and thrown around while still colliding with each other and reaction to the collision in realistic ways.

As a reference: https://lovehotel.world/home

The main issue in doing such a thing is that checking for the collision of the DOM elements and having them to realistically react to it it gets super messy, mainly because we're talking about rectangles from a geometric point of view.

The issues I've been encountering are then many, mainly that it's quite easy to do with ellipses native to p5.js (codepen for that: https://codepen.io/giambrodo/pen/LYBxMZZ)

When it's about building it using links for instance it gets quite messy, I understand that checking for the rectangle collision is super messy compared to a perfect circle (where the distance from center to border is always the same).

I managed to get the links to replace the ellipses: https://editor.p5js.org/giampo/sketches/SzRduNmSm

{ "links": [
    {
        "label": "who are you?",
        "section_link": "who"
    },
    {
        "label": "what do you do?",
        "section_link": "what"
    },
    {
        "label": "how do you do that?",
        "section_link": "how?"
    },
    {
        "label": "why?",
        "section_link": "why"
    },
    {
        "label": "where?",
        "section_link": "where"
    }
]
}

let numBalls = 13;
let spring = 0.05;
let gravity = 0.05;
let friction = -0.9;
let balls = [];
let menuData;

function preload() {
    menuData = loadJSON('menu.json');
}

function setup() {
    createCanvas(500, 500);
    for (let i = 0; i < menuData.links.length; i++) {
    balls[i] = new Ball(
      random(width),
      random(height),
      random(30, 40),
      i,
      balls
    );
  }
  noStroke();
  fill(255, 204);
}

function draw() {
  background(0);
  balls.forEach(ball => {
    ball.collide();
    ball.move();
    ball.display();
  });
}

function mousePressed() {
    balls.forEach(ball => {
        if ( ball.onBall(mouseX, mouseY))
        ball.startDrag();
      }
    );
  }

function mouseDragged() {
    balls.forEach(ball => {
      if (ball.dragging) {
        ball.x = mouseX;
        ball.y = mouseY;
      }
    });
  }

function mouseReleased() {
    balls.forEach(ball => {
      if (ball.dragging) {
        // Calculate the ball's new velocity based on how fast the mouse was moving when it was released
        ball.vx = (mouseX - ball.mousex) / 10;
        ball.vy = (mouseY - ball.mousey) / 10;

        // Set the ball's dragging property to false to indicate that it is no longer being dragged
        ball.dragging = false;
      }
    });
  }

class Ball {
  constructor(xin, yin, din, idin, oin) {
    this.x = xin;
    this.y = yin;
    this.vx = 0;
    this.vy = 0;
    this.diameter = din;
    this.id = idin;
    this.others = oin;
    this.dragging = false;
    this.anchor = createA(menuData.links[this.id].href, menuData.links[this.id].label);
  }

onBall(x, y) {
    // Get the bounding rect of the anchor element
    let rect = this.anchor.elt.getBoundingClientRect();

    // Check if the point (x, y) is within the bounding rect
    return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
  }

  startDrag() {
    this.dragging = true;
    this.mousex = mouseX;
    this.mousey = mouseY;
  }

  collide() {
    for (let i = this.id + 1; i < menuData.links.length; i++) {
      // Calculate distance and minimum distance between rectangles
      let dx = this.others[i].anchor.elt.getBoundingClientRect().x - this.anchor.elt.getBoundingClientRect().x;
      let dy = this.others[i].anchor.elt.getBoundingClientRect().y - this.anchor.elt.getBoundingClientRect().y;
      let distance = sqrt(dx * dx + dy * dy);
      let minDist = (this.others[i].anchor.elt.getBoundingClientRect().width + this.anchor.elt.getBoundingClientRect().width) / 2;

      // Check if rectangles are colliding
      if (distance < minDist) {
        // Calculate angle between rectangles
        let angle = atan2(dy, dx);
        // Calculate target position for rectangles to avoid overlap
        let targetX = this.anchor.elt.getBoundingClientRect().x + cos(angle) * minDist;
        let targetY = this.anchor.elt.getBoundingClientRect().y + sin(angle) * minDist;
        // Calculate force of collision using mass and elasticity
        let ax = (targetX - this.others[i].anchor.elt.getBoundingClientRect().x) * spring;
        let ay = (targetY - this.others[i].anchor.elt.getBoundingClientRect().y) * spring;
        this.vx -= ax;
        this.vy -= ay;
        this.others[i].vx += ax;
        this.others[i].vy += ay;
      }
    }
  }

  move() {

    if (this.dragging) {
        this.x = mouseX;
        this.y = mouseY;
    } else {
        // gravità
        this.vy += gravity;
        // update ball's position based on its velocity
        this.x += this.vx;
        this.y += this.vy;

        if (this.x + this.diameter / 2 > width) {
        this.x = width - this.diameter / 2;
        this.vx *= friction;
        } else if (this.x - this.diameter / 2 < 0) {
        this.x = this.diameter / 2;
        this.vx *= friction;
        }
        if (this.y + this.diameter / 2 > height) {
        this.y = height - this.diameter / 2;
        this.vy *= friction;
        } else if (this.y - this.diameter / 2 < 0) {
        this.y = this.diameter / 2;
        this.vy *= friction;
        }
    }
  }

  display() {
    this.anchor.style('position: relative');
    this.anchor.position(this.x, this.y);
    this.anchor.style('z-index: 3)');
    this.anchor.parent('maradona');
    this.anchor.style('border-style: solid');
    this.anchor.style('border-color: red');
  }
}

Can someone help me in finding a better way to deal with this?


问:
Problem with the JWT token to interact with google cloud
The following code is used to create a JWT for a google cloud service called fleetengine this code was working and suddenly it creates a wrong token the sad thing is that it is working on my friend's device with the same code without any changes.</p>
```<code>def generate_token(role='server', **kwargs):
        iat = time.time()
        exp = iat + 3600
        if role == 'consumer':
            iss = CONSUMER_SERVICE_ACCOUNT_EMAIL
            sub = CONSUMER_SERVICE_ACCOUNT_EMAIL
            authorization = {
                "trackingid": kwargs.get('tracking_id')
            }

        elif role == 'driver':
            iss = DRIVER_SERVICE_ACCOUNT_EMAIL
            sub = DRIVER_SERVICE_ACCOUNT_EMAIL
            authorization = {
                "deliveryvehicleid": kwargs.get('vehicle_id')
            }

        else:
            iss = SERVER_SERVICE_ACCOUNT_EMAIL
            sub = SERVER_SERVICE_ACCOUNT_EMAIL
            authorization = {
                "taskids": ["*"],
                "deliveryvehicleid": "*",
                "tripid": "*",
                "vehicleid": "*"
            }

        payload = {'iss': iss,
                   'sub': sub,
                   'aud': 'https://fleetengine.googleapis.com/',
                   'iat': iat,
                   'exp': exp,
                   "authorization": authorization,
                   }

        private_key = SERVER_GOOGLE_FLEET_ENGINE_SECRET_KEY.replace('\\n', '\n')
        additional_headers = {'kid': SERVER_GOOGLE_FLEET_KEY_ID, 'alg': 'RS256', 'typ': 'JWT'}
        signed_jwt = jwt.encode(payload, private_key, headers=additional_headers)
        return str(signed_jwt), iat, exp
</code>```

Body:
The following code is used to create a JWT for a google cloud service called fleetengine this code was working and suddenly it creates a wrong token the sad thing is that it is working on my friend's device with the same code without any changes.

def generate_token(role='server', **kwargs):
        iat = time.time()
        exp = iat + 3600
        if role == 'consumer':
            iss = CONSUMER_SERVICE_ACCOUNT_EMAIL
            sub = CONSUMER_SERVICE_ACCOUNT_EMAIL
            authorization = {
                "trackingid": kwargs.get('tracking_id')
            }

        elif role == 'driver':
            iss = DRIVER_SERVICE_ACCOUNT_EMAIL
            sub = DRIVER_SERVICE_ACCOUNT_EMAIL
            authorization = {
                "deliveryvehicleid": kwargs.get('vehicle_id')
            }

        else:
            iss = SERVER_SERVICE_ACCOUNT_EMAIL
            sub = SERVER_SERVICE_ACCOUNT_EMAIL
            authorization = {
                "taskids": ["*"],
                "deliveryvehicleid": "*",
                "tripid": "*",
                "vehicleid": "*"
            }

        payload = {'iss': iss,
                   'sub': sub,
                   'aud': 'https://fleetengine.googleapis.com/',
                   'iat': iat,
                   'exp': exp,
                   "authorization": authorization,
                   }

        private_key = SERVER_GOOGLE_FLEET_ENGINE_SECRET_KEY.replace('\\n', '\n')
        additional_headers = {'kid': SERVER_GOOGLE_FLEET_KEY_ID, 'alg': 'RS256', 'typ': 'JWT'}
        signed_jwt = jwt.encode(payload, private_key, headers=additional_headers)
        return str(signed_jwt), iat, exp


问:
Devise re-directing continuously when it should not
The following behaviour is observed in testing controller actions; they are boilerplate actions from a new application, where authorization will gradually be built into.

```<code>class ContactsController < ApplicationController
  before_action :set_contact, only: %i[ show edit update destroy ]

  def new
    @contact = Contact.new
  end
</code>```

The tests (using Minitest) return unexpected results (shown inline)

```<code>require "test_helper"

class ContactsControllerTest < ActionDispatch::IntegrationTest
  include Devise::Test::IntegrationHelpers

  setup do
    @contact = contacts(:one)
    @admin = users(:admin)
    @one = users(:one)
    @two = users(:two)
  end

  test "blank slate" do
    get new_contact_url
    assert_response :success
  end
=> 1 assertions

  test "should get new" do
    sign_in @admin
    get new_contact_url
    assert_response :success
  end
=>  was a <302: Found> redirect to <http://www.example.com/users/sign_in>

  test "fail test just to see what happens" do
    sign_in @one
    get new_contact_url
    assert_redirected_to root_path
  end
=> Expected response to be a redirect to <http://www.example.com/> but was a redirect to <http://www.example.com/users/sign_in>.
</code>```

when before_action :authenticate_user! is added at top of controller, the first test fails with:

```<code>Expected response to be a <2XX: success>, but was a <302: Found> redirect to <http://www.example.com/users/sign_in>
</code>```

and the latter two fail with the same result as previously.

The test helper is bare bones.

```<code>ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"

class ActiveSupport::TestCase
  parallelize(workers: :number_of_processors)

  fixtures :all

end
</code>```

rails generate devise:controllers was run but all actionable lines are commented out.  The only basic difference is that the application_controller.rb has

```<code>  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
    attributes = [:email, :password, :password_confirmation, :name_last, :name_first, :public_persona]
    devise_parameter_sanitizer.permit(:sign_up, keys: attributes)
    devise_parameter_sanitizer.permit(:account_update, keys: attributes)
  end
</code>```

There are no references to redirect_to new_user_session_path anywhere in the code.

```<code>Ruby 3.1.2
Rails 7.0.4
Devise 4.8.1
</code>```

Why is devise consistently re-directing to new_user_session_path on authentication?

Body:
The following behaviour is observed in testing controller actions; they are boilerplate actions from a new application, where authorization will gradually be built into.

class ContactsController < ApplicationController
  before_action :set_contact, only: %i[ show edit update destroy ]

  def new
    @contact = Contact.new
  end

The tests (using Minitest) return unexpected results (shown inline)

require "test_helper"

class ContactsControllerTest < ActionDispatch::IntegrationTest
  include Devise::Test::IntegrationHelpers

  setup do
    @contact = contacts(:one)
    @admin = users(:admin)
    @one = users(:one)
    @two = users(:two)
  end

  test "blank slate" do
    get new_contact_url
    assert_response :success
  end
=> 1 assertions

  test "should get new" do
    sign_in @admin
    get new_contact_url
    assert_response :success
  end
=>  was a <302: Found> redirect to <http://www.example.com/users/sign_in>

  test "fail test just to see what happens" do
    sign_in @one
    get new_contact_url
    assert_redirected_to root_path
  end
=> Expected response to be a redirect to <http://www.example.com/> but was a redirect to <http://www.example.com/users/sign_in>.

when before_action :authenticate_user! is added at top of controller, the first test fails with:

Expected response to be a <2XX: success>, but was a <302: Found> redirect to <http://www.example.com/users/sign_in>

and the latter two fail with the same result as previously.

The test helper is bare bones.

ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"

class ActiveSupport::TestCase
  parallelize(workers: :number_of_processors)

  fixtures :all

end

rails generate devise:controllers was run but all actionable lines are commented out.  The only basic difference is that the application_controller.rb has

  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
    attributes = [:email, :password, :password_confirmation, :name_last, :name_first, :public_persona]
    devise_parameter_sanitizer.permit(:sign_up, keys: attributes)
    devise_parameter_sanitizer.permit(:account_update, keys: attributes)
  end

There are no references to redirect_to new_user_session_path anywhere in the code.

Ruby 3.1.2
Rails 7.0.4
Devise 4.8.1

Why is devise consistently re-directing to new_user_session_path on authentication?


问:
Gradle finish clean task before running assemble tasks
I've created a custom task in the project's build.gradle file like so:

```<code>task buildAllForAppRelease {
    dependsOn(':clean', 'app:assembleDebug', ':clean', 'app:assembleRelease', 'app:bundleRelease')
}
</code>```

The apks and bundles are all built, but the clean task doesn't seem to do anything.
It shows up in the build output but no files are getting deleted.

When I run the clean task directly, it does what it is supposed to do.

How can I ensure, that clean task is actually run before the other tasks?

Btw. I've set org.gradle.paralell=true, but that shouldn't have an influence, does it?

Body:
I've created a custom task in the project's build.gradle file like so:

task buildAllForAppRelease {
    dependsOn(':clean', 'app:assembleDebug', ':clean', 'app:assembleRelease', 'app:bundleRelease')
}

The apks and bundles are all built, but the clean task doesn't seem to do anything.
It shows up in the build output but no files are getting deleted.

When I run the clean task directly, it does what it is supposed to do.

How can I ensure, that clean task is actually run before the other tasks?

Btw. I've set org.gradle.paralell=true, but that shouldn't have an influence, does it?


问:
How do I mock a object creation inside the contructor in Mockito
Here is what I want to achieve.

```<code>public class A {
    protected final Config config;
    protected final Connection connection;

    public A(Config config) {
        this.config = config;
        this.connection = new Connection("a", "b");
    }

    public void someMethod() {
    }
}
</code>```

When I try to test some underlying methods for the class A, I would want to mock the connection object creation. How can I do that, I have tried all possible ways but didn't find any luck.

Body:
Here is what I want to achieve.

public class A {
    protected final Config config;
    protected final Connection connection;

    public A(Config config) {
        this.config = config;
        this.connection = new Connection("a", "b");
    }

    public void someMethod() {
    }
}

When I try to test some underlying methods for the class A, I would want to mock the connection object creation. How can I do that, I have tried all possible ways but didn't find any luck.


问:
typescript and vuejs export interface reach
hello i have a problem i have an auth module i want to access the value which is interface in this file from another vue file how can i do that

What I really want to do is to access name, surname and email information.

```<code>export interface User {
 name: string;
 surname: string;
 email: string;
}

export interface ExUserAuthInfo {
 user: User;
 isAuthenticated: boolean;
}

 @Module
 export default class ExAuthModule extends VuexModule implements ExUserAuthInfo {
 user = {} as User;
 isAuthenticated = !!ExJwtService.getAccessToken();

 get currentUser(): User {
 return this.user;
 }

 get isUserAuthenticated(): boolean {
return this.isAuthenticated;
 }
</code>```

Body:
hello i have a problem i have an auth module i want to access the value which is interface in this file from another vue file how can i do that

What I really want to do is to access name, surname and email information.

export interface User {
 name: string;
 surname: string;
 email: string;
}

export interface ExUserAuthInfo {
 user: User;
 isAuthenticated: boolean;
}

 @Module
 export default class ExAuthModule extends VuexModule implements ExUserAuthInfo {
 user = {} as User;
 isAuthenticated = !!ExJwtService.getAccessToken();

 get currentUser(): User {
 return this.user;
 }

 get isUserAuthenticated(): boolean {
return this.isAuthenticated;
 }


问:
Error: Invariant Violation: requireNativeComponent "GestureHandlerRootView" in the "UIManager"
I am getting this error when I execute Release variant of app and just Android. It doesnt happen on Android Debug mode and neither on iOS. The Splash screen show until the js is loaded, then it crash. When I dismiss the error message the Splash screen is still there.

I tried to reinstall node_modules, read the react-native-gesture-handler documentation and other obvious stuff. The Android Release app keeps crashing on that same error. They say it can be related to expo-cli, but I dont use Expo.

Do you have any ideas please? Thank you very much.

This is my App.js.

```<code>export default function App() {
  return (
    <GestureHandlerRootView style={{flex: 1}}>
      <View style={{flex: 1}}></View>
      {/*<AppRoot />*/}
    </GestureHandlerRootView>
  );
}
</code>```

I expect the app would load correctly.

Body:
I am getting this error when I execute Release variant of app and just Android. It doesnt happen on Android Debug mode and neither on iOS. The Splash screen show until the js is loaded, then it crash. When I dismiss the error message the Splash screen is still there.

I tried to reinstall node_modules, read the react-native-gesture-handler documentation and other obvious stuff. The Android Release app keeps crashing on that same error. They say it can be related to expo-cli, but I dont use Expo.

Do you have any ideas please? Thank you very much.

This is my App.js.

export default function App() {
  return (
    <GestureHandlerRootView style={{flex: 1}}>
      <View style={{flex: 1}}></View>
      {/*<AppRoot />*/}
    </GestureHandlerRootView>
  );
}

I expect the app would load correctly.


问:
Input box inside the SVG shows black color on focus
I am drawing the svg which has three rectangles, and each rectangle has specific text(label). I have a requirement to be able to edit the text and it should take the label defined by user.
I tried few things like using input box and also contenteditable true attribute for the text, to edit the SVG text. Unfortunately, contenteditable is not working and using input box works partially. The issue with input box is that when i focus on the input, I see black color as shown in snapshot below and not sure from where it is taking. Since I am getting issue when the input box is focused, I am not able to debug as well, since when I click inspect element, the focus gets loose and there won't be any black color to debug. I am not sure if the black color is related to some font issue or something else, tried altering font but nothing worked.
I have shared the part of my code.

```<code>const drawSvg= svg.append("g")
. append("rect")
.attr("id", "myRect")
. style("fill", function (d) {color});
g.selectAll("g"). append("text").attr("id", "myText").on("click", textClick)
.text (function (d) {return label;});
g.selectAll("g").append("foreignObject")

function textClick(evt) {
let originalText = evt.target.innerHTML
const input = document.createElement("input");
input.value = originalText;
input.onkeyup = function(e) {
evt.target.innerHTML = input.value;
};
input.onfocus = function(e) {
evt.target.innerHTML = input.value;
};
input.onblur = function(e) {
input.remove();
};
input.style.fontSize = "1.25em"
input.style.padding = "0"
input.style.border = "none"
input.style.height = "1px"
input.style.width = "4px"
const myCells = document.querySelectorAll('.myForeignObject');
for (let i=0; i < myCells.length; i++) {
myCells[i].appendChild(input)
}
}
</code>```

Body:
I am drawing the svg which has three rectangles, and each rectangle has specific text(label). I have a requirement to be able to edit the text and it should take the label defined by user.
I tried few things like using input box and also contenteditable true attribute for the text, to edit the SVG text. Unfortunately, contenteditable is not working and using input box works partially. The issue with input box is that when i focus on the input, I see black color as shown in snapshot below and not sure from where it is taking. Since I am getting issue when the input box is focused, I am not able to debug as well, since when I click inspect element, the focus gets loose and there won't be any black color to debug. I am not sure if the black color is related to some font issue or something else, tried altering font but nothing worked.
I have shared the part of my code.

const drawSvg= svg.append("g")
. append("rect")
.attr("id", "myRect")
. style("fill", function (d) {color});
g.selectAll("g"). append("text").attr("id", "myText").on("click", textClick)
.text (function (d) {return label;});
g.selectAll("g").append("foreignObject")

function textClick(evt) {
let originalText = evt.target.innerHTML
const input = document.createElement("input");
input.value = originalText;
input.onkeyup = function(e) {
evt.target.innerHTML = input.value;
};
input.onfocus = function(e) {
evt.target.innerHTML = input.value;
};
input.onblur = function(e) {
input.remove();
};
input.style.fontSize = "1.25em"
input.style.padding = "0"
input.style.border = "none"
input.style.height = "1px"
input.style.width = "4px"
const myCells = document.querySelectorAll('.myForeignObject');
for (let i=0; i < myCells.length; i++) {
myCells[i].appendChild(input)
}
}