问:
Typing inside TextView causes entire layout/screen to "vibrate"
I have the following layout:

```<code><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingStart="@dimen/side_margin"
            android:paddingTop="@dimen/layout_margin_large"
            android:paddingEnd="@dimen/side_margin"
            android:paddingBottom="@dimen/layout_margin_default">

            <!-- Some oother stuff....-->

            <com.google.android.material.textview.MaterialTextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/layout_margin_default"
                android:text="@string/optional_data" />

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/brand"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_store_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/model"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_directions_car_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/build_year"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_event_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="date" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/license_plate"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_pin_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/vin"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_shield_car_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/note"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_notes_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textMultiLine"
                    android:minLines="3"
                />
            </com.google.android.material.textfield.TextInputLayout>

        </LinearLayout>

    </androidx.core.widget.NestedScrollView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

</code>```

Which looks like this:
https://jmp.sh/v/YgokjVB6XvyHAQqvoFlK

As you can see from the video, the issue I'm having is that when typing in the last TextInputEditText, my entire layout/screen starts to vibrate/shake, at least when I am in the first two line, when typing in my minLine (3) the vibration/shake stop or when I move the keyboard a little bit above the bottom line.

Removing the minLine attribute would solve the problem, however I want to set a minimum amount of lines/minimum height and the optimal way to do this is by using the minLine attribute.

I'm wondering what the issue might be? Is it maybe cause I don't have enough margin to the navigation bar?

Body:
I have the following layout:

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingStart="@dimen/side_margin"
            android:paddingTop="@dimen/layout_margin_large"
            android:paddingEnd="@dimen/side_margin"
            android:paddingBottom="@dimen/layout_margin_default">

            <com.google.android.material.textview.MaterialTextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/layout_margin_default"
                android:text="@string/optional_data" />

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/brand"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_store_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/model"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_directions_car_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/build_year"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_event_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="date" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/license_plate"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_pin_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/vin"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_shield_car_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/note"
                android:layout_marginTop="@dimen/layout_margin_default"
                app:startIconDrawable="@drawable/baseline_notes_24">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textMultiLine"
                    android:minLines="3"
                />
            </com.google.android.material.textfield.TextInputLayout>

        </LinearLayout>

    </androidx.core.widget.NestedScrollView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Which looks like this:
https://jmp.sh/v/YgokjVB6XvyHAQqvoFlK

As you can see from the video, the issue I'm having is that when typing in the last TextInputEditText, my entire layout/screen starts to vibrate/shake, at least when I am in the first two line, when typing in my minLine (3) the vibration/shake stop or when I move the keyboard a little bit above the bottom line.

Removing the minLine attribute would solve the problem, however I want to set a minimum amount of lines/minimum height and the optimal way to do this is by using the minLine attribute.

I'm wondering what the issue might be? Is it maybe cause I don't have enough margin to the navigation bar?


来源: stackexchange

问:
Creating ref in child component and set state in parent component will it mount and state be updated?
I have ref in child and updatestate in parent. Whenever any changes occur Updatestate is called. Will the State be updated?

Should I need to mount?

Note: In my case I couldn’t able to create ref in parent and pass it to child, formRef is always null, so I have to create it in child only.

```<code>//parent component with state and setState function

Class parent(){
 Constructor(props){
   Super(props)

 this.updateState =     this.updateState.bind(this)
}

updateState = (stateObj, afterUpdate = () => {} ) {
this.setState(stateObj, afterUpdate)
}

render(
   return(<child state = {this.state} />)
 )
</code>```

}

```<code>// child component

Class child() {
 Constructor(props){
  Super(props)

 // Creating ref in child and passing to child’s of this component

  this.ref = React.createRef()
 }

 // When a change is happened this triggers parents updateState function
handleChange(){
 this.props.updateState(key, Value)
}

render()

   // passing ref to childs and onChange event

}
</code>```

Kindly help

ContentLicense: CC BY-SA 4.0

Body:
I have ref in child and updatestate in parent. Whenever any changes occur Updatestate is called. Will the State be updated?

Should I need to mount?

Note: In my case I couldn’t able to create ref in parent and pass it to child, formRef is always null, so I have to create it in child only.

//parent component with state and setState function

Class parent(){
 Constructor(props){
   Super(props)

 this.updateState =     this.updateState.bind(this)
}

updateState = (stateObj, afterUpdate = () => {} ) {
this.setState(stateObj, afterUpdate)
}

render(
   return(<child state = {this.state} />)
 )

}

// child component

Class child() {
 Constructor(props){
  Super(props)

 // Creating ref in child and passing to child’s of this component

  this.ref = React.createRef()
 }

 // When a change is happened this triggers parents updateState function
handleChange(){
 this.props.updateState(key, Value)
}

render()

   // passing ref to childs and onChange event

}

Kindly help


问:
refinerycms constraints breaks routes
i'm running rails 3.0.10 on ruby-1.8.7p352. i installed refinerycms 1.0.8 and tried to block all access to the backend for all ip's except a whitelist. i did it by editing my routes.rb to:

```<code>TestWhitelist::Application.routes.draw do
  match "/refinery" => redirect( "/" ), :constraints => lambda{ |req| req.remote_ip != "127.0.0.1" }
end
</code>```

This approach works great if i try to access /refinery from another ip than 127.0.0.1. if i try to access /refinery from 127.0.0.1 i get a "No route matches /refinery".

ContentLicense: CC BY-SA 3.0

Title: refinerycms constraints breaks routes

Body:
i'm running rails 3.0.10 on ruby-1.8.7p352. i installed refinerycms 1.0.8 and tried to block all access to the backend for all ip's except a whitelist. i did it by editing my routes.rb to:

TestWhitelist::Application.routes.draw do
  match "/refinery" => redirect( "/" ), :constraints => lambda{ |req| req.remote_ip != "127.0.0.1" }
end

This approach works great if i try to access /refinery from another ip than 127.0.0.1. if i try to access /refinery from 127.0.0.1 i get a "No route matches /refinery".


问:
Are IHttpHandlers blocked by Googles redirect actions of blocking http links on https website pages?
Just last week many pages on my website were being reported by Google Webmaster with 'Page is not indexed: Redirect Error.  Turns out that is message is generated on pages of an https:// site which has links to http:// sites, to include google.

This situation is actually easy to remedy by verifying that the http:// links are actually to a https:// site and then changing the link on the page to make the URL https://.  Google then will accept the revised page for indexing.

But, immediately on changing the links to https:// and uploading them to the server, all images on the site which were retrieved from a sql database via a IHttpHandler would not load.  The only change that I have made to my website is the changes noted above.  Chrome developer tool is saying the images are not loading due to a 500 error.  I have spent a week trying to find a way around this problem. I contacted my ISP but have not received a response from them. I may be wrong but I feel the problem is coming from the site being https:// and the Handler being Http:// Google developer tool gives the error message concerning the images as 'Failed to load resource: the server responded with a status of 500 () and then the message points to Handler.ashx:1.

The site is relatively new, 4 years or so, but worked just fine until I changed the http://.  The code to retrieve the images is <asp:Image ID="ImageA" itemprop="image" CssClass="image3" runat="server" ImageUrl='<%# "~/Handler.ashx?RecipeID=" + Eval("RecipeID")%>' BorderStyle="Inset"
AlternateText="Picture of Food"/>  The RecipeID is rendered by a sql query.  Of note, other query information, i.e., recipe description, is retrieved from the sql database via the same query just fine but does not use the IHttpHandler.

I would appreciate any guidance on how to have images load via a sql query without using IHttpHandler or is the opinion that the http in the handler is not causing the problem.


问:
Accessing other classes inside a class Javascript
I am trying to make a simple breakout game with p5js. I got the balls to work fine, but when I try to make them interact with the brick class, I run into some problems. I can't seem to figure ourI don't have a ton of experience with classes in javascript, so this is a little confusing to me. Here is the code:

`

```<code>//Variables
let scene = 0;
let paddlex = 250;
let paddlespeed = 10;
let allBalls = [];

class Brick {
  constructor(brickX, brickY, brickW, brickH) {
    this.brickX = brickX
    this.brickY = brickY
    this.brickW = brickW
    this.brickH = brickH
    this.brickAlive = true
  }
  display(){
    push()
    if(this.brickAlive){
      fill("red")
      rect(this.brickX, this.brickY, this.brickW, this.brickH)
    }
    pop()
  }
}
class Ball {
  constructor(x, y, w, xdir, ydir) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.xdir = xdir;
    this.ydir = ydir;
    this.alive = true;
    allBalls.push(this);
  }
  move() {
    this.x += this.xdir;
    this.y += this.ydir;
    //Bounce off walls
    if (this.x >= 600 - this.w / 2) {
      this.xdir = this.xdir * -1;
    }
    if (this.x <= 0 + this.w / 2) {
      this.xdir = this.xdir * -1;
    }
    if (this.y <= 0 + this.w / 2) {
      this.ydir = this.ydir * -1;
    }
    if (this.y >= 400 + this.w / 2) {
      this.alive = false;
    }
    if (
      this.y >= 360 - this.w / 2 &&
      this.y <= 380 &&
      this.x >= paddlex &&
      this.x <= paddlex + 100
    ) {
      this.ydir = this.ydir * -1;
    }
  }
  show() {
    if (this.alive) {
      push();
      fill(0);
      ellipse(this.x, this.y, this.w, this.w);
      pop();
    }
  }
  //I believe this part is causing the error
  collide(brick){
    if(this.x >= brick.brickX && this.x <= brick.brickX + brick.brickW && this.y <= brick.brickY + brick.brickH){
      console.log("HI")
      brick.brickAlive = false
    }
  }
}

</code>```

`

I recieved an error that said "TypeError: Cannot read properties of undefined (reading 'brickX')"

Body:
I am trying to make a simple breakout game with p5js. I got the balls to work fine, but when I try to make them interact with the brick class, I run into some problems. I can't seem to figure ourI don't have a ton of experience with classes in javascript, so this is a little confusing to me. Here is the code:

`

//Variables
let scene = 0;
let paddlex = 250;
let paddlespeed = 10;
let allBalls = [];

class Brick {
  constructor(brickX, brickY, brickW, brickH) {
    this.brickX = brickX
    this.brickY = brickY
    this.brickW = brickW
    this.brickH = brickH
    this.brickAlive = true
  }
  display(){
    push()
    if(this.brickAlive){
      fill("red")
      rect(this.brickX, this.brickY, this.brickW, this.brickH)
    }
    pop()
  }
}
class Ball {
  constructor(x, y, w, xdir, ydir) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.xdir = xdir;
    this.ydir = ydir;
    this.alive = true;
    allBalls.push(this);
  }
  move() {
    this.x += this.xdir;
    this.y += this.ydir;
    //Bounce off walls
    if (this.x >= 600 - this.w / 2) {
      this.xdir = this.xdir * -1;
    }
    if (this.x <= 0 + this.w / 2) {
      this.xdir = this.xdir * -1;
    }
    if (this.y <= 0 + this.w / 2) {
      this.ydir = this.ydir * -1;
    }
    if (this.y >= 400 + this.w / 2) {
      this.alive = false;
    }
    if (
      this.y >= 360 - this.w / 2 &&
      this.y <= 380 &&
      this.x >= paddlex &&
      this.x <= paddlex + 100
    ) {
      this.ydir = this.ydir * -1;
    }
  }
  show() {
    if (this.alive) {
      push();
      fill(0);
      ellipse(this.x, this.y, this.w, this.w);
      pop();
    }
  }
  //I believe this part is causing the error
  collide(brick){
    if(this.x >= brick.brickX && this.x <= brick.brickX + brick.brickW && this.y <= brick.brickY + brick.brickH){
      console.log("HI")
      brick.brickAlive = false
    }
  }
}

`

I recieved an error that said "TypeError: Cannot read properties of undefined (reading 'brickX')"


问:
Shared view transition not working with fragmnet on a differnet view container
this works (when view container is same a FramentA)

FragmentA.kt

```<code>parentFragmentManager.commit {
   setReorderingAllowed(true)
   addSharedElement(image, "name")
   replace(R.id.sameViewContainerAsFramentA, FragmentB)  <----
   addToBackStack(null)
}
</code>```

this doesn't work (when view container is different from Fragment B)

FragmentA.kt

```<code>parentFragmentManager.commit {
  setReorderingAllowed(true)
  addSharedElement(image, "name")
  replace(android.R.id.content, FragmentB)  <----
  addToBackStack(null)
}
</code>```

Is there a way to resolve this. I want the transition animation to work even on a different view container.

Body:
this works (when view container is same a FramentA)

FragmentA.kt

parentFragmentManager.commit {
   setReorderingAllowed(true)
   addSharedElement(image, "name")
   replace(R.id.sameViewContainerAsFramentA, FragmentB)  <----
   addToBackStack(null)
}

this doesn't work (when view container is different from Fragment B)

FragmentA.kt

parentFragmentManager.commit {
  setReorderingAllowed(true)
  addSharedElement(image, "name")
  replace(android.R.id.content, FragmentB)  <----
  addToBackStack(null)
}

Is there a way to resolve this. I want the transition animation to work even on a different view container.


问:
I'm trying to change the standard django registration using crispy-forms, but at the same time the registration confirmation email stops coming
Installed crispy-forms and configured templates for authentication. Everything works well. Problem with registration. With the standard registration form, I fill out the forms, then an email is sent to the mail confirming registration with a link to activate the account. But as soon as I try to implement the crispy-forms template, the letter stops coming and immediately throws it to the login form. How do I make emails arrive using crispy-forms?

I tried a lot of things but there is no result
forms.py
your

```<code>class SignUpForm(UserCreationForm):
    email = forms.EmailField(label="Email")
    first_name = forms.CharField(label="Имя")
    last_name = forms.CharField(label="Фамилия")

    class Meta:
        model = User
        fields = (
            "username",
            "first_name",
            "last_name",
            "email",
            "password1",
            "password2",
        )
</code>```

 text
views.py
`your

```<code>class SignUpView(CreateView):
    model = User
    form_class = SignUpForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'
    success_message = "Ваш профиль создан"

</code>```

texturls.pyyour

```<code>urlpatterns = [
</code>```
```<code>
    path("signup/", SignUpView.as_view(), name='signup'),
    path("update/<int:pk>", AccountUserUpdate.as_view(), name='account_update'),
    path('setauthor/', set_me_author, name='set_me_author'),
    path('login/', views.LoginView.as_view(), name='login'),
    path('logout/', views.LogoutView.as_view(), name='logout'),
    path('password-change/', views.PasswordChangeView.as_view(), name='password_change'),
    path('password-change/done/', views.PasswordChangeDoneView.as_view(), name='password_change_done'),
    path('password-reset/', views.PasswordResetView.as_view(), name='password_reset'),
    path('password-reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'),
    path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
    path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
</code>```

text`

Body:
Installed crispy-forms and configured templates for authentication. Everything works well. Problem with registration. With the standard registration form, I fill out the forms, then an email is sent to the mail confirming registration with a link to activate the account. But as soon as I try to implement the crispy-forms template, the letter stops coming and immediately throws it to the login form. How do I make emails arrive using crispy-forms?

I tried a lot of things but there is no result
forms.py
your

class SignUpForm(UserCreationForm):
    email = forms.EmailField(label="Email")
    first_name = forms.CharField(label="Имя")
    last_name = forms.CharField(label="Фамилия")

    class Meta:
        model = User
        fields = (
            "username",
            "first_name",
            "last_name",
            "email",
            "password1",
            "password2",
        )

 text
views.py
`your

class SignUpView(CreateView):
    model = User
    form_class = SignUpForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'
    success_message = "Ваш профиль создан"

texturls.pyyour

urlpatterns = [

    path("signup/", SignUpView.as_view(), name='signup'),
    path("update/<int:pk>", AccountUserUpdate.as_view(), name='account_update'),
    path('setauthor/', set_me_author, name='set_me_author'),
    path('login/', views.LoginView.as_view(), name='login'),
    path('logout/', views.LogoutView.as_view(), name='logout'),
    path('password-change/', views.PasswordChangeView.as_view(), name='password_change'),
    path('password-change/done/', views.PasswordChangeDoneView.as_view(), name='password_change_done'),
    path('password-reset/', views.PasswordResetView.as_view(), name='password_reset'),
    path('password-reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'),
    path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
    path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),

text`


问:
How to lower bit and sample rate of web rtc to make the audio quality bad?
Trying to lower the audio quality of web rtc to make a project a bit more realistic for what its emulating. I've tried similar things that I've seen posted with no luck. I think what im trying to do is decrease the allowed bit and sample rate.

I tried (gotten from: Is it really possible for webRTC to stream high quality audio without noise?)
`

```<code>navigator.mediaDevices.getUserMedia({
  audio: {
    autoGainControl: false,
    channelCount: 2,
    echoCancellation: false,
    latency: 0,
    noiseSuppression: false,
    sampleRate: 8000,
    sampleSize: 16,
    volume: 1.0
  }
</code>```

`
but it doesn't seem to make the audio sound bad. The goal is to get it to sound more like AMBE audio.

Body:
Trying to lower the audio quality of web rtc to make a project a bit more realistic for what its emulating. I've tried similar things that I've seen posted with no luck. I think what im trying to do is decrease the allowed bit and sample rate.

I tried (gotten from: Is it really possible for webRTC to stream high quality audio without noise?)
`

navigator.mediaDevices.getUserMedia({
  audio: {
    autoGainControl: false,
    channelCount: 2,
    echoCancellation: false,
    latency: 0,
    noiseSuppression: false,
    sampleRate: 8000,
    sampleSize: 16,
    volume: 1.0
  }

`
but it doesn't seem to make the audio sound bad. The goal is to get it to sound more like AMBE audio.


问:
How can i retrieve the username form the keycloak user?
I'm running a quarkus setup with keycloak. To start of I am trying to implement the tutorial into my code. I have to note here that i didn't copy the realm that is used. The reason for this is that we received a realm from our tutors.

This is the code I am trying to implement. The problem with is that it doesn't return the user.

@Path("/api/users")
public class UserResource {
    @Inject
    SecurityIdentity identity;

    @GET
    @Path("/me")
    @NoCache
    public User me() {
        return new User(identity);
    }

    public static class User {
        private final String userName;

        User(SecurityIdentity identity) {
            this.userName = identity.getPrincipal().getName();
        }

        public String getUserName() {
            return userName;
        }
    }
}
```
<p>When I enabled policy enforcer, I wasn't even able to login, all request became 403 or 401.</p>
```quarkus.keycloak.policy-enforcer.enable=true
```

How can we solve this issue?

Another question would be if it is possible to retrieve some sort of userId from keycloak?

Body:
I'm running a quarkus setup with keycloak. To start of I am trying to implement the tutorial into my code. I have to note here that i didn't copy the realm that is used. The reason for this is that we received a realm from our tutors.

This is the code I am trying to implement. The problem with is that it doesn't return the user.

@Path("/api/users")
public class UserResource {
    @Inject
    SecurityIdentity identity;

    @GET
    @Path("/me")
    @NoCache
    public User me() {
        return new User(identity);
    }

    public static class User {
        private final String userName;

        User(SecurityIdentity identity) {
            this.userName = identity.getPrincipal().getName();
        }

        public String getUserName() {
            return userName;
        }
    }
}

When I enabled policy enforcer, I wasn't even able to login, all request became 403 or 401.

quarkus.keycloak.policy-enforcer.enable=true

How can we solve this issue?

Another question would be if it is possible to retrieve some sort of userId from keycloak?


问:
DnD-Kit Incorrect behavior while trying to move item to another container in ReactJs
I would appreciate any help with this case, so if you see any minor issue - please, write me. There will be rather a lot of code.

I was trying to implement 'dnd-kit/sortable' into my bug tracker app. I have Kanban board consisting of four repeating column components. I needed to implement dnd-kit to be able to move task cards not only inside of each column, but between columns as well. Current code with sorting task cards in column, but if you try to move a card to any other column - most of the time nothing happens, but sometimes you get the Uncaught TypeError: Cannot read properties of undefined (reading 'id') I red through documentation many times and looked through similar projects in open source, but couldn't find what could be the reason for this bug.

The tasks from TasksContext is object with keys backlog, todo, inProgress, inReview, done and contains array of object. Each object inside of array represents task card.

```<code>Dashboard.js

const Dashboard = () => {
    const { tasks, setTasks } = useContext(TasksContext)
    const [activeId, setActiveId] = useState(null);
    const mouseSensor = useSensor(MouseSensor);
    const touchSensor = useSensor(TouchSensor);
    const sensors = useSensors(mouseSensor, touchSensor)
    const fullArray = Array.from(Object.values(tasks).flat())
    console.log(fullArray)

    const handleDragStart = ({ active }) => setActiveId(active.id);

    const handleDragCancel = () => setActiveId(null);

    const handleDragEnd = ({active, over}) => {
        const { containerId: activeContainer } = active.data.current.sortable
        const { containerId: overContainer } = over.data.current.sortable
        const oldIndex = tasks[activeContainer].findIndex(obj => obj.id === active.id);
        const newIndex = tasks[overContainer].findIndex(obj => obj.id === over.id);

        if (active.id !== over.id) {
            setTasks((prevTasks) => ({
                ...prevTasks,
                [overContainer]: arrayMove(prevTasks[overContainer], oldIndex, newIndex)
            }));
        }

        setActiveId(null);
    }

    return (
        <div className='relative grid grid-cols-4 gap-6 px-6 grow-0 shrink-0 basis-5/6 overflow-y-scroll'>
            <DndContext sensors={sensors} collisionDetection={rectIntersection} onDragStart={handleDragStart} onDragCancel={handleDragCancel} onDragEnd={handleDragEnd}>
                    <TasksColumn key='to do' title='to do' id='todo' tasks={tasks.todo} />
                    <TasksColumn key='in progress' title='in progress' id='inProgress' tasks={tasks.inProgress} />
                    <TasksColumn key='in review' title='in review' id='inReview' tasks={tasks.inReview} />
                    <TasksColumn key='done' title='done' id='done' tasks={tasks.done} />
                    <DragOverlay>{activeId ? <TaskCard id={activeId} task={fullArray.filter(task => task?.id === activeId)[0]} /> : null}</DragOverlay>
            </DndContext>
        </div>
    )
}
</code>```
```<code>TasksColumn.js

const TasksColumn = ({ title, id, tasks }) => {
    const { setNodeRef } = useDroppable({id});

  return (
    <div className=''>
        <ColumnHeader title={title} id={id} />

        <div className="h-3 w-full border-b-2 border-grayDark" />
        <SortableContext items={tasks} id={id} strategy={verticalListSortingStrategy}>
            <div ref={setNodeRef} className=''>
               {tasks.map(task => (
                    <Draggable key={task.name} id={task.id} task={task} />
                ))}
            </div>
        </SortableContext>
    </div>
  )
}
</code>```
```<code>Draggable.js

const Draggable = ({ id, task }) => {
    const { setNodeRef, transform, transition, isDragging, } = useSortable({id});

    const style = {
        transform: CSS.Translate.toString(transform),
        transition,
        opacity: isDragging ? 0.5 : 1,
    };

  return (
    <div ref={setNodeRef} style={style}>
        <TaskCard id={id} task={task} />
    </div>
  )
}
</code>```
```<code>TaskCard.js

const TaskCard = ({ id, task }) => {
    const { attributes, listeners, setActivatorNodeRef } = useSortable({id});

    return (
        <div className="py-4 border-b-2 border-grayLight">
            <div className="">
                <p className="">{task.deadline}</p>
                <p className="">{task.priority}</p>
            </div>
            <ArrowsPointingOutIcon className='rotate-45 w-5 h-5 outline-none' ref={setActivatorNodeRef} {...listeners} {...attributes} />
            <p className="">{task.name}</p>
            <div className="">
                <p className="">{task.author}</p>
                <p className="">{task.time}</p>
            </div>
        </div>
    )
}
</code>```

Body:
I would appreciate any help with this case, so if you see any minor issue - please, write me. There will be rather a lot of code.

I was trying to implement 'dnd-kit/sortable' into my bug tracker app. I have Kanban board consisting of four repeating column components. I needed to implement dnd-kit to be able to move task cards not only inside of each column, but between columns as well. Current code with sorting task cards in column, but if you try to move a card to any other column - most of the time nothing happens, but sometimes you get the Uncaught TypeError: Cannot read properties of undefined (reading 'id') I red through documentation many times and looked through similar projects in open source, but couldn't find what could be the reason for this bug.

The tasks from TasksContext is object with keys backlog, todo, inProgress, inReview, done and contains array of object. Each object inside of array represents task card.

Dashboard.js

const Dashboard = () => {
    const { tasks, setTasks } = useContext(TasksContext)
    const [activeId, setActiveId] = useState(null);
    const mouseSensor = useSensor(MouseSensor);
    const touchSensor = useSensor(TouchSensor);
    const sensors = useSensors(mouseSensor, touchSensor)
    const fullArray = Array.from(Object.values(tasks).flat())
    console.log(fullArray)

    const handleDragStart = ({ active }) => setActiveId(active.id);

    const handleDragCancel = () => setActiveId(null);

    const handleDragEnd = ({active, over}) => {
        const { containerId: activeContainer } = active.data.current.sortable
        const { containerId: overContainer } = over.data.current.sortable
        const oldIndex = tasks[activeContainer].findIndex(obj => obj.id === active.id);
        const newIndex = tasks[overContainer].findIndex(obj => obj.id === over.id);

        if (active.id !== over.id) {
            setTasks((prevTasks) => ({
                ...prevTasks,
                [overContainer]: arrayMove(prevTasks[overContainer], oldIndex, newIndex)
            }));
        }

        setActiveId(null);
    }

    return (

            <DndContext sensors={sensors} collisionDetection={rectIntersection} onDragStart={handleDragStart} onDragCancel={handleDragCancel} onDragEnd={handleDragEnd}>
                    <TasksColumn key='to do' title='to do' id='todo' tasks={tasks.todo} />
                    <TasksColumn key='in progress' title='in progress' id='inProgress' tasks={tasks.inProgress} />
                    <TasksColumn key='in review' title='in review' id='inReview' tasks={tasks.inReview} />
                    <TasksColumn key='done' title='done' id='done' tasks={tasks.done} />
                    <DragOverlay>{activeId ? <TaskCard id={activeId} task={fullArray.filter(task => task?.id === activeId)[0]} /> : null}</DragOverlay>
            </DndContext>

    )
}

TasksColumn.js

const TasksColumn = ({ title, id, tasks }) => {
    const { setNodeRef } = useDroppable({id});

  return (

        <ColumnHeader title={title} id={id} />

        <SortableContext items={tasks} id={id} strategy={verticalListSortingStrategy}>

               {tasks.map(task => (
                    <Draggable key={task.name} id={task.id} task={task} />
                ))}

        </SortableContext>

  )
}

Draggable.js

const Draggable = ({ id, task }) => {
    const { setNodeRef, transform, transition, isDragging, } = useSortable({id});

    const style = {
        transform: CSS.Translate.toString(transform),
        transition,
        opacity: isDragging ? 0.5 : 1,
    };

  return (

        <TaskCard id={id} task={task} />

  )
}

TaskCard.js

const TaskCard = ({ id, task }) => {
    const { attributes, listeners, setActivatorNodeRef } = useSortable({id});

    return (

{task.deadline}

{task.priority}

            <ArrowsPointingOutIcon className='rotate-45 w-5 h-5 outline-none' ref={setActivatorNodeRef} {...listeners} {...attributes} />

{task.name}

{task.author}

{task.time}

    )
}


问:
Disable cache on nginx uwsgi
I have a nginx, flask, uwsgi docker setup.

My problem is that when i call the api I immediately get the result from last call, and not the new one. I have now tried to return the time to debug.
I can see that when I get the response back it runs the code for 10 sec. behind and finish fine.

```<code>    @app.route(URLPREFIX + "/loaddata")
    def loaddata():
        global sg
        sg = StatsGenerator(client.runningactivities())   # takes 10 sec to run

        return datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
</code>```

from nginx conf

```<code>location /stravastats/ {
        expires -1;
        proxy_no_cache 1;
        proxy_cache_bypass 1;
        include uwsgi_params;
        uwsgi_pass stravastats:8080;
    }

</code>```

Title: Disable cache on nginx uwsgi

Body:
I have a nginx, flask, uwsgi docker setup.

My problem is that when i call the api I immediately get the result from last call, and not the new one. I have now tried to return the time to debug.
I can see that when I get the response back it runs the code for 10 sec. behind and finish fine.

    @app.route(URLPREFIX + "/loaddata")
    def loaddata():
        global sg
        sg = StatsGenerator(client.runningactivities())   # takes 10 sec to run

        return datetime.now().strftime("%m/%d/%Y, %H:%M:%S")

from nginx conf

location /stravastats/ {
        expires -1;
        proxy_no_cache 1;
        proxy_cache_bypass 1;
        include uwsgi_params;
        uwsgi_pass stravastats:8080;
    }


问:
Find memory held by a class in JavaScript
I am working on some Visual Programming type thing - I have a class in JavaScript like so:

```<code>class HoldsValues {
  queue = []
  otherStuff = {}

  getMemoryUsed(){
    // rough calculation/approximation
   return this.queue.size * 50;
  }
}
</code>```

as the queue in the class grows, is there a way to know how much memory is being used by this class, or do I just need to do those calculations manually somehow knowing the size of the queue array etc?

Body:
I am working on some Visual Programming type thing - I have a class in JavaScript like so:

class HoldsValues {
  queue = []
  otherStuff = {}

  getMemoryUsed(){
    // rough calculation/approximation
   return this.queue.size * 50;
  }
}

as the queue in the class grows, is there a way to know how much memory is being used by this class, or do I just need to do those calculations manually somehow knowing the size of the queue array etc?


问:
Running timer and functions at background in Bluetooth App(Swift after iOS 13)
I have an app which is looking for bluetooth devices at background and there is a timer which looking for devices and some other functions to notify user. When the app is running, the timer and functions are working perfectly but when it is closed, it stops.

I tried to check every document I found on web and stackoverflow but found nothing. Actually I check BG fetch and processing in "Target" section and made configuration in info.plist.

But I am not sure exactly what to do in AppDelegate. Here is the functions I want to run in BG:

```<code>    timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(refreshViews), userInfo: nil, repeats: true)

    timer = Timer.scheduledTimer(timeInterval: 9.0, target: self, selector: #selector(removeDevices), userInfo: nil, repeats: true)

    timer = Timer.scheduledTimer(timeInterval: 6.0, target: self, selector: #selector(alarm), userInfo: nil, repeats: true)
</code>```

Body:
I have an app which is looking for bluetooth devices at background and there is a timer which looking for devices and some other functions to notify user. When the app is running, the timer and functions are working perfectly but when it is closed, it stops.

I tried to check every document I found on web and stackoverflow but found nothing. Actually I check BG fetch and processing in "Target" section and made configuration in info.plist.

But I am not sure exactly what to do in AppDelegate. Here is the functions I want to run in BG:

    timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(refreshViews), userInfo: nil, repeats: true)

    timer = Timer.scheduledTimer(timeInterval: 9.0, target: self, selector: #selector(removeDevices), userInfo: nil, repeats: true)

    timer = Timer.scheduledTimer(timeInterval: 6.0, target: self, selector: #selector(alarm), userInfo: nil, repeats: true)


问:
Kafka Confluent Python SSL truststore configuration
I have a confluent Kafka consumer code using Python. I also have the truststore ca files including: certificate.jks and chain_certificate.pem. I know that we I am not able to use .jks file in python code and the PEM file that I have is a chain file (a single .pem file). My config code is as bellow:

```<code>from confluent_kafka import Consumer

consumer = Consumer({'bootstrap.servers':'myserver',
                     'security.protocol':'SSL',
                     'ssl.truststore.type':'PEM',
                     'ssl.truststore.location': 'chain_certificate.pem',
                     'ssl.truststore.password':'mypass',
                     'group.id':'test'
                     })
</code>```

I have tried multiple options like adding the ssl.check.hostname = False/True, but every time I am getting different errors and I'm not able to connect to the broker and topic.

'ssl.truststore.password' : 'mypass' cimpl.kafkaException: kafkaError{code=_INVALID_ARG, val=-186, str="No such configuration property:ssl.trusstore.type""} .

However, when I remove the ssl.truststore.type it gives the same error with just 'ssl.truststore.password' : 'mypass' cimpl.kafkaException: kafkaError{code=_INVALID_ARG, val=-186, str="Java truststore are not supported, use 'ssl.ca.location' and a certification file instead.""}

Body:
I have a confluent Kafka consumer code using Python. I also have the truststore ca files including: certificate.jks and chain_certificate.pem. I know that we I am not able to use .jks file in python code and the PEM file that I have is a chain file (a single .pem file). My config code is as bellow:

from confluent_kafka import Consumer

consumer = Consumer({'bootstrap.servers':'myserver',
                     'security.protocol':'SSL',
                     'ssl.truststore.type':'PEM',
                     'ssl.truststore.location': 'chain_certificate.pem',
                     'ssl.truststore.password':'mypass',
                     'group.id':'test'
                     })

I have tried multiple options like adding the ssl.check.hostname = False/True, but every time I am getting different errors and I'm not able to connect to the broker and topic.

'ssl.truststore.password' : 'mypass' cimpl.kafkaException: kafkaError{code=_INVALID_ARG, val=-186, str="No such configuration property:ssl.trusstore.type""} .

However, when I remove the ssl.truststore.type it gives the same error with just 'ssl.truststore.password' : 'mypass' cimpl.kafkaException: kafkaError{code=_INVALID_ARG, val=-186, str="Java truststore are not supported, use 'ssl.ca.location' and a certification file instead.""}


问:
Beginner problem with crashing code to lookup class or text on website
I write this code to check if on my website is a text and if its not then it should send me a notification thru slack. When I run it on VSC it crushes after some time like maybe 15 min or something like that.

I want to make it nice to put it on a server and run it remotly but need to be sure that will not crash every so often. I want to use it to check some websites for changing information on them and if they will change or be gone then send me notification. Best bit it works but crashes and don't know why :(

Can someone maybe help or pinpoint what it can be the problem? It will be better that this tool can just see text instead of class but I don't know how to do that.

```<code>

//Puppeteer library
const pt= require('puppeteer')
const axios = require('axios')
process.setMaxListeners(0);
async function getText(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.setDefaultNavigationTimeout(0);
   //website
   await page.goto('https://mieciusio.pl/kontakt.html')

   //identify element
   if (await page.$("[class='p-style btn-resize-mode label-bloc-2-style label-1-style']"))

   console.log("found")
   else //console.log("not found")
   axios.post(' https://hooks.slack.com/services/MYUniqeID', {text: 'Its changed'})

}

setInterval(getText, 12000)

</code>```

Try to find it online on YT but it's hard I was looking in a lot of tut's but can't find right one to work on finding text on website or not to crush because I don't know why crashes.

Body:
I write this code to check if on my website is a text and if its not then it should send me a notification thru slack. When I run it on VSC it crushes after some time like maybe 15 min or something like that.

I want to make it nice to put it on a server and run it remotly but need to be sure that will not crash every so often. I want to use it to check some websites for changing information on them and if they will change or be gone then send me notification. Best bit it works but crashes and don't know why :(

Can someone maybe help or pinpoint what it can be the problem? It will be better that this tool can just see text instead of class but I don't know how to do that.

//Puppeteer library
const pt= require('puppeteer')
const axios = require('axios')
process.setMaxListeners(0);
async function getText(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.setDefaultNavigationTimeout(0);
   //website
   await page.goto('https://mieciusio.pl/kontakt.html')

   //identify element
   if (await page.$("[class='p-style btn-resize-mode label-bloc-2-style label-1-style']"))

   console.log("found")
   else //console.log("not found")
   axios.post(' https://hooks.slack.com/services/MYUniqeID', {text: 'Its changed'})

}

setInterval(getText, 12000)

Try to find it online on YT but it's hard I was looking in a lot of tut's but can't find right one to work on finding text on website or not to crush because I don't know why crashes.


问:
how to copy env without leaks
Another Example For copy
But it makes segmentation faults

```<code>
typedef struct s_env
{
    char *key;
    char *val;
    struct s_env *next;
} t_env;

void env_tokenizing(char **envp, t_env **env)
{
    int i;
    char **_tok;

    i = -1;
   *env = malloc(sizeof(t_env));
    if(!env)
        return ;
    while(envp[++i])
    {
        _tok = ft_split(envp[i], '=');
        (*env)->key = _tok[0];
        (*env)->val = _tok[1];
        if (!envp[i + 1])
            break;
        (*env)->next = malloc(sizeof(t_env));
        if(!(*env)->next)
            return ;
        env = &(*env)->next;
    }
    (*env)->next = NULL;
}

void env_tokenizing(char **envp, t_env **env)
{
    int i;
    char **_tok;

    i = -1;
   *env = malloc(sizeof(t_env));
    if(!env)
        return ;
    while(envp[++i])
    {
        _tok = ft_split(envp[i], '=');
        keyval((*env)->key, _tok[0]);
        keyval((*env)->val, _tok[1]);
        if (!envp[i + 1])
            break;
        (*env)->next = malloc(sizeof(t_env));
        if(!(*env)->next)
            return ;
        env = &(*env)->next;
    }
    (*env)->next = NULL;
}

void keyval(char *locate, char *kv)
{
    int i;
    size_t len;

    len = ft_strlen(kv);
    locate = malloc(sizeof(char) * (len + 1));
    if(!locate)
        return ;
    i = -1;
    while(kv[++i])
        locate[i] = kv[i];
    locate[i] = '\0';
    free(kv);
}

</code>```

I'm going to copy environment variables from **envp argument from main without leaks. When I try to split every line in envp with = sign with [0] index i put the value to my env->key member, and a value of index [1] put to env->val member. But it leaves leaks behind. How can I add nodes to my env linked list withg key value members with **envp values. Here are two examples how I copied values.
In second example copy with keyval() function programm makes segmentation faluts.

Title: how to copy env without leaks

Body:
Another Example For copy
But it makes segmentation faults

typedef struct s_env
{
    char *key;
    char *val;
    struct s_env *next;
} t_env;

void env_tokenizing(char **envp, t_env **env)
{
    int i;
    char **_tok;

    i = -1;
   *env = malloc(sizeof(t_env));
    if(!env)
        return ;
    while(envp[++i])
    {
        _tok = ft_split(envp[i], '=');
        (*env)->key = _tok[0];
        (*env)->val = _tok[1];
        if (!envp[i + 1])
            break;
        (*env)->next = malloc(sizeof(t_env));
        if(!(*env)->next)
            return ;
        env = &(*env)->next;
    }
    (*env)->next = NULL;
}

void env_tokenizing(char **envp, t_env **env)
{
    int i;
    char **_tok;

    i = -1;
   *env = malloc(sizeof(t_env));
    if(!env)
        return ;
    while(envp[++i])
    {
        _tok = ft_split(envp[i], '=');
        keyval((*env)->key, _tok[0]);
        keyval((*env)->val, _tok[1]);
        if (!envp[i + 1])
            break;
        (*env)->next = malloc(sizeof(t_env));
        if(!(*env)->next)
            return ;
        env = &(*env)->next;
    }
    (*env)->next = NULL;
}

void keyval(char *locate, char *kv)
{
    int i;
    size_t len;

    len = ft_strlen(kv);
    locate = malloc(sizeof(char) * (len + 1));
    if(!locate)
        return ;
    i = -1;
    while(kv[++i])
        locate[i] = kv[i];
    locate[i] = '\0';
    free(kv);
}

I'm going to copy environment variables from **envp argument from main without leaks. When I try to split every line in envp with = sign with [0] index i put the value to my env->key member, and a value of index [1] put to env->val member. But it leaves leaks behind. How can I add nodes to my env linked list withg key value members with **envp values. Here are two examples how I copied values.
In second example copy with keyval() function programm makes segmentation faluts.


问:
Entity Framework Core 7 "Update" not working on foreign key entity
I am currently working on an ASP.NET MVC personal blog project where I have 2 models in the database.

ContentModel which contains tutorial and the date it was made on:

```<code>public class ContentModel
{
    [Required]
    public int ID { get; set; }
    public virtual tutorialModel Tutorial { get; set; }
    public DateTime DateCreated { get; set; }
}
</code>```

and TutorialModel itself:

```<code>public class tutorialModel
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string? Description { get; set; }
    public string Content { get; set; }
}
</code>```

I'm trying to write an EditTutorial function that takes a ContentModel and updates the tutorialModel object inside it:

(this function is written in IPostService)

```<code>    public void EditTutorial(ContentModel Content)
    {
        _context.Update(Content);
        _context.SaveChanges();
    }
</code>```

I've tried using breakpoints, the data sent from controller to this function is fine (the ContentModel being sent from the controller action has the new data within), but when I check the breakpoint in the EditTutorial function, the data within the passed TutorialObject is still the old data.

How can I update the tutorialModel object within the ContentModel?

Body:
I am currently working on an ASP.NET MVC personal blog project where I have 2 models in the database.

ContentModel which contains tutorial and the date it was made on:

public class ContentModel
{
    [Required]
    public int ID { get; set; }
    public virtual tutorialModel Tutorial { get; set; }
    public DateTime DateCreated { get; set; }
}

and TutorialModel itself:

public class tutorialModel
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string? Description { get; set; }
    public string Content { get; set; }
}

I'm trying to write an EditTutorial function that takes a ContentModel and updates the tutorialModel object inside it:

(this function is written in IPostService)

    public void EditTutorial(ContentModel Content)
    {
        _context.Update(Content);
        _context.SaveChanges();
    }

I've tried using breakpoints, the data sent from controller to this function is fine (the ContentModel being sent from the controller action has the new data within), but when I check the breakpoint in the EditTutorial function, the data within the passed TutorialObject is still the old data.

How can I update the tutorialModel object within the ContentModel?


问:
How do i use diffrent session and proxy after every 5 request in python?
below is my code but currently it sometimes take different proxy on every new request and for some reason the request are taking too much time to show response, way more than usual

i also have no way of knowing if the session is staying same for all five request or are they changing on every new request

i'm rotating proxy using next(proxy_cycle) and i'm hitting the request like this in the postman http://127.0.0.1:8000/test/http://ipinfo.io/json

i don't know what exactly i'm doing wrong.

```<code>from fastapi import FastAPI
import requests
from bs4 import BeautifulSoup
import lxml
import asyncio
import uvicorn
from itertools import cycle

app = FastAPI()
counter_lock = asyncio.Lock()
counter = 0

def make_5_req_per_session(url, proxy, session):
    try:
        response = session.get(url, proxies=proxy, timeout=10)
        if response.status_code == 200:
            return response.json()
        else:
            return None
    except Exception as e:
        # print(e)
        print("dead proxy")
        return None

def load_proxies():
    # read proxies from a text file
    with open("proxies.txt", "r") as proxies_file:
        list_of_proxies = []
        for proxy in proxies_file:
            list_of_proxies.append(proxy.strip())
        return list_of_proxies

list_of_proxies = load_proxies()

proxy_cycle = cycle(list_of_proxies)

# first time proxy and session
proxy = {"http": next(proxy_cycle)}
session = requests.Session()

@app.get("/test/{url:path}")
async def hello_world(
    url,
    proxy=proxy,
    session=session,
):
    global counter
    async with counter_lock:
        counter += 1
        if counter == 5:
            counter = 0
            # make new proxy and session after 5 requests
            proxy = {"http": next(proxy_cycle)}
            session = requests.Session()

    data = make_5_req_per_session(url, proxy, session)
    # if the response is None, then try again with new proxy
    while data is None:
        proxy = {"http": next(proxy_cycle)}
        session = requests.Session()
        data = make_5_req_per_session(url, proxy, session)
    return {"url": f" {counter} {proxy} {data} "}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

</code>```

this is my proxies in "proxies.txt"

```<code>111.21.183.58:9091
112.105.59.218:80
110.164.3.7:8888
</code>```

Body:
below is my code but currently it sometimes take different proxy on every new request and for some reason the request are taking too much time to show response, way more than usual

i also have no way of knowing if the session is staying same for all five request or are they changing on every new request

i'm rotating proxy using next(proxy_cycle) and i'm hitting the request like this in the postman http://127.0.0.1:8000/test/http://ipinfo.io/json

i don't know what exactly i'm doing wrong.

from fastapi import FastAPI
import requests
from bs4 import BeautifulSoup
import lxml
import asyncio
import uvicorn
from itertools import cycle

app = FastAPI()
counter_lock = asyncio.Lock()
counter = 0

def make_5_req_per_session(url, proxy, session):
    try:
        response = session.get(url, proxies=proxy, timeout=10)
        if response.status_code == 200:
            return response.json()
        else:
            return None
    except Exception as e:
        # print(e)
        print("dead proxy")
        return None

def load_proxies():
    # read proxies from a text file
    with open("proxies.txt", "r") as proxies_file:
        list_of_proxies = []
        for proxy in proxies_file:
            list_of_proxies.append(proxy.strip())
        return list_of_proxies

list_of_proxies = load_proxies()

proxy_cycle = cycle(list_of_proxies)

# first time proxy and session
proxy = {"http": next(proxy_cycle)}
session = requests.Session()

@app.get("/test/{url:path}")
async def hello_world(
    url,
    proxy=proxy,
    session=session,
):
    global counter
    async with counter_lock:
        counter += 1
        if counter == 5:
            counter = 0
            # make new proxy and session after 5 requests
            proxy = {"http": next(proxy_cycle)}
            session = requests.Session()

    data = make_5_req_per_session(url, proxy, session)
    # if the response is None, then try again with new proxy
    while data is None:
        proxy = {"http": next(proxy_cycle)}
        session = requests.Session()
        data = make_5_req_per_session(url, proxy, session)
    return {"url": f" {counter} {proxy} {data} "}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

this is my proxies in "proxies.txt"

111.21.183.58:9091
112.105.59.218:80
110.164.3.7:8888


问:
Get class mapped by @ORM\OneToOne
I have following class with mapped property (OneToOne) to another class:

```<code>class UserProfile
{
 ...
     /**
 * @Verzeilberg\UploadField(mapping="profile_image")
 * @Assert\Type(type="verzeilberg\UploadImagesBundle\Entity\Image")
 * @ORM\OneToOne(targetEntity="verzeilberg\UploadImagesBundle\Entity\Image", cascade={"persist", "remove"})
 * @ORM\JoinColumn(name="image_id", referencedColumnName="id")
 * @Assert\Valid
 */
protected $image;

...
}
</code>```

For the Image class (verzeilberg\UploadImagesBundle\Entity\Image) I have a created a listner who does stuff before saving the object into the database.

So when saving the UserProfile class with a image the image listener wil be activated And in this image listener I have to get the UserProfile class.

My question is how do I get the UserProfile class when I am in the Image class.

This is the Iamge listener:

```<code>class ImageListener
{
protected ImageService $imageService;

public function __construct(
    ImageService $imageService
)
{
    $this->imageService = $imageService;
}

public function prePersistHandler(Image $image, LifecycleEventArgs $event)
{
    $reader = new ImageAnnotationReader();
    $reader->loadMetadataForClass($image);
    $this->processImageBeforeSave($image);
}
</code>```

And this is the ImageAnnotationReader:

```<code>class ImageAnnotationReader
{

/**
 * @throws ReflectionException
 */
public function loadMetadataForClass($class)
{

    $reader = new AnnotationReader();
    $reflClass = new ReflectionClass($class);
</code>```

And here I need the UserProfile class To get this part (in bold):

@Verzeilberg\UploadField(mapping="profile_image")

Title: Get class mapped by @ORM\OneToOne

Body:
I have following class with mapped property (OneToOne) to another class:

class UserProfile
{
 ...
     /**
 * @Verzeilberg\UploadField(mapping="profile_image")
 * @Assert\Type(type="verzeilberg\UploadImagesBundle\Entity\Image")
 * @ORM\OneToOne(targetEntity="verzeilberg\UploadImagesBundle\Entity\Image", cascade={"persist", "remove"})
 * @ORM\JoinColumn(name="image_id", referencedColumnName="id")
 * @Assert\Valid
 */
protected $image;

...
}

For the Image class (verzeilberg\UploadImagesBundle\Entity\Image) I have a created a listner who does stuff before saving the object into the database.

So when saving the UserProfile class with a image the image listener wil be activated And in this image listener I have to get the UserProfile class.

My question is how do I get the UserProfile class when I am in the Image class.

This is the Iamge listener:

class ImageListener
{
protected ImageService $imageService;

public function __construct(
    ImageService $imageService
)
{
    $this->imageService = $imageService;
}

public function prePersistHandler(Image $image, LifecycleEventArgs $event)
{
    $reader = new ImageAnnotationReader();
    $reader->loadMetadataForClass($image);
    $this->processImageBeforeSave($image);
}

And this is the ImageAnnotationReader:

class ImageAnnotationReader
{

/**
 * @throws ReflectionException
 */
public function loadMetadataForClass($class)
{

    $reader = new AnnotationReader();
    $reflClass = new ReflectionClass($class);

And here I need the UserProfile class To get this part (in bold):

@Verzeilberg\UploadField(mapping="profile_image")


问:
How to access elements inside <object> tag?
My app is split between frontend(localhost:9000) and backend(localhost:8000). On frontend I use Vue.js and on backend I use Laravel.

What I'm trying to do is get a .svg file from backend's public folder and display it in frontend. On frontend I would then access elements(images) inside that .svg file and add a simple drag&drop functionality or change display style on them. The .svg files are being created in Inkscape.

The problem comes when accessing the elements(images)... I try to access them but it keeps returning an empty array no matter what I do.

HTML code:

```<code><object
  id="leftPage"
  title="left page"
  data="http://127.0.0.1:8000/albums/Animals_1/1.svg"
  type="image/svg+xml"
  class="col-6 album-page"
/>
</code>```

Images inside the 1.svg file have all an id that starts with 'image____'.

changePage function that gets called on button press (only prints out elements):

```<code>const changePage = () => {
  const stickerNodes = document.querySelectorAll("[id^='image']")
  console.log(stickerNodes)
}
</code>```

Output:

I try running the querySelector directly in the console and it doesn't return anything, but when I select an image inside .svg file with a tool inside inspect:

And then running it again(querySelector), then it returns an array of NodeElements:

Why does it return elements in the console after using select tool, but doesn't return them in the function even after using the tool ?

I tried getting document content of the object and then accessing elements inside it as well:

```<code>const changePage = () => {
  const leftPage = document.getElementById('leftPage')
  const doc = leftPage.contentDocument
  const stickerNodes = doc.querySelectorAll("[id^='image']")
  console.log(stickerNodes)
}
</code>```

But that turned out to not work as well (error: leftPage.contentDocument returns null)

I read somewhere that it could be a cors problem, but I tried putting the .svg files on frontend and accessing it that way and the problem remains...

Maybe I should've stored the .svg files in the  tag instead ? I thought about storing it directly in  tags since that is supported now, but worried about responsiveness...

Maybe the issue could be that I'm exporting .svg files from Inkscape ?

I did some hours of searching and it got me nowhere... While I keep searching I thought about posting it here in case someone knows how to solve this issue...

I hope you could understand most of it and I'm sorry if my english is not that good. If there is any additional information you need, please let me be know. Any help or direction is appreciated ! Thank you.

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

Body:
My app is split between frontend(localhost:9000) and backend(localhost:8000). On frontend I use Vue.js and on backend I use Laravel.

What I'm trying to do is get a .svg file from backend's public folder and display it in frontend. On frontend I would then access elements(images) inside that .svg file and add a simple drag&drop functionality or change display style on them. The .svg files are being created in Inkscape.

The problem comes when accessing the elements(images)... I try to access them but it keeps returning an empty array no matter what I do.

HTML code:

<object
  id="leftPage"
  title="left page"
  data="http://127.0.0.1:8000/albums/Animals_1/1.svg"
  type="image/svg+xml"
  class="col-6 album-page"
/>

Images inside the 1.svg file have all an id that starts with 'image____'.

changePage function that gets called on button press (only prints out elements):

const changePage = () => {
  const stickerNodes = document.querySelectorAll("[id^='image']")
  console.log(stickerNodes)
}

Output:

I try running the querySelector directly in the console and it doesn't return anything, but when I select an image inside .svg file with a tool inside inspect:

And then running it again(querySelector), then it returns an array of NodeElements:

Why does it return elements in the console after using select tool, but doesn't return them in the function even after using the tool ?

I tried getting document content of the object and then accessing elements inside it as well:

const changePage = () => {
  const leftPage = document.getElementById('leftPage')
  const doc = leftPage.contentDocument
  const stickerNodes = doc.querySelectorAll("[id^='image']")
  console.log(stickerNodes)
}

But that turned out to not work as well (error: leftPage.contentDocument returns null)

I read somewhere that it could be a cors problem, but I tried putting the .svg files on frontend and accessing it that way and the problem remains...

Maybe I should've stored the .svg files in the  tag instead ? I thought about storing it directly in  tags since that is supported now, but worried about responsiveness...

Maybe the issue could be that I'm exporting .svg files from Inkscape ?

I did some hours of searching and it got me nowhere... While I keep searching I thought about posting it here in case someone knows how to solve this issue...

I hope you could understand most of it and I'm sorry if my english is not that good. If there is any additional information you need, please let me be know. Any help or direction is appreciated ! Thank you.


问:
how to use trickle to limit upload bandwith from .sh file?
I want to limit the upload bandwidth limit of the linux version of 115.com webapp. This webapp actually is run by "sh /usr/local/115/115.sh". If I do
trickle -s -u 5 sh /usr/local/115/115.sh, then the upload limit is not in effect.

The inside of /usr/local/115/115.sh is

#!/bin/sh
export LD_LIBRARY_PATH=/usr/local/115/lib:$LD_LIBRARY_PATH export PATH=/usr/local/115:$PATH

/bin/bash -c "exec -a $0 /usr/local/115/115 > /dev/null 2>&1" $0

I feel I need to put the trickle command inside the 115.sh. How exactly should I do it? Thanks

I tried
trickle -s -u 5 /bin/bash -c "exec -a $0 /usr/local/115/115 > /dev/null 2>&1" $0
/bin/bash -c "exec -a trickle -s -u 5 $0 /usr/local/115/115 > /dev/null 2>&1" $0

and

/bin/bash -c "exec -a $0 trickle -s -u 5 /usr/local/115/115 > /dev/null 2>&1" $0

but still the speed limit is not effective.


问:
How can i get class values from an externally embeded iframe or page
I added tradingview ticker on my website using like this

```<code><!-- TradingView Widget BEGIN -->
        <div class="tradingview-widget-container">
          <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-tickers.js" async>
          {
          "symbols": [
            {
              "description": "BYBITPERP:WAVESUSDT",
              "proName": "BYBIT:WAVESUSDT.P"
            }
          ],
          "colorTheme": "light",
          "isTransparent": false,
          "showSymbolLogo": true,
          "locale": "en"
        }
          </script>
        </div>
        <!-- TradingView Widget END -->
</code>```

But i tried getting the value as to run other functions based on price of the asset which is contained in a class called .tv-ticker-item-change__last
and i have done

```<code>var price = $('.tv-ticker-item-change__last').text();
alert(price);
</code>```

Yet the value of .tv-ticker-item-change__last is not being captured even when is showing on the page, Please any help or clarifications will be highly appreciated

Body:
I added tradingview ticker on my website using like this

But i tried getting the value as to run other functions based on price of the asset which is contained in a class called .tv-ticker-item-change__last
and i have done

var price = $('.tv-ticker-item-change__last').text();
alert(price);

Yet the value of .tv-ticker-item-change__last is not being captured even when is showing on the page, Please any help or clarifications will be highly appreciated


问:
PyTorch error when downloading https://github.com/zeyad-mansour/lunar
pip install pytorch
Collecting pytorch
Using cached pytorch-1.0.2.tar.gz (689 bytes)
Preparing metadata (setup.py) ... done
Building wheels for collected packages: pytorch
Building wheel for pytorch (setup.py) ... error
error: subprocess-exited-with-error

× python setup.py bdist_wheel did not run successfully.
│ exit code: 1
╰─> [6 lines of output]
Traceback (most recent call last):
File "", line 2, in
File "", line 34, in
File "C:\Users\isamu\AppData\Local\Temp\pip-install-ib00i94p\pytorch_f353fda7bc1a41bdabf99f644cf66bcb\setup.py", line 15, in
raise Exception(message)
Exception: You tried to install "pytorch". The package named for PyTorch is "torch"
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for pytorch
Running setup.py clean for pytorch
Failed to build pytorch
Installing collected packages: pytorch
Running setup.py install for pytorch ... error
error: subprocess-exited-with-error

× Running setup.py install for pytorch did not run successfully.
│ exit code: 1
╰─> [6 lines of output]
Traceback (most recent call last):
File "", line 2, in
File "", line 34, in
File "C:\Users\isamu\AppData\Local\Temp\pip-install-ib00i94p\pytorch_f353fda7bc1a41bdabf99f644cf66bcb\setup.py", line 11, in
raise Exception(message)
Exception: You tried to install "pytorch". The package named for PyTorch is "torch"
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> pytorch

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.

tried:

```<code>pip install torch
</code>```
```<code>pip3 install efficiencynet_pytorch
</code>```
```<code>pip install pytorch
</code>```

but didn't help

Body:
pip install pytorch
Collecting pytorch
Using cached pytorch-1.0.2.tar.gz (689 bytes)
Preparing metadata (setup.py) ... done
Building wheels for collected packages: pytorch
Building wheel for pytorch (setup.py) ... error
error: subprocess-exited-with-error

× python setup.py bdist_wheel did not run successfully.
│ exit code: 1
╰─> [6 lines of output]
Traceback (most recent call last):
File "", line 2, in
File "", line 34, in
File "C:\Users\isamu\AppData\Local\Temp\pip-install-ib00i94p\pytorch_f353fda7bc1a41bdabf99f644cf66bcb\setup.py", line 15, in
raise Exception(message)
Exception: You tried to install "pytorch". The package named for PyTorch is "torch"
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for pytorch
Running setup.py clean for pytorch
Failed to build pytorch
Installing collected packages: pytorch
Running setup.py install for pytorch ... error
error: subprocess-exited-with-error

× Running setup.py install for pytorch did not run successfully.
│ exit code: 1
╰─> [6 lines of output]
Traceback (most recent call last):
File "", line 2, in
File "", line 34, in
File "C:\Users\isamu\AppData\Local\Temp\pip-install-ib00i94p\pytorch_f353fda7bc1a41bdabf99f644cf66bcb\setup.py", line 11, in
raise Exception(message)
Exception: You tried to install "pytorch". The package named for PyTorch is "torch"
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> pytorch

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.

tried:

pip install torch

pip3 install efficiencynet_pytorch

pip install pytorch

but didn't help


问:
How to change the background color for the webview when loading in swiftUI
I have been trying to make the background color for the WebView to be black as the white doesn't look good.

```<code>struct ContentView: View {
    @State private var showWebView = false
    private let urlString: String = "https://example.com"

    var body: some View {
        VStack(spacing: 40) {
            // Normal WebView
            WebView(url: URL(string: urlString)!).frame(
                minWidth: 0,
                maxWidth: .infinity,
                minHeight: 0,
                maxHeight: .infinity
            )
        }
    }
</code>```

I have tried to do this

```<code>VStack(spacing: 40) {
            // Normal WebView
            WebView(url: URL(string: urlString)!).frame(
                minWidth: 0,
                maxWidth: .infinity,
                minHeight: 0,
                maxHeight: .infinity
            )
        }.background(Color.black)
</code>```

Body:
I have been trying to make the background color for the WebView to be black as the white doesn't look good.

struct ContentView: View {
    @State private var showWebView = false
    private let urlString: String = "https://example.com"

    var body: some View {
        VStack(spacing: 40) {
            // Normal WebView
            WebView(url: URL(string: urlString)!).frame(
                minWidth: 0,
                maxWidth: .infinity,
                minHeight: 0,
                maxHeight: .infinity
            )
        }
    }

I have tried to do this

VStack(spacing: 40) {
            // Normal WebView
            WebView(url: URL(string: urlString)!).frame(
                minWidth: 0,
                maxWidth: .infinity,
                minHeight: 0,
                maxHeight: .infinity
            )
        }.background(Color.black)


问:
Ubuntu proxy timeout errors
I get the timeout error when using proxies with or without authentications on Ubuntu. It seems the problem lies on my network route ends. I have tried

Modify /etc/resolv.conf by adding nameserver xx.xx.xx.xx before nameserver 127.0.0.53 on separate lines

Uncomment the following part in /etc/apache/mods-available

```<code>ProxyRequests On
<Proxy *>
AddDefaultCharset off
Require all denied
#Require local
</Proxy>
</code>```

On Chrome and Firefox with HTTP/HTTPS and SOCKS5 ports

but did not succeed. I checked system firewall status with sudo ufw status and it says inactive therefore I assume that it's not because of firewall security. Where would the potential network blockage be and how do you go about it?

Title: Ubuntu proxy timeout errors

Body:
I get the timeout error when using proxies with or without authentications on Ubuntu. It seems the problem lies on my network route ends. I have tried

Modify /etc/resolv.conf by adding nameserver xx.xx.xx.xx before nameserver 127.0.0.53 on separate lines

Uncomment the following part in /etc/apache/mods-available

ProxyRequests On
<Proxy *>
AddDefaultCharset off
Require all denied
#Require local
</Proxy>

On Chrome and Firefox with HTTP/HTTPS and SOCKS5 ports

but did not succeed. I checked system firewall status with sudo ufw status and it says inactive therefore I assume that it's not because of firewall security. Where would the potential network blockage be and how do you go about it?


问:
How do I fetch only the most recent email with IMAP in Python?
I am trying to use IMAP with Gmail to fetch and store the body of the most recent email in the inbox. I cannot find any documentation or threads that say how to do this. Kind of a beginner question, haha.
Ideally:

```<code>imap.login('user', 'pass')
imap.select('Inbox')
#find most recent email
#store the body of the most recent email in a string variable
#log out of imap
</code>```

I have looked around a lot, but can't find any documentation on it. Thanks!

Body:
I am trying to use IMAP with Gmail to fetch and store the body of the most recent email in the inbox. I cannot find any documentation or threads that say how to do this. Kind of a beginner question, haha.
Ideally:

imap.login('user', 'pass')
imap.select('Inbox')
#find most recent email
#store the body of the most recent email in a string variable
#log out of imap

I have looked around a lot, but can't find any documentation on it. Thanks!


问:
Text Based Adventure Game
I am brand new to coding and python. I am trying to write a text based game and I am getting two errors.

```<code>

def showInstructions():
    print('Master Heist Adventure Game')
    print('Collect 6 artifacts to win the game, get caught by guard and lose')
    print('Move commands: go North, go South, go East, go West')
    print("Add to Inventory: get 'item name'")

def showStatus(current_room, inventory, rooms):
     # print the player's current location
    # print the current inventory
    # print an item if there is

    rooms = {
        'Great Hall of Wonders': {'South': 'Japan', 'North': 'Rome', 'East': 'Bikini Bottom', 'West': 'Idaho'},
        'Japan': {'North': 'Great Hall of Wonders', 'East': 'Babylon', 'Item': 'Golden Caterpillar'},
        'Idaho': {'East': 'Great Hall of Wonders', 'Item': 'Cats with Wings'},
        'Babylon': {'West': 'Japan', 'Item': 'Elder Scrolls'},
        'Rome': {'South': 'Great Hall of Wonders', 'East': 'Antarctica', 'Item': 'White Rose'},
        'Antarctica': {'West': 'Rome', 'Item': 'Guard'},
        'Bikini Bottom': {'West': 'Great Hall of Wonders', 'North': 'South Africa', 'Item': 'Crabby Patty Recipe'},
        'South Africa': {'South': 'Bikini Bottom', 'Item': 'Rosetta Stone'}
    }

def get_new_current_room(current_room, any_direction):
    new_current_room = current_room
    for i in rooms:
        if i == current_room:
            if direction in rooms[i]:
                new_current_room = rooms[i][any_direction]
    return new_current_room

# establish inventory
inventory = []
rooms = []
items = []

# start location
start_room = 'Great Hall of Wonders'

current_room = start_room
showInstructions()
def get_item(current_room):
    return [current_room]['Item']

while True:
    print('\nYou are in the {}'.format(current_room))
    print('Inventory:', inventory)

    item = get_item(current_room)
    print('Nab the ', item)
    if item == 'Guard':
        print('Your are Caught! GAME OVER!')
        exit(0)
    direction = input('What is your move? ')
    if direction == ('go North', 'go South', 'go East', 'go West'):
        direction = direction
        get_new_current_room = get_new_current_room(current_room, direction)
        if current_room == current_room:
            print('Wrong way! Try another direction.')
        else:
            current_room = get_new_current_room
    elif direction == ('get ' +item):
        if item in inventory:
            print('Item already nabbed!')
        else:
            inventory.append(item)
    else:
        print('Invalid direction')
    if len(inventory) == 6:
        print('GREAT JOB MASTER THIEF! YOU BEAT THE HEIST!')
        exit(0)

</code>```

Here are the error messages that I am getting. I am having issues getting the items. I wrote a code last week to move about the different rooms but implementing items have become a challenge for me.

```<code> File "C:\Users\jamie\PycharmProjects\ModuleSixMilestone\TextBasedGame.py", line 51, in <module>
    item = get_item(current_room)
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\jamie\PycharmProjects\ModuleSixMilestone\TextBasedGame.py", line 45, in get_item
    return [current_room]['Item']
           ~~~~~~~~~~~~~~^^^^^^^^
TypeError: list indices must be integers or slices, not str
</code>```

Title: Text Based Adventure Game

Body:
I am brand new to coding and python. I am trying to write a text based game and I am getting two errors.

def showInstructions():
    print('Master Heist Adventure Game')
    print('Collect 6 artifacts to win the game, get caught by guard and lose')
    print('Move commands: go North, go South, go East, go West')
    print("Add to Inventory: get 'item name'")

def showStatus(current_room, inventory, rooms):
     # print the player's current location
    # print the current inventory
    # print an item if there is

    rooms = {
        'Great Hall of Wonders': {'South': 'Japan', 'North': 'Rome', 'East': 'Bikini Bottom', 'West': 'Idaho'},
        'Japan': {'North': 'Great Hall of Wonders', 'East': 'Babylon', 'Item': 'Golden Caterpillar'},
        'Idaho': {'East': 'Great Hall of Wonders', 'Item': 'Cats with Wings'},
        'Babylon': {'West': 'Japan', 'Item': 'Elder Scrolls'},
        'Rome': {'South': 'Great Hall of Wonders', 'East': 'Antarctica', 'Item': 'White Rose'},
        'Antarctica': {'West': 'Rome', 'Item': 'Guard'},
        'Bikini Bottom': {'West': 'Great Hall of Wonders', 'North': 'South Africa', 'Item': 'Crabby Patty Recipe'},
        'South Africa': {'South': 'Bikini Bottom', 'Item': 'Rosetta Stone'}
    }

def get_new_current_room(current_room, any_direction):
    new_current_room = current_room
    for i in rooms:
        if i == current_room:
            if direction in rooms[i]:
                new_current_room = rooms[i][any_direction]
    return new_current_room

# establish inventory
inventory = []
rooms = []
items = []

# start location
start_room = 'Great Hall of Wonders'

current_room = start_room
showInstructions()
def get_item(current_room):
    return [current_room]['Item']

while True:
    print('\nYou are in the {}'.format(current_room))
    print('Inventory:', inventory)

    item = get_item(current_room)
    print('Nab the ', item)
    if item == 'Guard':
        print('Your are Caught! GAME OVER!')
        exit(0)
    direction = input('What is your move? ')
    if direction == ('go North', 'go South', 'go East', 'go West'):
        direction = direction
        get_new_current_room = get_new_current_room(current_room, direction)
        if current_room == current_room:
            print('Wrong way! Try another direction.')
        else:
            current_room = get_new_current_room
    elif direction == ('get ' +item):
        if item in inventory:
            print('Item already nabbed!')
        else:
            inventory.append(item)
    else:
        print('Invalid direction')
    if len(inventory) == 6:
        print('GREAT JOB MASTER THIEF! YOU BEAT THE HEIST!')
        exit(0)

Here are the error messages that I am getting. I am having issues getting the items. I wrote a code last week to move about the different rooms but implementing items have become a challenge for me.

 File "C:\Users\jamie\PycharmProjects\ModuleSixMilestone\TextBasedGame.py", line 51, in <module>
    item = get_item(current_room)
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\jamie\PycharmProjects\ModuleSixMilestone\TextBasedGame.py", line 45, in get_item
    return [current_room]['Item']
           ~~~~~~~~~~~~~~^^^^^^^^
TypeError: list indices must be integers or slices, not str


问:
Bitmap compress quality ok in emulator, but not in real device
In my app, images are saving successfully to gallery after editing. but quality is not up to the mark on physical device. I got 0.5mp to 0.7mp highest. but same app I open in emulator and after saving image I got pretty good quality of images (about 1.5mp to 3mp). didn't find the exact reason of this. will be glad if you help to find out. attaching my image saving code below.

```<code>
public void saveAsFile(@NonNull final String str, @NonNull final SaveSettings saveSettings, @NonNull final OnSaveListener onSaveListener) {
    Log.d(TAG, "Image Path: " + str);
    this.parentView.saveFilter((OnSaveBitmap) new OnSaveBitmap() {
        @Override
        public void onBitmapReady(Bitmap bitmap) {
            new AsyncTask<String, String, Exception>() {
                @Override
                public void onPreExecute() {
                    super.onPreExecute();
                    PhotoEditor.this.clearHelperBox();
                    PhotoEditor.this.parentView.setDrawingCacheEnabled(false);
                }

                @SuppressLint({"MissingPermission"})

                public Exception doInBackground(String... strArr) {
                    Bitmap bitmap;
                    try {
                        FileOutputStream fileOutputStream = new FileOutputStream(new File(str), false);
                        if (PhotoEditor.this.parentView != null) {
                            PhotoEditor.this.parentView.setDrawingCacheEnabled(true);
                            if (saveSettings.isTransparencyEnabled()) {
                                bitmap = BitmapUtil.removeTransparency(PhotoEditor.this.parentView.getDrawingCache());
                            } else {
                                bitmap = PhotoEditor.this.parentView.getDrawingCache();
                            }

                            bitmap.compress(Bitmap.CompressFormat.PNG, 100 , fileOutputStream);

                        }

                        Log.d(PhotoEditor.TAG, "Filed Saved Successfully");
                        return null;
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.d(PhotoEditor.TAG, "Failed to save File");
                        return e;
                    }
                }

                @Override
                public void onPostExecute(Exception exc) {
                    super.onPostExecute(exc);
                    if (exc == null) {
                        if (saveSettings.isClearViewsEnabled()) {
                            PhotoEditor.this.clearAllViews();
                        }
                        onSaveListener.onSuccess(str);
                        return;
                    }
                    onSaveListener.onFailure(exc);
                }
            }.execute();
        }

        public void onFailure(Exception exc) {
            onSaveListener.onFailure(exc);
        }
    });
}
</code>```

I tried in many ways but couldn't find the solution.

Body:
In my app, images are saving successfully to gallery after editing. but quality is not up to the mark on physical device. I got 0.5mp to 0.7mp highest. but same app I open in emulator and after saving image I got pretty good quality of images (about 1.5mp to 3mp). didn't find the exact reason of this. will be glad if you help to find out. attaching my image saving code below.

public void saveAsFile(@NonNull final String str, @NonNull final SaveSettings saveSettings, @NonNull final OnSaveListener onSaveListener) {
    Log.d(TAG, "Image Path: " + str);
    this.parentView.saveFilter((OnSaveBitmap) new OnSaveBitmap() {
        @Override
        public void onBitmapReady(Bitmap bitmap) {
            new AsyncTask<String, String, Exception>() {
                @Override
                public void onPreExecute() {
                    super.onPreExecute();
                    PhotoEditor.this.clearHelperBox();
                    PhotoEditor.this.parentView.setDrawingCacheEnabled(false);
                }

                @SuppressLint({"MissingPermission"})

                public Exception doInBackground(String... strArr) {
                    Bitmap bitmap;
                    try {
                        FileOutputStream fileOutputStream = new FileOutputStream(new File(str), false);
                        if (PhotoEditor.this.parentView != null) {
                            PhotoEditor.this.parentView.setDrawingCacheEnabled(true);
                            if (saveSettings.isTransparencyEnabled()) {
                                bitmap = BitmapUtil.removeTransparency(PhotoEditor.this.parentView.getDrawingCache());
                            } else {
                                bitmap = PhotoEditor.this.parentView.getDrawingCache();
                            }

                            bitmap.compress(Bitmap.CompressFormat.PNG, 100 , fileOutputStream);

                        }

                        Log.d(PhotoEditor.TAG, "Filed Saved Successfully");
                        return null;
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.d(PhotoEditor.TAG, "Failed to save File");
                        return e;
                    }
                }

                @Override
                public void onPostExecute(Exception exc) {
                    super.onPostExecute(exc);
                    if (exc == null) {
                        if (saveSettings.isClearViewsEnabled()) {
                            PhotoEditor.this.clearAllViews();
                        }
                        onSaveListener.onSuccess(str);
                        return;
                    }
                    onSaveListener.onFailure(exc);
                }
            }.execute();
        }

        public void onFailure(Exception exc) {
            onSaveListener.onFailure(exc);
        }
    });
}

I tried in many ways but couldn't find the solution.


问:
Pinescript reset indicator when specific condition is met
I am using ta.supertrend() indicator in my script which is being calculated and drawn from the start of max bars back.

Once an order is opened, I would like to reset the indicator so that it starts the calculation at the bar of order entry.

Is there a way to reset the indicator so that it starts from scratch with every order entry signal?

I've tried almost everything I could but couldn't achieve this behaviour whatsoever. I've used all sorts of conditionals, bar index, time, etc. in order to conditionally restart the indicator calculation when specific conditions are met but no luck, the script either gives a compiling error or draws weird lines on the chart.

Does anyone know how to achieve this in Pinescript?

Whatever solutions I used to reset the indicator either returned an compiling error or the supertrend drawing wasn't as it should.


问:
JPA - Does @OneToMany demand @ManyToOne?
I am developing an application with JPA and I came across a small problem.

I have this two entities Category and Supplier.

A Supplier must have at least one category so I used the @OneToMany tag.

```<code>@Entity
public class Supplier extends AbstractEntity {
    @NotEmpty
    private String name;
    @NotEmpty
    private String address;

   @OneToMany(mappedBy = "supplier")
   private List<Category> categories = new LinkedList<>();

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return this.address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

   public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }

    //TO DO : Add verification to ensure that a Supplier has at least a supplied category
    //TO DO : add a method do add a category to supplied categories
}
</code>```

On the other end since I used the @OneToMany tag in the Supplier entity I ended up using the @ManyToOne tag in Category entity.

```<code>@Entity
public class Category extends AbstractEntity{
    @NotBlank
    private String description;

    @ManyToOne
    @JoinColumn(name = "supplier_id")
    @NotNull
    @JsonIgnoreProperties({"categories"})
    private Supplier supplier;

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}
</code>```

But this creates a little problem.

Anytime that I want to create a new Category I need to provide a Supplier to it, which is not the intended behavior.

How can I get around this? Can I remove the @ManyToOne tag in Category?

Body:
I am developing an application with JPA and I came across a small problem.

I have this two entities Category and Supplier.

A Supplier must have at least one category so I used the @OneToMany tag.

@Entity
public class Supplier extends AbstractEntity {
    @NotEmpty
    private String name;
    @NotEmpty
    private String address;

   @OneToMany(mappedBy = "supplier")
   private List<Category> categories = new LinkedList<>();

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return this.address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

   public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }

    //TO DO : Add verification to ensure that a Supplier has at least a supplied category
    //TO DO : add a method do add a category to supplied categories
}

On the other end since I used the @OneToMany tag in the Supplier entity I ended up using the @ManyToOne tag in Category entity.

@Entity
public class Category extends AbstractEntity{
    @NotBlank
    private String description;

    @ManyToOne
    @JoinColumn(name = "supplier_id")
    @NotNull
    @JsonIgnoreProperties({"categories"})
    private Supplier supplier;

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

But this creates a little problem.

Anytime that I want to create a new Category I need to provide a Supplier to it, which is not the intended behavior.

How can I get around this? Can I remove the @ManyToOne tag in Category?


问:
VM with SIS installed
I am looking for a virtual machine with Berkeley's SIS tool installed.

After a major effort, I managed to compile the tool from the source code in my own VM; however, even though the tool works most of the time, it fails to execute many functions, resulting in segmentation faults.

For this reason, I started looking for a VM with the tool installed. So far, I have not got any good result from Google.

Please let me know if you are aware of a VM or know how to correctly compile the tool from the source code. Perhaps advising on the best linux distribution (and version) that works well with the tool.

PS: I could not find any suitable tags for this question except for virtual-machine. The tag SIS refers to something completely different. Electronic Design Automation (EDA) may be a more suitable tag than "logical-operators," but it also refers to something else.

Title: VM with SIS installed