问:
window.location.pathname/href catches previous url Angular 14
When user logs in, user redirects to home page and his pic became visible on the home page.When user clicks on the pic, a dropdown actions become visible with some routes, and user can move to some certain paths by clicking on those routes.

Also when User logs In I'm stopping user to access some certain pages.I'm using cPath:string=window.location.pathname to catch current url in my guard. And redirecting user to homepage if cPath matches with certain condition or url/path.

Now when user logs in and click on his pic first time he can move to the other pages. And when user try to access the routes which he doesn't have permission, he gets redirected to home page. And after that , If I click on the user pic second time and try to move to some other page, it does not redirect to the clicked page, instead console shows that the window.location.pathname has the path of the previous route. The request is made but for the previous path.

For example dashboard is the forbidden path, and user image has two paths my-posts and my-profile (the user image that becomes visible after login at home page),

so whenever I access dashboard path and gets redirected to home page, and then I try to access my-profile or my-posts page through the pic. the window.location.pathname redirects to dashboard path instead of my-posts or my-profile.

It happens whenever I try to access a forbidden path and gets redirected to home page

It's same with both pathname and href

I hope I was Able to explain my case in an understandable way

guard.ts

```<code>  currentPath: string = window.location.pathname;

  adminPath: string = '/admin';
  dashPath: string = '/dashboard';
  usersPath: string = '/allusers';

  user!: UserDto;

  async canActivate() {
    if (this.authService.userNotLoggedOut()) {

       let res: LooggedUser = this.authService.getUserProfile();
       this.user = await this.userService.getUser(res.user);

      console.log('href', this.currentPath);

      if (
        this.user.role[0] == 0 &&
        (this.currentPath == this.adminPath || this.currentPath == this.dashPath || this.currentPath == this.usersPath)
      ) {
        this.route.navigate(['/']);
        return false;
      }
     else {
        return true;
      }
}
</code>```

links to move to other pages

```<code>          <li>
            <a
              [routerLink]="['/my-profile']"
              class="custom-transition hover:text-slate-800"
              >Profile</a
            >
          </li>
          <li>
            <a
              [routerLink]="['/my-posts']"
              class="custom-transition hover:text-slate-800"
              >My Posts</a
            >
          </li>
</code>```

Body:
When user logs in, user redirects to home page and his pic became visible on the home page.When user clicks on the pic, a dropdown actions become visible with some routes, and user can move to some certain paths by clicking on those routes.

Also when User logs In I'm stopping user to access some certain pages.I'm using cPath:string=window.location.pathname to catch current url in my guard. And redirecting user to homepage if cPath matches with certain condition or url/path.

Now when user logs in and click on his pic first time he can move to the other pages. And when user try to access the routes which he doesn't have permission, he gets redirected to home page. And after that , If I click on the user pic second time and try to move to some other page, it does not redirect to the clicked page, instead console shows that the window.location.pathname has the path of the previous route. The request is made but for the previous path.

For example dashboard is the forbidden path, and user image has two paths my-posts and my-profile (the user image that becomes visible after login at home page),

so whenever I access dashboard path and gets redirected to home page, and then I try to access my-profile or my-posts page through the pic. the window.location.pathname redirects to dashboard path instead of my-posts or my-profile.

It happens whenever I try to access a forbidden path and gets redirected to home page

It's same with both pathname and href

I hope I was Able to explain my case in an understandable way

guard.ts

  currentPath: string = window.location.pathname;

  adminPath: string = '/admin';
  dashPath: string = '/dashboard';
  usersPath: string = '/allusers';

  user!: UserDto;

  async canActivate() {
    if (this.authService.userNotLoggedOut()) {

       let res: LooggedUser = this.authService.getUserProfile();
       this.user = await this.userService.getUser(res.user);

      console.log('href', this.currentPath);

      if (
        this.user.role[0] == 0 &&
        (this.currentPath == this.adminPath || this.currentPath == this.dashPath || this.currentPath == this.usersPath)
      ) {
        this.route.navigate(['/']);
        return false;
      }
     else {
        return true;
      }
}

links to move to other pages

            Profile

            My Posts


来源: stackexchange

问:
How to I send a authentication token from firebase to my django backend so that it may add that user in the admin of django?
Like this is the code I have used in my backend part of Django..My frontend is in ReactJS

```<code>default_app = firebase_admin.initialize_app(cred)

class FirebaseAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        auth_header = request.META.get("HTTP_AUTHORIZATION")
        if not auth_header:
            raise NoAuthToken("No auth token provided")

        id_token = auth_header.split(" ").pop()
        decoded_token = None
        try:
            decoded_token = auth.verify_id_token(id_token)
        except Exception:
            raise InvalidAuthToken("Invalid auth token")
            pass

        if not id_token or not decoded_token:
            return None

        try:
            uid = decoded_token.get("uid")
        except Exception:
            raise FirebaseError()

        user, created = User.objects.get_or_create(username=uid)
        user.profile.last_activity = timezone.localtime()

        return (user, None)
</code>```

I have just written this in backend and now am wondering where and how do I call this and how will be token received here.Thank you so much in advance

ContentLicense: CC BY-SA 4.0

Body:
Like this is the code I have used in my backend part of Django..My frontend is in ReactJS

default_app = firebase_admin.initialize_app(cred)

class FirebaseAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        auth_header = request.META.get("HTTP_AUTHORIZATION")
        if not auth_header:
            raise NoAuthToken("No auth token provided")

        id_token = auth_header.split(" ").pop()
        decoded_token = None
        try:
            decoded_token = auth.verify_id_token(id_token)
        except Exception:
            raise InvalidAuthToken("Invalid auth token")
            pass

        if not id_token or not decoded_token:
            return None

        try:
            uid = decoded_token.get("uid")
        except Exception:
            raise FirebaseError()

        user, created = User.objects.get_or_create(username=uid)
        user.profile.last_activity = timezone.localtime()

        return (user, None)

I have just written this in backend and now am wondering where and how do I call this and how will be token received here.Thank you so much in advance


问:
Th orientation for device disappearing data on table view that put on scroll view - IOS
image1 image  I have a screen contains table view and segment control that has 3 indexes every index call an api that return array of movies . I displayed the movies on table view and put all the components of the screen in scroll view and set its constraint very well .And i ran my app and it worked well.
the problem caused when i make rotation for my device the data in table view disappeared
if any one can help me ?

i created a variable from height of table view constraint to change it based on the array of movies  that come from api .
I tried to change the height of scroll view and its content and used ViewDidLayoutViews() function to update the height but the problem still .

```<code>    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        scrollviewhight.constant = movieListTableView.contentSize.height
    }

</code>```

Body:
image1 image  I have a screen contains table view and segment control that has 3 indexes every index call an api that return array of movies . I displayed the movies on table view and put all the components of the screen in scroll view and set its constraint very well .And i ran my app and it worked well.
the problem caused when i make rotation for my device the data in table view disappeared
if any one can help me ?

i created a variable from height of table view constraint to change it based on the array of movies  that come from api .
I tried to change the height of scroll view and its content and used ViewDidLayoutViews() function to update the height but the problem still .

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        scrollviewhight.constant = movieListTableView.contentSize.height
    }


问:
When debugging my .netcore app in a docker container, the process stops when a System.InvalidOperation exception is thrown
When I attach the vsdbg debugger to my running application in a docker container; I am able to step through code no problem; however, when I hit a particular line of code (has to do with executing a sqlcommand) which is surrounded by a try/catch, the application halts; and I get the following message in the debugging window in VSCode "The pipe program 'docker' exited unexpectedly with code 139.

As mentioned this is in a try/catch block, if I am not debugging, the application runs just fine as the exception is handled by the code.  This only happens when debugging and only when the app is in the container.

Here are my debugger configuration in my launch.json file for reference:

```<code>"configurations": [
    {
      "name" : ".NET Core Docker Attach",
      "type" : "coreclr",
      "request" : "attach",
      "processId" : "${command:pickRemoteProcess}",
      "pipeTransport": {
          "pipeProgram" : "docker",
          "pipeArgs" : ["exec", "-i", "lightning-backend-1"],
          "debuggerPath" : "/vsdbg/vsdbg",
          "pipeCwd" : "${workspaceRoot}",
          "quoteArgs" : false
      },
      "sourceFileMap" : {
        "/app/WorkRequests": "${workspaceFolder}/WorkRequests"
      },
    }
  ]
</code>```

I tried hosting the application locally rather than in a container to see what would happen outside the container as the error mentioned had to do with the container exiting with code 139. When I did, and I stepped through the code, I actually fell into the catch block and saw the exception was a System.InvalidOperation exception, however, the error is handled in the catch block and the application continue to run. My debugger still attached to the local instance of the application.

I then tried to be more specific in the code catch the exception rather than:
catch(Exception ex), I made it catch(System.InvalidOperation ex), and tried again in the container, but I got the same result. The application halts, it doesn't give an exception error on the console, or anything, and the message in the vscode debugger window says the same thing "the pipe program 'docker' exited unexpectedly with code 139".

I looked into what that error is and found its a SIGSEV issue, but I don't know why this won't fall into the catch block and continue.  I'm not an expert with docker so any help is greatly appreciated.

Body:
When I attach the vsdbg debugger to my running application in a docker container; I am able to step through code no problem; however, when I hit a particular line of code (has to do with executing a sqlcommand) which is surrounded by a try/catch, the application halts; and I get the following message in the debugging window in VSCode "The pipe program 'docker' exited unexpectedly with code 139.

As mentioned this is in a try/catch block, if I am not debugging, the application runs just fine as the exception is handled by the code.  This only happens when debugging and only when the app is in the container.

Here are my debugger configuration in my launch.json file for reference:

"configurations": [
    {
      "name" : ".NET Core Docker Attach",
      "type" : "coreclr",
      "request" : "attach",
      "processId" : "${command:pickRemoteProcess}",
      "pipeTransport": {
          "pipeProgram" : "docker",
          "pipeArgs" : ["exec", "-i", "lightning-backend-1"],
          "debuggerPath" : "/vsdbg/vsdbg",
          "pipeCwd" : "${workspaceRoot}",
          "quoteArgs" : false
      },
      "sourceFileMap" : {
        "/app/WorkRequests": "${workspaceFolder}/WorkRequests"
      },
    }
  ]

I tried hosting the application locally rather than in a container to see what would happen outside the container as the error mentioned had to do with the container exiting with code 139. When I did, and I stepped through the code, I actually fell into the catch block and saw the exception was a System.InvalidOperation exception, however, the error is handled in the catch block and the application continue to run. My debugger still attached to the local instance of the application.

I then tried to be more specific in the code catch the exception rather than:
catch(Exception ex), I made it catch(System.InvalidOperation ex), and tried again in the container, but I got the same result. The application halts, it doesn't give an exception error on the console, or anything, and the message in the vscode debugger window says the same thing "the pipe program 'docker' exited unexpectedly with code 139".

I looked into what that error is and found its a SIGSEV issue, but I don't know why this won't fall into the catch block and continue.  I'm not an expert with docker so any help is greatly appreciated.


问:
Trajectory of an electron in python
I've been trying to calculate the trajectory of an electron in python without using numpy.

I had to use Lorentz's Force, so I defined a function for cross product.

```<code>def cross(a, b):#function for cross product
    c = [a[1]*b[2] - a[2]*b[1],
         a[2]*b[0] - a[0]*b[2],
         a[0]*b[1] - a[1]*b[0]]

    return c
</code>```

Then to calculate the position and speed in 3D, I wrote code written below.

```<code>E = [1,1,0]
B = [0,0,10]
r = [[0,0,0]]
v = [[0,0,0]]
force = [0,0,0]#list for instantaneous values of force

t = 0
while(t < 1):
  a = [0,0,0]#list for instantanenous values of a
  V = [0,0,0]
  R = [0,0,0]

  #Bforce = cross(V,B)
  for j in range(3):
    force[j] = q*(cross(V,B)[j] + E[j])
    a[j] = force[j]/m
    V[j] = v[-1][j] + a[j]*dt
    R[j] = r[-1] + V[j]*dt + 0.5*a[j]*dt**2
  v.append(V)
  r.append(R)
  t += dt
</code>```

When I tried to plot the trajectory I had a problem with my z axis. Also my electron does not make circular motion, but goes a quarter of a circle.

Can someone help me?

In my code I first calculate the force, then I calculate position and speed component by component. After one loop I add them to their main lists, v and r as vectors. I was expecting periodic graphs for their speed graphs. However, I ended with an exponential one.

Title: Trajectory of an electron in python

Body:
I've been trying to calculate the trajectory of an electron in python without using numpy.

I had to use Lorentz's Force, so I defined a function for cross product.

def cross(a, b):#function for cross product
    c = [a[1]*b[2] - a[2]*b[1],
         a[2]*b[0] - a[0]*b[2],
         a[0]*b[1] - a[1]*b[0]]

    return c

Then to calculate the position and speed in 3D, I wrote code written below.

E = [1,1,0]
B = [0,0,10]
r = [[0,0,0]]
v = [[0,0,0]]
force = [0,0,0]#list for instantaneous values of force

t = 0
while(t < 1):
  a = [0,0,0]#list for instantanenous values of a
  V = [0,0,0]
  R = [0,0,0]

  #Bforce = cross(V,B)
  for j in range(3):
    force[j] = q*(cross(V,B)[j] + E[j])
    a[j] = force[j]/m
    V[j] = v[-1][j] + a[j]*dt
    R[j] = r[-1] + V[j]*dt + 0.5*a[j]*dt**2
  v.append(V)
  r.append(R)
  t += dt

When I tried to plot the trajectory I had a problem with my z axis. Also my electron does not make circular motion, but goes a quarter of a circle.

Can someone help me?

In my code I first calculate the force, then I calculate position and speed component by component. After one loop I add them to their main lists, v and r as vectors. I was expecting periodic graphs for their speed graphs. However, I ended with an exponential one.


问:
Found FontName for 0 fonts in R
I got "Found FontName for 0 fonts." in R so cannot import any font.

On Windows11 R-4.2.2 the below solution doesn't work anymore. How can I solve this error?

```<code>library(extrafont)
library(remotes)
remotes::install_version("Rttf2pt1", version = "1.3.8")
extrafont::font_import()
</code>```

How can I resolve the "No Font Name" issue when importing fonts into R using extrafont?

Title: Found FontName for 0 fonts in R

Body:
I got "Found FontName for 0 fonts." in R so cannot import any font.

On Windows11 R-4.2.2 the below solution doesn't work anymore. How can I solve this error?

library(extrafont)
library(remotes)
remotes::install_version("Rttf2pt1", version = "1.3.8")
extrafont::font_import()

How can I resolve the "No Font Name" issue when importing fonts into R using extrafont?


问:
Is possible create distinct query from BooleanBuilder querydsl or get result without duplicate records?
I found similar question. But I use BooleanBuilder for creating predicate and using him in a JpaRepository.

Is possible create distinct query with help BooleanBuilder or get result without duplicate records?


问:
two-dimensional(2D) arrays in Python don't change values the way I wanted
I read that in order to change the values in a 2D array, you just need to specify the index of the array in which our number is located, then specify the index of the number already in the array itself. But for some reason it does not work properly . I want to change in 2 tables, 3 values (index 1,2) and not all.
Here's what the console outputs

```<code>sim=str(input('Введите символ для перемещения- '))
dlin=int(input('Введите количество строк в длину- '))
hi=int(input('Введите количество строк в высотку- '))
text=[[' ']*dlin]*hi
text[1][2]=sim
for i in text:
    print(i)
</code>```

If you write an array manually and use this method, it works
I do not know what to do
I job in VS code

Body:
I read that in order to change the values in a 2D array, you just need to specify the index of the array in which our number is located, then specify the index of the number already in the array itself. But for some reason it does not work properly . I want to change in 2 tables, 3 values (index 1,2) and not all.
Here's what the console outputs

sim=str(input('Введите символ для перемещения- '))
dlin=int(input('Введите количество строк в длину- '))
hi=int(input('Введите количество строк в высотку- '))
text=[[' ']*dlin]*hi
text[1][2]=sim
for i in text:
    print(i)

If you write an array manually and use this method, it works
I do not know what to do
I job in VS code


问:
GeocoderUnavailable at /
from django.shortcuts import render, get_object_or_404
from .models import Measurement
from .forms import MeasurementModelForm
from geopy.geocoders import Nominatim
from geopy.distance import geodesic
from .utils import get_geo, get_center_coordinates, get_zoom
import folium

Create your views here.

def calculate_distance_view(request):
# initial values
distance = None
destination = None

```<code>obj = get_object_or_404(Measurement, id=1)
form = MeasurementModelForm(request.POST or None)
geolocator = Nominatim(user_agent='measurements')

ip = '72.14.207.99'
country, city, lat, lon = get_geo(ip)
location = geolocator.geocode(city)

# location coordinates
l_lat = lat
l_lon = lon
pointA = (l_lat, l_lon)

# initial folium map
m = folium.Map(width=800, height=500, location=get_center_coordinates(l_lat, l_lon), zoom_start=8)
# location marker
folium.Marker(\[l_lat, l_lon\], tooltip='click here for more', popup=city\['city'\],
                icon=folium.Icon(color='purple')).add_to(m)

if form.is_valid():
    instance = form.save(commit=False)
    destination\_ = form.cleaned_data.get('destination')
    destination = geolocator.geocode(destination\_)

    # destination coordinates
    d_lat = destination.latitude
    d_lon = destination.longitude
    pointB = (d_lat, d_lon)
    # distance calculation
    distance = round(geodesic(pointA, pointB).km, 2)

    # folium map modification
    m = folium.Map(width=800, height=500, location=get_center_coordinates(l_lat, l_lon, d_lat, d_lon), zoom_start=get_zoom(distance))
    # location marker
    folium.Marker(\[l_lat, l_lon\], tooltip='click here for more', popup=city\['city'\],
                icon=folium.Icon(color='purple')).add_to(m)
    # destination marker
    folium.Marker(\[d_lat, d_lon\], tooltip='click here for more', popup=destination,
                icon=folium.Icon(color='red', icon='cloud')).add_to(m)

    # draw the line between location and destination
    line = folium.PolyLine(locations=\[pointA, pointB\], weight=5, color='blue')
    m.add_child(line)

    instance.location = location
    instance.distance = distance
    instance.save()

m = m.\_repr_html\_()

context = {
    'distance' : distance,
    'destination': destination,
    'form': form,
    'map': m,
}

return render(request, 'measurements/main.html', context)
</code>```

i am workin geodjango library i am trying to get two location but received this error GeocoderUnavailable at /

Title: GeocoderUnavailable at /

Body:
from django.shortcuts import render, get_object_or_404
from .models import Measurement
from .forms import MeasurementModelForm
from geopy.geocoders import Nominatim
from geopy.distance import geodesic
from .utils import get_geo, get_center_coordinates, get_zoom
import folium

Create your views here.

def calculate_distance_view(request):
# initial values
distance = None
destination = None

obj = get_object_or_404(Measurement, id=1)
form = MeasurementModelForm(request.POST or None)
geolocator = Nominatim(user_agent='measurements')

ip = '72.14.207.99'
country, city, lat, lon = get_geo(ip)
location = geolocator.geocode(city)

# location coordinates
l_lat = lat
l_lon = lon
pointA = (l_lat, l_lon)

# initial folium map
m = folium.Map(width=800, height=500, location=get_center_coordinates(l_lat, l_lon), zoom_start=8)
# location marker
folium.Marker(\[l_lat, l_lon\], tooltip='click here for more', popup=city\['city'\],
                icon=folium.Icon(color='purple')).add_to(m)

if form.is_valid():
    instance = form.save(commit=False)
    destination\_ = form.cleaned_data.get('destination')
    destination = geolocator.geocode(destination\_)

    # destination coordinates
    d_lat = destination.latitude
    d_lon = destination.longitude
    pointB = (d_lat, d_lon)
    # distance calculation
    distance = round(geodesic(pointA, pointB).km, 2)

    # folium map modification
    m = folium.Map(width=800, height=500, location=get_center_coordinates(l_lat, l_lon, d_lat, d_lon), zoom_start=get_zoom(distance))
    # location marker
    folium.Marker(\[l_lat, l_lon\], tooltip='click here for more', popup=city\['city'\],
                icon=folium.Icon(color='purple')).add_to(m)
    # destination marker
    folium.Marker(\[d_lat, d_lon\], tooltip='click here for more', popup=destination,
                icon=folium.Icon(color='red', icon='cloud')).add_to(m)

    # draw the line between location and destination
    line = folium.PolyLine(locations=\[pointA, pointB\], weight=5, color='blue')
    m.add_child(line)

    instance.location = location
    instance.distance = distance
    instance.save()

m = m.\_repr_html\_()

context = {
    'distance' : distance,
    'destination': destination,
    'form': form,
    'map': m,
}

return render(request, 'measurements/main.html', context)

i am workin geodjango library i am trying to get two location but received this error GeocoderUnavailable at /


问:
Determine the index (row, col) of a QGridLayout item clicked
I have a widget that owns a QGridLayout which overrides the mouseClickEvent. If the grid layout was clicked (solved), I need the row and column of the item. Is there a way to convert a mouse click position to a QGridLayout index?

Edit: I am solving this in a terrible way currently. When I create the widget, I attach the row and column as a property of the widget and access the property thusly in mouseClickEvent:

```<code>QWidget* widget = childAt(event->pos());
if (widget)
{
    int index = ui.grid->indexOf(widget);
    QLayoutItem* item = ui.grid->itemAt(index);
    if (item->widget())
    {
        auto prop = item->widget()->property("prop");
        // convert prop to row, column
    }
}
</code>```

Body:
I have a widget that owns a QGridLayout which overrides the mouseClickEvent. If the grid layout was clicked (solved), I need the row and column of the item. Is there a way to convert a mouse click position to a QGridLayout index?

Edit: I am solving this in a terrible way currently. When I create the widget, I attach the row and column as a property of the widget and access the property thusly in mouseClickEvent:

QWidget* widget = childAt(event->pos());
if (widget)
{
    int index = ui.grid->indexOf(widget);
    QLayoutItem* item = ui.grid->itemAt(index);
    if (item->widget())
    {
        auto prop = item->widget()->property("prop");
        // convert prop to row, column
    }
}


问:
File picked by file_picker package does not exist in flutter
I want to pick an audio file in Flutter. I use file_picker package to pick an audio file. After picking it, I want to upload the file to AWS Storage, but the file in the path of the picked file does not exist. I check it by the following code snippet:

```<code>FilePickerResult? pickedAudioResult = await FilePicker.platform
          .pickFiles(type: FileType.any, withData: true);

if (pickedAudioResult == null) return;
PlatformFile pickedFile = pickedAudio.files.single;

print('Does file exist? ${await File(pickedFile.path!).exists()}');
print('File name: ${pickedFile.name}');
print('File extension: ${pickedFile.extension}');
print('File path: ${pickedFile.path}');
print('File size: ${pickedFile.size}');
</code>```

And the log output is:

```<code>Does file exist? false
File name: best ringtones - most romantic 2018.mp3
File extension: mp3
File path: /storage/emulated/0/Android/data/com.salamgram.salamgram/files/Ringtones/best ringtones - most romantic 2018.mp3
File size: 0
</code>```

I am confused by its strange behavior as it gives some info but doesn't give other.
So how can I get the chosen file as a File object?

Body:
I want to pick an audio file in Flutter. I use file_picker package to pick an audio file. After picking it, I want to upload the file to AWS Storage, but the file in the path of the picked file does not exist. I check it by the following code snippet:

FilePickerResult? pickedAudioResult = await FilePicker.platform
          .pickFiles(type: FileType.any, withData: true);

if (pickedAudioResult == null) return;
PlatformFile pickedFile = pickedAudio.files.single;

print('Does file exist? ${await File(pickedFile.path!).exists()}');
print('File name: ${pickedFile.name}');
print('File extension: ${pickedFile.extension}');
print('File path: ${pickedFile.path}');
print('File size: ${pickedFile.size}');

And the log output is:

Does file exist? false
File name: best ringtones - most romantic 2018.mp3
File extension: mp3
File path: /storage/emulated/0/Android/data/com.salamgram.salamgram/files/Ringtones/best ringtones - most romantic 2018.mp3
File size: 0

I am confused by its strange behavior as it gives some info but doesn't give other.
So how can I get the chosen file as a File object?


问:
after eas build command i have this error
expo logs

i want to publish my app but after command eas build i have this problems.

Prebuild

```<code>  Android package Learn more: https://expo.fyi/android-package
</code>```

2[stderr] CommandError: Input is required, but 'npx expo' is in non-interactive mode.
3[stderr] Project must have a android.package set in the Expo config (app.json or app.config.js).

i want to publish my app but after command eas build i have this problems.

Prebuild

```<code>  Android package Learn more: https://expo.fyi/android-package
</code>```

2[stderr] CommandError: Input is required, but 'npx expo' is in non-interactive mode.
3[stderr] Project must have a android.package set in the Expo config (app.json or app.config.js).

Body:
expo logs

i want to publish my app but after command eas build i have this problems.

Prebuild

  Android package Learn more: https://expo.fyi/android-package

2[stderr] CommandError: Input is required, but 'npx expo' is in non-interactive mode.
3[stderr] Project must have a android.package set in the Expo config (app.json or app.config.js).

i want to publish my app but after command eas build i have this problems.

Prebuild

  Android package Learn more: https://expo.fyi/android-package

2[stderr] CommandError: Input is required, but 'npx expo' is in non-interactive mode.
3[stderr] Project must have a android.package set in the Expo config (app.json or app.config.js).


问:
TypeError: Expected `trainable` argument to be a boolean, but got: 8
I've been designing a ML RNN program that implements a transforer model using tensorflow and keras. However, upon running, it is giving me this error:

```<code>Traceback (most recent call last):
  File "C:\Users\ignore\PycharmProjects\Cognify V3\main.py", line 487, in <module>
    transformer = Transformer(vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length)
  File "C:\Users\ignore\PycharmProjects\Cognify V3\main.py", line 475, in __init__
    self.encoder = Encoder(vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length, trainable=True)
  File "C:\Users\ignore\PycharmProjects\Cognify V3\main.py", line 315, in __init__
    self.enc_layers = [EncoderLayer(self.ff_dim, self.num_heads) for _ in range(6)]
  File "C:\Users\ignorei\PycharmProjects\Cognify V3\main.py", line 315, in <listcomp>
    self.enc_layers = [EncoderLayer(self.ff_dim, self.num_heads) for _ in range(6)]
  File "C:\Users\ignore\PycharmProjects\Cognify V3\main.py", line 291, in __init__
    self.mha = MultiHeadAttention(num_heads, ff_dim)
  File "C:\Users\ignore\Cognify V3\lib\site-packages\tensorflow\python\trackable\base.py", line 205, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "C:\Users\ignore\Cognify V3\lib\site-packages\keras\engine\base_layer.py", line 352, in __init__
    raise TypeError(
TypeError: Expected `trainable` argument to be a boolean, but got: 8
</code>```

And the lines referenced look like this...

Line 487:

```<code>transformer = Transformer(vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length)
</code>```

Lines 457:

```<code>class Transformer(tf.keras.Model):
    def __init__(self, vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length, **kwargs):
        super(Transformer, self).__init__(**kwargs)
        self.encoder = Encoder(vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length, trainable=True)
        self.decoder = Decoder(vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length)
        self.final_layer = tf.keras.layers.Dense(vocab_size)
</code>```

Line 315:

```<code>self.enc_layers = [EncoderLayer(self.ff_dim, self.num_heads) for _ in range(6)]

</code>```

Line 291:

```<code>self.mha = MultiHeadAttention(num_heads, ff_dim)

</code>```

The other lines are found in the base and base_layer part of the script.

Line 205 Base.py:

```<code>def _method_wrapper(self, *args, **kwargs):
  previous_value = getattr(self, "_self_setattr_tracking", True)
  self._self_setattr_tracking = False  # pylint: disable=protected-access
  try:
    result = method(self, *args, **kwargs)
  finally:
    self._self_setattr_tracking = previous_value  # pylint: disable=protected-access
  return result

return tf_decorator.make_decorator(
    target=method, decorator_func=_method_wrapper)
</code>```

Line 352 Base_Layer.py:

```<code>raise TypeError(
    "Expected `trainable` argument to be a boolean, "
    f"but got: {trainable}"
)
</code>```

Not sure what to do to fix this. I've run through a few ways to get around it but none have worked. I am stumped. The errors do show that I've tried, but I removed it back to its original state. It seems that I am missing arguments but even with things like self._trainable argument in my Encoder class to name one effort, it just doesn't work.

Body:
I've been designing a ML RNN program that implements a transforer model using tensorflow and keras. However, upon running, it is giving me this error:

Traceback (most recent call last):
  File "C:\Users\ignore\PycharmProjects\Cognify V3\main.py", line 487, in <module>
    transformer = Transformer(vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length)
  File "C:\Users\ignore\PycharmProjects\Cognify V3\main.py", line 475, in __init__
    self.encoder = Encoder(vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length, trainable=True)
  File "C:\Users\ignore\PycharmProjects\Cognify V3\main.py", line 315, in __init__
    self.enc_layers = [EncoderLayer(self.ff_dim, self.num_heads) for _ in range(6)]
  File "C:\Users\ignorei\PycharmProjects\Cognify V3\main.py", line 315, in <listcomp>
    self.enc_layers = [EncoderLayer(self.ff_dim, self.num_heads) for _ in range(6)]
  File "C:\Users\ignore\PycharmProjects\Cognify V3\main.py", line 291, in __init__
    self.mha = MultiHeadAttention(num_heads, ff_dim)
  File "C:\Users\ignore\Cognify V3\lib\site-packages\tensorflow\python\trackable\base.py", line 205, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "C:\Users\ignore\Cognify V3\lib\site-packages\keras\engine\base_layer.py", line 352, in __init__
    raise TypeError(
TypeError: Expected `trainable` argument to be a boolean, but got: 8

And the lines referenced look like this...

Line 487:

transformer = Transformer(vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length)

Lines 457:

class Transformer(tf.keras.Model):
    def __init__(self, vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length, **kwargs):
        super(Transformer, self).__init__(**kwargs)
        self.encoder = Encoder(vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length, trainable=True)
        self.decoder = Decoder(vocab_size, embedding_dim, num_heads, ff_dim, max_sequence_length)
        self.final_layer = tf.keras.layers.Dense(vocab_size)

Line 315:

self.enc_layers = [EncoderLayer(self.ff_dim, self.num_heads) for _ in range(6)]

Line 291:

self.mha = MultiHeadAttention(num_heads, ff_dim)

The other lines are found in the base and base_layer part of the script.

Line 205 Base.py:

def _method_wrapper(self, *args, **kwargs):
  previous_value = getattr(self, "_self_setattr_tracking", True)
  self._self_setattr_tracking = False  # pylint: disable=protected-access
  try:
    result = method(self, *args, **kwargs)
  finally:
    self._self_setattr_tracking = previous_value  # pylint: disable=protected-access
  return result

return tf_decorator.make_decorator(
    target=method, decorator_func=_method_wrapper)

Line 352 Base_Layer.py:

raise TypeError(
    "Expected `trainable` argument to be a boolean, "
    f"but got: {trainable}"
)

Not sure what to do to fix this. I've run through a few ways to get around it but none have worked. I am stumped. The errors do show that I've tried, but I removed it back to its original state. It seems that I am missing arguments but even with things like self._trainable argument in my Encoder class to name one effort, it just doesn't work.


问:
Error when Installing Playwright with yarn
The following error appears once I run yarn create playwright --ct on a react project; the documentation also says that after running that command some files are generated but they were not.

Any help is appreciated

```<code>bash: line 1: _modules.binplaywright: command not found
error Command failed with exit code 127.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Command failed: yarn playwright install
    at checkExecSyncError (node:child_process:871:11)
    at execSync (node:child_process:943:15)
    at executeCommands (\AppData\Local\Yarn\Data\global\node_modules\create-playwright\lib\index.js:4519:39)
    at Generator.run (\AppData\Local\Yarn\Data\global\node_modules\create-playwright\lib\index.js:4660:5)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async \AppData\Local\Yarn\Data\global\node_modules\create-playwright\lib\index.js:4928:3 {
  status: 127,
  signal: null,
  output: [ null, null, null ],
  pid: 17900,
  stdout: null,
  stderr: null
}
error Command failed.
Exit code: 1
</code>```

Tried to delete node_modules and reinstall it but didn't work

Body:
The following error appears once I run yarn create playwright --ct on a react project; the documentation also says that after running that command some files are generated but they were not.

Any help is appreciated

bash: line 1: _modules.binplaywright: command not found
error Command failed with exit code 127.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Command failed: yarn playwright install
    at checkExecSyncError (node:child_process:871:11)
    at execSync (node:child_process:943:15)
    at executeCommands (\AppData\Local\Yarn\Data\global\node_modules\create-playwright\lib\index.js:4519:39)
    at Generator.run (\AppData\Local\Yarn\Data\global\node_modules\create-playwright\lib\index.js:4660:5)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async \AppData\Local\Yarn\Data\global\node_modules\create-playwright\lib\index.js:4928:3 {
  status: 127,
  signal: null,
  output: [ null, null, null ],
  pid: 17900,
  stdout: null,
  stderr: null
}
error Command failed.
Exit code: 1

Tried to delete node_modules and reinstall it but didn't work


问:
Is normalization of word embeddings important?
I am doing actor-critic reinforcement learning for an environment that is best represented as a "bag-of-words". For this reason, I have opted to use a single body, multi-head approach for the net architecture. I use a linear pre-processing layer to generate n word embeddings of dimension d. Then I run the (batch,n,d) words through a stack of (2) nn.TransformerEncoder layers for the body and each head is another encoder layer followed by a linear logit layer.

Since this is RL and I have limited compute, it is also difficult to evaluate training as its happening. I decided to try looking a the mean cosine similarity of the latent words after the encoder body. My intuition tells me if the net is learning a proper latent representation of the environment then dis-similar words should have low cosine similarity.

However even though the net is clearly improving somewhat the mean cosine sim. remains very high, > .99

Thinking about it more, I don't think theres any reason to believe my first intuition, especially since I am not even normalizing the words after encoder body stack. But even if I did normalize, I'm not sure that would encourage lower cosine sim. as I am using 256 dimensions per word. All normalizing does is reduce the dimension of the output space by 1, which should hardly matter here.

Does this make sense? Also any general advice about my net is welcome


问:
Unique graph nodes with custom type in DyNetx
So I am trying to build a python application that manages a directed temporal graph (so edges happen at a time T). I am using DyNetx with the function to read the graph from a Dataset where every row is a 3-tuple that has: startNode, endNode, timestamp.
Problem is, I wanted to store every single node as Node type object which is a class i created with attributes id and status since the focus of the program is to study influence maximization. I get the id from the file and I initialize every node with status 0. But when at some point in the code I change the status of the code, if that node appears later in another edge of the graph its status is resetted to 0, i think its because with custom node types there is no way to check if a node already exists..so my question is, is there a way to change the function that reads the temporal graph from the file so that if the same id occurrs twice the node associated is the same and there are no other objects created? or a way to give a status attribute to a node when rapresenting it as an int?
code below</p>
```<code>import dynetx
```
class Node:
    def __init__(self, id):
        self.id = int(id)
        self.status = 0
```

g = dynetx.read_snapshots('college.txt', nodetype=Node, timestamptype=int)
for e in g.stream_interactions():
    print(e[0].id)
    print(e[0].status)
```
</code>```

Body:
So I am trying to build a python application that manages a directed temporal graph (so edges happen at a time T). I am using DyNetx with the function to read the graph from a Dataset where every row is a 3-tuple that has: startNode, endNode, timestamp.
Problem is, I wanted to store every single node as Node type object which is a class i created with attributes id and status since the focus of the program is to study influence maximization. I get the id from the file and I initialize every node with status 0. But when at some point in the code I change the status of the code, if that node appears later in another edge of the graph its status is resetted to 0, i think its because with custom node types there is no way to check if a node already exists..so my question is, is there a way to change the function that reads the temporal graph from the file so that if the same id occurrs twice the node associated is the same and there are no other objects created? or a way to give a status attribute to a node when rapresenting it as an int?
code below

import dynetx
```
class Node:
    def __init__(self, id):
        self.id = int(id)
        self.status = 0
```

g = dynetx.read_snapshots('college.txt', nodetype=Node, timestamptype=int)
for e in g.stream_interactions():
    print(e[0].id)
    print(e[0].status)
```


问:
i have a simple Error from my k-fold cross validation code for a logistic regression model Python
i have this error below from my code for a K-Fold cross validation

```<code>"None of [Int64Index([      0,       1,       3,       4,       5,       6,       7,\n                  8,       9,      10,\n            ...\n            1048565, 1048566, 1048567, 1048568, 1048569, 1048570, 1048571,\n            1048572, 1048573, 1048574],\n           dtype='int64', length=943717)] are in the [columns]"
</code>```

the model is logistic regression model and i need to evaluate it using K-fold
however if you have another code in python i would be thankful

this is my code

```<code>y3_data = data['DEATH']
    #dependant variable y_data:
x3_data = df14
from sklearn.model_selection import KFold
from sklearn.model_selection import StratifiedKFold

from imblearn.under_sampling import RandomUnderSampler

rus = RandomUnderSampler(random_state=0)
x3_resampled,y3_resampled = rus.fit_resample(x3_data,y3_data)

    #training and test sample :
x3_training_data, x3_test_data, y3_training_data, y3_test_data = train_test_split(x3_data, y3_data, test_size = 0.3)

    # Estimation result:
logit_model=sm.Logit(y3_training_data,x3_training_data)
result3=logit_model.fit()
print(result3.summary2())

    # Model Evaluation  :
logreg=LogisticRegression()
logreg.fit(x3_training_data,y3_training_data)
y_pred=logreg.predict(x3_test_data)
print('Logistic regression model accuracy:{:.2f}'.format(logreg.score(x3_test_data,y3_test_data)))
print("Logistic Regression F1 Score :",f1_score(y3_test_data,logreg.predict(x3_test_data),average=None))
sns.heatmap(confusion_matrix(y3_test_data, logreg.predict(x3_test_data)), annot=True, fmt=".0f")
plt.title("Logistic Regression Confusion Matrix",fontsize=18, color="red");

num_splits = 10
kfold = StratifiedKFold(num_splits, shuffle= True, random_state = 1)
train_accs, test_accs = [], []  #create empty lists to store accurcy values
for train_index, test_index in kfold.split(x3_data, y3_data):  #Generate indices to split data into training and test set.
    x3_train, x3_test = x3_data[train_index], x3_data[test_index]
    y3_train, y3_test = y3_data[train_index], y3_data[test_index]

    logreg.fit(x3_train, y3_train)
    y3_pred_train = logreg.predict(x3_train)
    y3_pred_test = logreg.predict(x3_test)

    train_accs.append(metrics.accuracy_score(y3_train, y3_pred_train) * 100)
    test_accs.append(metrics.accuracy_score(y3_test, y3_pred_test) * 100)

ave_train_acc = 0
ave_test_acc = 0

print("\t","Training_Acc","\t","\t", "Testing_Acc")

for i in range(num_splits):
    print(i,"\t", train_accs[i],"\t", test_accs[i])

    ave_train_acc+= train_accs[i]/num_splits
    ave_test_acc+= test_accs[i]/num_splits

print("Av", "\t", ave_train_acc,"\t", ave_test_acc)
</code>```

the error is only on the k fold part

and i want the output to be like this one below

```<code>     Training_Acc        Testing_Acc
0    76.0586319218241    75.32467532467533
1    75.2442996742671    74.67532467532467
2    73.9413680781759    81.16883116883116
3    77.72357723577235   71.89542483660131
4    76.7479674796748    73.20261437908496
Av   75.94316887794285   75.25337407690348

</code>```

PLEASE help

THIS IS the full error trace track

```<code>RF Regression F1 Score : [0.96507625 0.47731195]

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-19-955883a0e9f9> in <module>
     62 train_accs, test_accs = [], []  #create empty lists to store accurcy values
     63 for train_index, test_index in kfold.split(x_data, y_data):  #Generate indices to split data into training and test set.
---> 64     x_train_data, x_test_data = x_data[train_index], x_data[test_index]
     65     y_train, y_test = y_data[train_index], y_data[test_index]
     66

    2 frames

    /usr/local/lib/python3.8/dist-packages/pandas/core/indexing.py in _validate_read_indexer(self, key, indexer, axis)
       1372                 if use_interval_msg:
       1373                     key = list(key)
    -> 1374                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
       1375
       1376             not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())

    KeyError: "None of [Int64Index([      0,       1,       3,       4,       5,       6,       7,\n                  8,       9,      10,\n            ...\n            1048564, 1048565, 1048566, 1048567, 1048568, 1048569, 1048570,\n            1048572, 1048573, 1048574],\n           dtype='int64', length=838860)] are in the [columns]"
</code>```

new error

```<code>> ---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

/usr/local/lib/python3.8/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3360             try:
-> 3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:

4 frames

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)

/usr/local/lib/python3.8/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:
-> 3363                 raise KeyError(key) from err
   3364
   3365         if is_scalar(key) and isna(key) and not self.hasnans:
</code>```

Body:
i have this error below from my code for a K-Fold cross validation

"None of [Int64Index([      0,       1,       3,       4,       5,       6,       7,\n                  8,       9,      10,\n            ...\n            1048565, 1048566, 1048567, 1048568, 1048569, 1048570, 1048571,\n            1048572, 1048573, 1048574],\n           dtype='int64', length=943717)] are in the [columns]"

the model is logistic regression model and i need to evaluate it using K-fold
however if you have another code in python i would be thankful

this is my code

y3_data = data['DEATH']
    #dependant variable y_data:
x3_data = df14
from sklearn.model_selection import KFold
from sklearn.model_selection import StratifiedKFold

from imblearn.under_sampling import RandomUnderSampler

rus = RandomUnderSampler(random_state=0)
x3_resampled,y3_resampled = rus.fit_resample(x3_data,y3_data)

    #training and test sample :
x3_training_data, x3_test_data, y3_training_data, y3_test_data = train_test_split(x3_data, y3_data, test_size = 0.3)

    # Estimation result:
logit_model=sm.Logit(y3_training_data,x3_training_data)
result3=logit_model.fit()
print(result3.summary2())

    # Model Evaluation  :
logreg=LogisticRegression()
logreg.fit(x3_training_data,y3_training_data)
y_pred=logreg.predict(x3_test_data)
print('Logistic regression model accuracy:{:.2f}'.format(logreg.score(x3_test_data,y3_test_data)))
print("Logistic Regression F1 Score :",f1_score(y3_test_data,logreg.predict(x3_test_data),average=None))
sns.heatmap(confusion_matrix(y3_test_data, logreg.predict(x3_test_data)), annot=True, fmt=".0f")
plt.title("Logistic Regression Confusion Matrix",fontsize=18, color="red");

num_splits = 10
kfold = StratifiedKFold(num_splits, shuffle= True, random_state = 1)
train_accs, test_accs = [], []  #create empty lists to store accurcy values
for train_index, test_index in kfold.split(x3_data, y3_data):  #Generate indices to split data into training and test set.
    x3_train, x3_test = x3_data[train_index], x3_data[test_index]
    y3_train, y3_test = y3_data[train_index], y3_data[test_index]

    logreg.fit(x3_train, y3_train)
    y3_pred_train = logreg.predict(x3_train)
    y3_pred_test = logreg.predict(x3_test)

    train_accs.append(metrics.accuracy_score(y3_train, y3_pred_train) * 100)
    test_accs.append(metrics.accuracy_score(y3_test, y3_pred_test) * 100)

ave_train_acc = 0
ave_test_acc = 0

print("\t","Training_Acc","\t","\t", "Testing_Acc")

for i in range(num_splits):
    print(i,"\t", train_accs[i],"\t", test_accs[i])

    ave_train_acc+= train_accs[i]/num_splits
    ave_test_acc+= test_accs[i]/num_splits

print("Av", "\t", ave_train_acc,"\t", ave_test_acc)

the error is only on the k fold part

and i want the output to be like this one below

     Training_Acc        Testing_Acc
0    76.0586319218241    75.32467532467533
1    75.2442996742671    74.67532467532467
2    73.9413680781759    81.16883116883116
3    77.72357723577235   71.89542483660131
4    76.7479674796748    73.20261437908496
Av   75.94316887794285   75.25337407690348

PLEASE help

THIS IS the full error trace track

RF Regression F1 Score : [0.96507625 0.47731195]

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-19-955883a0e9f9> in <module>
     62 train_accs, test_accs = [], []  #create empty lists to store accurcy values
     63 for train_index, test_index in kfold.split(x_data, y_data):  #Generate indices to split data into training and test set.
---> 64     x_train_data, x_test_data = x_data[train_index], x_data[test_index]
     65     y_train, y_test = y_data[train_index], y_data[test_index]
     66

    2 frames

    /usr/local/lib/python3.8/dist-packages/pandas/core/indexing.py in _validate_read_indexer(self, key, indexer, axis)
       1372                 if use_interval_msg:
       1373                     key = list(key)
    -> 1374                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
       1375
       1376             not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())

    KeyError: "None of [Int64Index([      0,       1,       3,       4,       5,       6,       7,\n                  8,       9,      10,\n            ...\n            1048564, 1048565, 1048566, 1048567, 1048568, 1048569, 1048570,\n            1048572, 1048573, 1048574],\n           dtype='int64', length=838860)] are in the [columns]"

new error

> ---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

/usr/local/lib/python3.8/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3360             try:
-> 3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:

4 frames

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)

/usr/local/lib/python3.8/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:
-> 3363                 raise KeyError(key) from err
   3364
   3365         if is_scalar(key) and isna(key) and not self.hasnans:


问:
In angular, the size of my main.js file is 20mb and vendor.js file is 7mb, what could be the issue and how can I optimize my build?
Size of main.js = 20mb and size of vendor.js = 7.84mb, what could be the issue and how can I optimize my build?

I tried using ng build --prod which gives error for version 15.2-15.3


问:
Creating a profile in the database once an user is registered, working with IdentityUser
I'm currently making a forum using ASP.NET and I'm trying out to generate a profile entry in the database once the user makes an account (I have a 'Profile' model with a foreign key to 'ApplicationUserId' deriving IdentityUser).

Though, I have used scaffolding on ApplicationUser and most of the generated code that manages user registration uses async functions located in Register.cshtml.cs and I don't thoroughly comprehend how they interact with the database. My method of creating a profile would've been to get the context of my database through

IServiceProvider.serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()

then created a Profile object with New Profile() and lastly added it to the database that way. Though that beats me because I don't know how to obtain the serviceProvider used to fetch the database context, inside the Register.cshtml.cs file.

Sorry for my poor understanding of .net, the documentation is overwhelming for me since I'm a beginner.

Phrased in another way, my question boils down to, how can I create an instance of a profile and add it to my database, when most of the user registration (to my understanding) uses pre-defined functions by the framework?

(Part of) register.cshtml.cs, in case I should include it

```<code> public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = CreateUser();

                await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
                await setDataAndCountsAsync(user);
                await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
                var result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    await _userManager.AddToRoleAsync(user, "User");

                    var userId = await _userManager.GetUserIdAsync(user);
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        return LocalRedirect(returnUrl);
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }
</code>```

Body:
I'm currently making a forum using ASP.NET and I'm trying out to generate a profile entry in the database once the user makes an account (I have a 'Profile' model with a foreign key to 'ApplicationUserId' deriving IdentityUser).

Though, I have used scaffolding on ApplicationUser and most of the generated code that manages user registration uses async functions located in Register.cshtml.cs and I don't thoroughly comprehend how they interact with the database. My method of creating a profile would've been to get the context of my database through

IServiceProvider.serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()

then created a Profile object with New Profile() and lastly added it to the database that way. Though that beats me because I don't know how to obtain the serviceProvider used to fetch the database context, inside the Register.cshtml.cs file.

Sorry for my poor understanding of .net, the documentation is overwhelming for me since I'm a beginner.

Phrased in another way, my question boils down to, how can I create an instance of a profile and add it to my database, when most of the user registration (to my understanding) uses pre-defined functions by the framework?

(Part of) register.cshtml.cs, in case I should include it

 public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = CreateUser();

                await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
                await setDataAndCountsAsync(user);
                await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
                var result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    await _userManager.AddToRoleAsync(user, "User");

                    var userId = await _userManager.GetUserIdAsync(user);
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by clicking here.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        return LocalRedirect(returnUrl);
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }


问:
setFocus of react-hook-form doesn't work when updating a context from ContextAPI
I want to set focus to a next input after typing in one input. But not only set focus, I want to submit an async request and update a global context with ContextAPI. If I do not update the context, the submit with setFocus works great. But if a context is updated there, the automatic refresh of page loses the focus to no input.

I knew Redux avoid the refresh problem. Can I use setFocus when updating a Context?

I use the register to manage the refs. Works great if I do not update the ContextAPI. I tried using manually the refs, but no success


问:
React 18 SSR chunk preload (like in @loadable)
Using ChunkExtractor from @loadable/server, we can include links in the body of the page to preload the necessary chunks during SSR.

This speeds up hydration by having these scripts loaded at the same time as the main chunk just after the HTML document.

How can I do the same with React 18 SSR + Lazy/Suspense without @loadable?

renderToPipeableStream`s onAllReady callback has no arguments.


问:
I want the footer to completely cover the bottom
I want my footer to completely cover the bottom but ıt keeps giving me space from the left. you can see my code snippet. i still couldnt figure it out unforteunatly. thanks for all your help

I want my footer to completely cover the bottom but ıt keeps giving me space from the left. you can see my code snippet. i still couldnt figure it out unforteunatly. thanks for all your help

*{
    margin: 0;
    border: 0;
    box-sizing: border-box;
}

a{
    text-decoration: none;
    color:#fff;

}

html{
    font-family:"Open Sans", sans-serif;
    font-family: 'Oswald', sans-serif;
}
#navbar{
    color: #ffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 0.75rem;
    height: 70px;
}
#navbar ul{
    list-style-type: none;
    display: flex;
    align-items: center;
}
#navbar ul li a {
    padding: 0.7rem;
}
#navbar ul li a:hover {
    background: rgb(226, 109, 128);
    border-radius: 5px;
}
#home{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 2rem;
    border-bottom: 1px solid grey;
}
#home img{
    max-width: 100%;
    height: auto;
    border-radius: 100%;
}
#home .name h2{
    margin-bottom: 0.74rem;
}
#home .name p{
    opacity: 0.5;
    font-style:italic;
    font-size:larger;

}
/* home a ve home hover kısmı hakkımda kısmı */
#education{
    color: #fff;
    padding: 1rem;
}
#education .items{
    display: flex;
    justify-content: space-between;
    align-items: center;
}
#education .items .item{
    width: 33%;
    text-align: center;
    padding: 0.5rem;
}
#education .items .item:hover{
    color:palevioletred
}
#education .education-image{
    padding: 1rem;
}

#about{
    color: #333;
    padding: 1rem;
}
.about{
    display: flex;
    flex-direction: column;
    padding: 1rem;
}
.p h3{
    text-align: center;
    word-spacing: 5px;
}
 .abouts .about{
    display: flex;
    padding: 0.5rem;
    margin-bottom: 0.5rem;
 }
 .abouts .about .about-image{
    margin-right: 0.5rem;
    position: relative;
 }
 .abouts .about .about-image{
    border-radius: 50px;
 }
 img.yuvarlak{
    border-radius: 100%;
 }

 @import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800;900&display=swap");

 .footer {
    position: relative;
    width: 100%;
    background: #3586ff;
    min-height: 100px;
    padding: 20px 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }

  .social-icon,
  .menu {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px 0;
    flex-wrap: wrap;
  }

  .social-icon__item,
  .menu__item {
    list-style: none;
  }

  .social-icon__link {
    font-size: 2rem;
    color: #fff;
    margin: 0 10px;
    display: inline-block;
    transition: 0.5s;
  }
  .social-icon__link:hover {
    transform: translateY(-10px);
  }

  .menu__link {
    font-size: 1.2rem;
    color: #fff;
    margin: 0 10px;
    display: inline-block;
    transition: 0.5s;
    text-decoration: none;
    opacity: 0.75;
    font-weight: 300;
  }

  .menu__link:hover {
    opacity: 1;
  }

  .footer p {
    color: #fff;
    margin: 15px 0 10px 0;
    font-size: 1rem;
    font-weight: 300;
  }

  .wave {
    position: absolute;
    top: -100px;
    left: 0;
    width: 100%;
    height: 100px;
    background: url("https://i.ibb.co/wQZVxxk/wave.png");
    background-size: 1000px 100px;
  }

  .wave#wave1 {
    z-index: 1000;
    opacity: 1;
    bottom: 0;
    animation: animateWaves 4s linear infinite;
  }

  .wave#wave2 {
    z-index: 999;
    opacity: 0.5;
    bottom: 10px;
    animation: animate 4s linear infinite !important;
  }

  .wave#wave3 {
    z-index: 1000;
    opacity: 0.2;
    bottom: 15px;
    animation: animateWaves 3s linear infinite;
  }

  .wave#wave4 {
    z-index: 999;
    opacity: 0.7;
    bottom: 20px;
    animation: animate 3s linear infinite;
  }

  @keyframes animateWaves {
    0% {
      background-position-x: 1000px;
    }
    100% {
      background-positon-x: 0px;
    }
  }

  @keyframes animate {
    0% {
      background-position-x: -1000px;
    }
    100% {
      background-positon-x: 0px;
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>

</head>
<body>
     <header class="bg-dark-blue">
        <div class="container">
            <nav id="navbar">
            <h1 class="heading-small"> Buse Nur Çetin</h1>
              <ul>
                <li>Ana Sayfa</li>
                <li>Hakkımda</li>
                <li>İletişim</li>
                <li>Eğitim</li>
              </ul>
        </nav>
        </div>
     </header>
     <section id="home">
        <img src="images/me1.jpeg" alt="Buse Nur Çetin" width="270px">
        <div class="name text-center">
            <h2 class="heading-big">Buse Nur Çetin</h2>
            <p>Student | Developer | Genius </p>
        </div>

        Hakkımda?

     </section>
     <section id= "education" class="bg-dark-blue">
        <h3 class="text-center heading-medium">Ben Kimim?</h3>
        <div class="items">
            <article class="item">
                <i class="fa-solid fa-school"></i>
                <h3>Okul Eğitimleri</h3>
                <p>Okul Eğitimlerimi Görmek İçin Tıklayınız.

                </p>
            </article>

            <article class="item">
                <i class="fa-solid fa-dumbbell"></i>
                <h3>Yaptığım Sporlar</h3>
                <p>Yaptığım Sporları Görmek İçin Tıklayınız.

                </p>
            </article>

            <article class="item">
                <i class="fa-solid fa-medal"></i>
                <h3>Sertifikalar</h3>
                <p>Sertifikalarımı Görmek İçin Tıklayınız.

                </p>
            </article>

        </div>

     </section >
     <section id="about">
        <h3 class="text-center heading-medium">Hakkımda</h3>
        <div class="container">
            <div class="about">
                <!-- hakkımda -->
                <div class="about">
                   <div class="about-image">

                    <div style="text-align: center;">

                   </div>
                   <div class="about-info">
                    <p><h3> Ben Buse Nur Çetin

                    </div><br>

                    <div class="education">
                        <div id="education"></div>
                        <h3 class="text-center heading-medium">Sertifikalar</h3>
                        <div class="education">
                            <div style="text-align:center ;">
                            <div class="education-image">
                                <img src="images/sertifika1.jpeg" alt="Sertifika" width="200px" height="200px" class="yuvarlak" >

                                <div style="text-align:center ;">
                                    <h3> YEA Akademi Sertifikası</h3>
                                </div> <br>

                     <div class="contact">
                        <h1 class="text-center heading- medium">İletişim</h1> <br>

                             <img src="images/insta.jpeg" width="50px"class="yuvarlak" >

                                <img src="images/gmail.jpeg" width="100px"class="yuvarlak" alt="">

                                <img src="images/twitter.png" width="50px"class="yuvarlak" >

                              <!--footer -->

                                <footer class="footer">
                                  <div class="waves">
                                    <div class="wave" id="wave1"></div>
                                    <div class="wave" id="wave2"></div>
                                    <div class="wave" id="wave3"></div>
                                    <div class="wave" id="wave4"></div>
                                  </div>
                                  <ul class="social-icon">
                                    <li class="social-icon__item">
                                        <ion-icon name="logo-facebook"></ion-icon>
                                      </li>
                                    <li class="social-icon__item">
                                        <ion-icon name="logo-twitter"></ion-icon>
                                      </li>
                                    <li class="social-icon__item">
                                        <ion-icon name="logo-linkedin"></ion-icon>
                                      </li>
                                    <li class="social-icon__item">
                                        <ion-icon name="logo-instagram"></ion-icon>
                                      </li>
                                  </ul>
                                  <ul class="menu">
                                    <li class="menu__item">Home</li>
                                    <li class="menu__item">About</li>
                                    <li class="menu__item">Services</li>
                                    <li class="menu__item">Team</li>
                                    <li class="menu__item">Contact</li>

                                  </ul>
                                  <p>©2021 Nadine Coelho | All Rights Reserved</p>
                                </footer>
                                <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
                                <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>

                              <!--bitiş footer-->

                        <div class="contact">
                            <div id="contact"></div>
                            <div style="text-align:center ;"></div>
                        </div>
                     </div>
                                </div>
                            </div>
                        </div>
                    </div>
                   </div>
                </div>
            </div>
        </div>

     </section>

</body>
</html></code>```

Body:
I want my footer to completely cover the bottom but ıt keeps giving me space from the left. you can see my code snippet. i still couldnt figure it out unforteunatly. thanks for all your help

I want my footer to completely cover the bottom but ıt keeps giving me space from the left. you can see my code snippet. i still couldnt figure it out unforteunatly. thanks for all your help

*{
    margin: 0;
    border: 0;
    box-sizing: border-box;
}

a{
    text-decoration: none;
    color:#fff;

}

html{
    font-family:"Open Sans", sans-serif;
    font-family: 'Oswald', sans-serif;
}
#navbar{
    color: #ffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 0.75rem;
    height: 70px;
}
#navbar ul{
    list-style-type: none;
    display: flex;
    align-items: center;
}
#navbar ul li a {
    padding: 0.7rem;
}
#navbar ul li a:hover {
    background: rgb(226, 109, 128);
    border-radius: 5px;
}
#home{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 2rem;
    border-bottom: 1px solid grey;
}
#home img{
    max-width: 100%;
    height: auto;
    border-radius: 100%;
}
#home .name h2{
    margin-bottom: 0.74rem;
}
#home .name p{
    opacity: 0.5;
    font-style:italic;
    font-size:larger;

}
/* home a ve home hover kısmı hakkımda kısmı */
#education{
    color: #fff;
    padding: 1rem;
}
#education .items{
    display: flex;
    justify-content: space-between;
    align-items: center;
}
#education .items .item{
    width: 33%;
    text-align: center;
    padding: 0.5rem;
}
#education .items .item:hover{
    color:palevioletred
}
#education .education-image{
    padding: 1rem;
}

#about{
    color: #333;
    padding: 1rem;
}
.about{
    display: flex;
    flex-direction: column;
    padding: 1rem;
}
.p h3{
    text-align: center;
    word-spacing: 5px;
}
 .abouts .about{
    display: flex;
    padding: 0.5rem;
    margin-bottom: 0.5rem;
 }
 .abouts .about .about-image{
    margin-right: 0.5rem;
    position: relative;
 }
 .abouts .about .about-image{
    border-radius: 50px;
 }
 img.yuvarlak{
    border-radius: 100%;
 }

 @import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800;900&display=swap");

 .footer {
    position: relative;
    width: 100%;
    background: #3586ff;
    min-height: 100px;
    padding: 20px 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }

  .social-icon,
  .menu {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px 0;
    flex-wrap: wrap;
  }

  .social-icon__item,
  .menu__item {
    list-style: none;
  }

  .social-icon__link {
    font-size: 2rem;
    color: #fff;
    margin: 0 10px;
    display: inline-block;
    transition: 0.5s;
  }
  .social-icon__link:hover {
    transform: translateY(-10px);
  }

  .menu__link {
    font-size: 1.2rem;
    color: #fff;
    margin: 0 10px;
    display: inline-block;
    transition: 0.5s;
    text-decoration: none;
    opacity: 0.75;
    font-weight: 300;
  }

  .menu__link:hover {
    opacity: 1;
  }

  .footer p {
    color: #fff;
    margin: 15px 0 10px 0;
    font-size: 1rem;
    font-weight: 300;
  }

  .wave {
    position: absolute;
    top: -100px;
    left: 0;
    width: 100%;
    height: 100px;
    background: url("https://i.ibb.co/wQZVxxk/wave.png");
    background-size: 1000px 100px;
  }

  .wave#wave1 {
    z-index: 1000;
    opacity: 1;
    bottom: 0;
    animation: animateWaves 4s linear infinite;
  }

  .wave#wave2 {
    z-index: 999;
    opacity: 0.5;
    bottom: 10px;
    animation: animate 4s linear infinite !important;
  }

  .wave#wave3 {
    z-index: 1000;
    opacity: 0.2;
    bottom: 15px;
    animation: animateWaves 3s linear infinite;
  }

  .wave#wave4 {
    z-index: 999;
    opacity: 0.7;
    bottom: 20px;
    animation: animate 3s linear infinite;
  }

  @keyframes animateWaves {
    0% {
      background-position-x: 1000px;
    }
    100% {
      background-positon-x: 0px;
    }
  }

  @keyframes animate {
    0% {
      background-position-x: -1000px;
    }
    100% {
      background-positon-x: 0px;
    }
  }

 Buse Nur Çetin

Ana Sayfa

Hakkımda

İletişim

Eğitim

Buse Nur Çetin

Student | Developer | Genius

        Hakkımda?

Ben Kimim?

Okul Eğitimleri

Okul Eğitimlerimi Görmek İçin Tıklayınız.

Yaptığım Sporlar

Yaptığım Sporları Görmek İçin Tıklayınız.

Sertifikalar

Sertifikalarımı Görmek İçin Tıklayınız.

Hakkımda

 Ben Buse Nur Çetin

Sertifikalar

 YEA Akademi Sertifikası

İletişim

                                        <ion-icon name="logo-facebook"></ion-icon>

                                        <ion-icon name="logo-twitter"></ion-icon>

                                        <ion-icon name="logo-linkedin"></ion-icon>

                                        <ion-icon name="logo-instagram"></ion-icon>

Home

About

Services

Team

Contact

©2021 Nadine Coelho | All Rights Reserved


问:
How to create a website location with WebPack
I need to create a site (just HTML, images and JS) and for that I chose to use WebPack, which allows me to create packages with the JS and HTML that will be generated.

One of my goals is to have the site available in English and Spanish, which is accessible through a directory within the site eg: example.com/es-es/contact.html, while in the default language, it will be accessed through example.com/contact.html.

Does WebPack have any native feature that allows you to extract the original text from HTML and JS content, export to an external file (used as a repository of the text to be translated) and build this new site, without having to duplicate the files used in development?


问:
nodejs multiple instances (AWS load balancer) duplicated WS listeners
We have node.js app, hosted on AWS elastic beanstalk  and it uses load balancer. So we have multiple backend instances.
On each instance we create WS listener (to listen to smart contracts events).
e.g.

```<code>ws.on("Event", () => { // handle event })
</code>```

Problem here is that we receive same event multiple times.

We'd like to handle event at most once.

Tried setting in redis "handling" flag. In handler checked if it's true => do nothing. If false => set "handling" to true and handle event.
But faced another issue, sometimes both instances receive false and start handling same event.

```<code>ws.on("Event", async () => {
  const isHandling = await redis.get("handling");
  // isHandling may be null on multiple instances
  if(isHandling !== "true") {
     await redis.set("handling", "true");
     // handle event
  }
})
</code>```

Thank you in advance!

Body:
We have node.js app, hosted on AWS elastic beanstalk  and it uses load balancer. So we have multiple backend instances.
On each instance we create WS listener (to listen to smart contracts events).
e.g.

ws.on("Event", () => { // handle event })

Problem here is that we receive same event multiple times.

We'd like to handle event at most once.

Tried setting in redis "handling" flag. In handler checked if it's true => do nothing. If false => set "handling" to true and handle event.
But faced another issue, sometimes both instances receive false and start handling same event.

ws.on("Event", async () => {
  const isHandling = await redis.get("handling");
  // isHandling may be null on multiple instances
  if(isHandling !== "true") {
     await redis.set("handling", "true");
     // handle event
  }
})

Thank you in advance!


问:
Vitest coverage ignores return statement
I'm just trying to experiment a little and get into strange behavior. Maybe there is something I'm missing and I don't know what to search for, but this is a simple function:

export const evenOrOdd = (number) => {
  if (number % 2 === 0) {
    return "Even";
  }

  return "Odd";
};
```
<p>and test for it:</p>
<pre class="lang-js prettyprint-override"><code>describe("evenOrOdd", () => {
  it("checks if number is even", () => {
    expect(evenOrOdd(2)).toBe("Even");
  });
  // it("checks if number is odd", () => {
  //   expect(evenOrOdd(3)).toBe("Odd");
  // });
});
</code>```

Packages I'm using are:

```<code>"vitest": "^0.25.8"
"@vitest/coverage-c8": "^0.26.2",
</code>```

The issue I'm getting is actually the coverage of return "Odd";. Right now coverage marks it as covered but when I change it to else { return "Odd"; } then the coverage works (in my opinion) as expected and marks that code as not covered with tests.

Am I missing or have lack of knowledge about something?

Body:
I'm just trying to experiment a little and get into strange behavior. Maybe there is something I'm missing and I don't know what to search for, but this is a simple function:

export const evenOrOdd = (number) => {
  if (number % 2 === 0) {
    return "Even";
  }

  return "Odd";
};

and test for it:

describe("evenOrOdd", () => {
  it("checks if number is even", () => {
    expect(evenOrOdd(2)).toBe("Even");
  });
  // it("checks if number is odd", () => {
  //   expect(evenOrOdd(3)).toBe("Odd");
  // });
});

Packages I'm using are:

"vitest": "^0.25.8"
"@vitest/coverage-c8": "^0.26.2",

The issue I'm getting is actually the coverage of return "Odd";. Right now coverage marks it as covered but when I change it to else { return "Odd"; } then the coverage works (in my opinion) as expected and marks that code as not covered with tests.

Am I missing or have lack of knowledge about something?


问:
Unable to convert Python to Window Based app .exe
I'm converting my Main.py python code to .exe application and I need to load ids.txt there are some values line by line, but after converting is done the Auto-py-to-exe-master free Github app says this error message:

```<code>Traceback (most recent call last):
   File "main.py", line 37, in <module>
   FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\janka\\AppData\\Local\\Temp\\_MEI200202\\base_library.zip\\ids.txt'
</code>```

By the way my file location of ids.txt is called in other directory and from application path as follows:

```<code> with open(os.path.join(sys.path[0], "ids.txt"), "r") as f:
    devIds = f.read().splitlines()
</code>```

Body:
I'm converting my Main.py python code to .exe application and I need to load ids.txt there are some values line by line, but after converting is done the Auto-py-to-exe-master free Github app says this error message:

Traceback (most recent call last):
   File "main.py", line 37, in <module>
   FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\janka\\AppData\\Local\\Temp\\_MEI200202\\base_library.zip\\ids.txt'

By the way my file location of ids.txt is called in other directory and from application path as follows:

 with open(os.path.join(sys.path[0], "ids.txt"), "r") as f:
    devIds = f.read().splitlines()


问:
Passing parameters with special characters within Ansible Playbook
I have an Ansible Playbook that uses credentials pulled from a secrets vault. Because the credentials are rotated by Vault there is a chance that the password will contain special characters. The problem is that the password can contain a comma (,) which is causing an error while attempting to pass it in as a parameter to my shell command:

- name: Check if /mnt/ansible_backups exists
  hosts: all

  tasks:
  - name: Check if directory exists
    stat:
      path: /mnt/ansible_backups/playbook_file_check.txt
    register: fc

  - name: If share is not mounted get the secret from Vault
    ansible.builtin.shell: /var/lib/tss/tss secret -s 1 -f password
    register: tss
    no_log: true
    when: fc.stat.exists == false

  - name: Mount the share
    ansible.builtin.shell: mount -t cifs //nas/Backups/Ansible /mnt/ansible_backups -o 'username=user1,domain=contoso,password={{ tss.stdout }}'
    no_log: true
    when: fc.stat.exists == false
```

Is there a way I can pass the arguments (or mount the file share) where I can pass a password that has special characters?

Body:
I have an Ansible Playbook that uses credentials pulled from a secrets vault. Because the credentials are rotated by Vault there is a chance that the password will contain special characters. The problem is that the password can contain a comma (,) which is causing an error while attempting to pass it in as a parameter to my shell command:

- name: Check if /mnt/ansible_backups exists
  hosts: all

  tasks:
  - name: Check if directory exists
    stat:
      path: /mnt/ansible_backups/playbook_file_check.txt
    register: fc

  - name: If share is not mounted get the secret from Vault
    ansible.builtin.shell: /var/lib/tss/tss secret -s 1 -f password
    register: tss
    no_log: true
    when: fc.stat.exists == false

  - name: Mount the share
    ansible.builtin.shell: mount -t cifs //nas/Backups/Ansible /mnt/ansible_backups -o 'username=user1,domain=contoso,password={{ tss.stdout }}'
    no_log: true
    when: fc.stat.exists == false

Is there a way I can pass the arguments (or mount the file share) where I can pass a password that has special characters?