问:
Why is leaflet L not defined inside leaflet.cluster marker group iconCreateFunction when using leaflet as an injectable service?
During runtime I get the following error:

"TypeError: Cannot read properties of undefined (reading 'L')"

The line of code it points to is:

```<code>  return this.mapService.L.divIcon({ html: '<div><span>' +'<b> Coffee: </b> '+ markers + '</span></div>', className: c, iconSize: this.mapService.L.Point(40, 40) });
</code>```

Here is the structure of the code:

MapService.ts

```<code>import { Injectable, PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable()
export class MapService {

  public L = null;
  public geocoder = null;
  public draw = null;
  public AwesomeMarkers = null;
  public markerClusterGroup = null;

  constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    if (isPlatformBrowser(platformId)) {
      this.L = require('leaflet');
      this.geocoder = require('leaflet-control-geocoder');
      this.draw = require('leaflet-draw');
      this.AwesomeMarkers = require('leaflet.awesome-markers');
      this.markerClusterGroup = require('leaflet.markercluster');

    }
  }

}
</code>```

NgModule

```<code>@NgModule({
  declarations: [
    AppComponent,
    ...COMPONENTS,
    ...SHARED_COMPONENTS,
    ...PIPES,
    DeviceDetailsComponent,
    DeviceListComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule.withConfig({warnOnNgModelWithFormControl: 'never'}),
    HttpModule,
    HttpClientModule,
    NgxSpinnerModule,
    BrowserAnimationsModule,
    NgbModule
  ],
  providers: [
    MapService,
    {provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true},
    SHARED_GUARDS,
    SHARED_SERVICES,

  ],
  bootstrap: [AppComponent],
})
</code>```

deviceFile

```<code> constructor(
    private deviceService: DeviceService,
    private loadingService: NgxSpinnerService,
    private usersService: UsersService,
    private authService: AuthService,
    private mapService: MapService
  ) {}

    ngOnInit() {
      this.currentUser = this.authService.getCurrentUser();
      const self = this;
      var map = new this.mapService.L.Map('map').setView([39.82, -98.58], 5);

      mapArray.push(map);
        /*this.mapService.L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      }).addTo(map);*/
    this.mapService.L.tileLayer(
        "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
        {
          attribution: '© <a href="http://www.esri.com/">Esri</a> contributors',
          maxZoom: 21,
          maxNativeZoom: 20,
        }
      ).addTo(map);
      this.initLocations(map);

    // this.loadGeoFences(map);
   // this.loadUsers();

    // secondsCounter.subscribe(n => this.ngUpdate());
  }
</code>```

and the function where the error is which is the last part of this code

```<code>initLocations(map) {
    console.log("initLocations");
    let numdevices = 0;
    let numcoffee = 0;
    let numbattery = 0;
    let numO2 = 0;
    let numCapt = 0;
    let numPOB = 0;
    var init_popup_text = "";
    var coffee_markers = new this.mapService.L.markerClusterGroup( {
      iconCreateFunction: function(cluster){
      var markers = cluster.getChildCount();
      var c = 'coffee-marker-cluster';
      return this.mapService.L.divIcon({ html: '<div><span>' +'<b> Coffee: </b> '+ markers + '</span></div>', className: c, iconSize: this.mapService.L.Point(40, 40) });
    }} );
</code>```

There is no leaflet.js inside the HTML file.  The leaflet plugin is injected into Angular, Marker Cluster Groups work fine without the iconCreate function.  This issue only occurs within the scope of iconCreate.

I could really use your help with a fix or work around.

using the latest stable versions from npm for leaflet and related plugins.

Thank you,

Mike

Body:
During runtime I get the following error:

"TypeError: Cannot read properties of undefined (reading 'L')"

The line of code it points to is:

  return this.mapService.L.divIcon({ html: '
' +' Coffee:  '+ markers + '
', className: c, iconSize: this.mapService.L.Point(40, 40) });

Here is the structure of the code:

MapService.ts

import { Injectable, PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable()
export class MapService {

  public L = null;
  public geocoder = null;
  public draw = null;
  public AwesomeMarkers = null;
  public markerClusterGroup = null;

  constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    if (isPlatformBrowser(platformId)) {
      this.L = require('leaflet');
      this.geocoder = require('leaflet-control-geocoder');
      this.draw = require('leaflet-draw');
      this.AwesomeMarkers = require('leaflet.awesome-markers');
      this.markerClusterGroup = require('leaflet.markercluster');

    }
  }

}

NgModule

@NgModule({
  declarations: [
    AppComponent,
    ...COMPONENTS,
    ...SHARED_COMPONENTS,
    ...PIPES,
    DeviceDetailsComponent,
    DeviceListComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule.withConfig({warnOnNgModelWithFormControl: 'never'}),
    HttpModule,
    HttpClientModule,
    NgxSpinnerModule,
    BrowserAnimationsModule,
    NgbModule
  ],
  providers: [
    MapService,
    {provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true},
    SHARED_GUARDS,
    SHARED_SERVICES,

  ],
  bootstrap: [AppComponent],
})

deviceFile

 constructor(
    private deviceService: DeviceService,
    private loadingService: NgxSpinnerService,
    private usersService: UsersService,
    private authService: AuthService,
    private mapService: MapService
  ) {}

    ngOnInit() {
      this.currentUser = this.authService.getCurrentUser();
      const self = this;
      var map = new this.mapService.L.Map('map').setView([39.82, -98.58], 5);

      mapArray.push(map);
        /*this.mapService.L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          attribution: '© OpenStreetMap contributors'
      }).addTo(map);*/
    this.mapService.L.tileLayer(
        "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
        {
          attribution: '© Esri contributors',
          maxZoom: 21,
          maxNativeZoom: 20,
        }
      ).addTo(map);
      this.initLocations(map);

    // this.loadGeoFences(map);
   // this.loadUsers();

    // secondsCounter.subscribe(n => this.ngUpdate());
  }

and the function where the error is which is the last part of this code

initLocations(map) {
    console.log("initLocations");
    let numdevices = 0;
    let numcoffee = 0;
    let numbattery = 0;
    let numO2 = 0;
    let numCapt = 0;
    let numPOB = 0;
    var init_popup_text = "";
    var coffee_markers = new this.mapService.L.markerClusterGroup( {
      iconCreateFunction: function(cluster){
      var markers = cluster.getChildCount();
      var c = 'coffee-marker-cluster';
      return this.mapService.L.divIcon({ html: '
' +' Coffee:  '+ markers + '
', className: c, iconSize: this.mapService.L.Point(40, 40) });
    }} );

There is no leaflet.js inside the HTML file.  The leaflet plugin is injected into Angular, Marker Cluster Groups work fine without the iconCreate function.  This issue only occurs within the scope of iconCreate.

I could really use your help with a fix or work around.

using the latest stable versions from npm for leaflet and related plugins.

Thank you,

Mike


来源: stackexchange

问:
FCM: Notifications disappear
I use Firebase Cloud Messaging to send push notificaions. When I get two notifications of my app and click on the first one to show the corresponding post in the app, the second notifcation disappears from the notification area (statusbar).

I checked other apps (e.g. news app) and the behavior is different. When I click the first notification here the second one remains in the status bar.

I searched for options I could specify in my notifications, but I did not find anything appropriate. Maybe I'm missing something. Any ideas how to solve this?

ContentLicense: CC BY-SA 4.0

Title: FCM: Notifications disappear


问:
Change attached GIT Hub account on Heroku
I set up a Heroku account and attached it to a GIT Hub account, however, I would like to change which GIT Hub account it is connected to.

For example, if my Heroku account is HerokuUser1, and it is connected to GITHubUser1. I want to change it to GITHUBUser2.

When I go to a Heroku Project, and then the Deploy Tab, and click GITHub under Deployment method, it shows GITHUBUser1 under the drop down for Search a repo to connect to.  I do not see a way to connect GITHUBUser2.

I was expecting an option to change to a different user here.  Perhaps there is another location where I can add a different GITHub account?


问:
Do not treat position as fixed; only use immediately and call `holder.getAdapterPosition()` to look it up later
```<code>@Override
public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
    RecyclerViewModel currentItem = items.get(position);
    holder.imageView.setImageResource(currentItem.getImg());
    holder.textView.setText(currentItem.getText());

    holder.linearLayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          row_index = position;
          notifyDataSetChanged();
      }
    });
    if (row_index == position){
      holder.linearLayout.setBackgroundResource(R.drawable.static_rv_selected_bg);
    }
    else {
      holder.linearLayout.setBackgroundResource(R.drawable.recycler_bg);
    }
}
</code>```

I don't understand the problem here. How do I get rid of this error? It highlights the int position on the first line

I've tried using holder.getAdapterPosition(); but I think I might be using it wrongly?

oh btw getAdapterPosition() is striked through

Body:
@Override
public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
    RecyclerViewModel currentItem = items.get(position);
    holder.imageView.setImageResource(currentItem.getImg());
    holder.textView.setText(currentItem.getText());

    holder.linearLayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          row_index = position;
          notifyDataSetChanged();
      }
    });
    if (row_index == position){
      holder.linearLayout.setBackgroundResource(R.drawable.static_rv_selected_bg);
    }
    else {
      holder.linearLayout.setBackgroundResource(R.drawable.recycler_bg);
    }
}

I don't understand the problem here. How do I get rid of this error? It highlights the int position on the first line

I've tried using holder.getAdapterPosition(); but I think I might be using it wrongly?

oh btw getAdapterPosition() is striked through


问:
Avoid cyclic dependency guice
I have a set of entities, each of which can have subentities. I have converters for each entity.

When i need to convert an entity, i need to convert all the subentities as well. So i need conveters for subentities within the parententityconverter.

There are a lot of entity types, so i have created a util class which contains a Map<EntityType,EntityConverter>.

So, my code looks something like this

```<code>@Allargsconstructor(@Inject)
Class ParentEntityConverter {
private final ConverterUtil converterUtil;
public Entity convert(Entity parentEntity) {
//Do something
converterUtil.convert(parentEntity.getChildren().get(0));
// Do something and return
}
}
</code>```
```<code>@AllArgsConstructor(@Inject)
class ConveterUtil {
private final Map<EntityType,EntityConverter> converterMap;

public Entity convert(Entity entity) {
//do something
Return converterMap.get(entity.type()).convert(entity);
}
}
</code>```

In guice module, i have something like

```<code>@Provides
@Singleton
Map<EntityType,EntityConverter> getConverterMap(
EntityConverter parentEntityConverter,
EntityConverter childEntityConverter,...etc) {
Return Map.of(ParentEntity.type(),parentEntityConverter,
ChildEntity.type(), childEntityConverter,...);
}
</code>```

Now my question, is that,
Since this map containing instance of ParentEntityConverter will be injected into ConverterUtil, and since converterUtil instance will be injected into ParentEntityConverter, doesn't this cause cyclic dependency indirectly? Because parentEntityConverter needs ConverterUtil instance, and ConverterUtil needs parentEntityConverter in map?

If no, then why? If yes, then how come this code is working, shouldn't cyclic dependencies error out in guice?(I have tested that it's working)

Also, is this the best code design for the problem? Or is there a better approach?

Also, will this code cause any garbage collection issues, given that ParentConverter is always referenced by Map, which is always referenced by converterUtil, which is always referenced by parentEntityConverter?

PS: Please ignore syntactically incorrect code, as it's just a pseudocode.

Thanks to everyone in advance.

Title: Avoid cyclic dependency guice

Body:
I have a set of entities, each of which can have subentities. I have converters for each entity.

When i need to convert an entity, i need to convert all the subentities as well. So i need conveters for subentities within the parententityconverter.

There are a lot of entity types, so i have created a util class which contains a Map<EntityType,EntityConverter>.

So, my code looks something like this

@Allargsconstructor(@Inject)
Class ParentEntityConverter {
private final ConverterUtil converterUtil;
public Entity convert(Entity parentEntity) {
//Do something
converterUtil.convert(parentEntity.getChildren().get(0));
// Do something and return
}
}

@AllArgsConstructor(@Inject)
class ConveterUtil {
private final Map<EntityType,EntityConverter> converterMap;

public Entity convert(Entity entity) {
//do something
Return converterMap.get(entity.type()).convert(entity);
}
}

In guice module, i have something like

@Provides
@Singleton
Map<EntityType,EntityConverter> getConverterMap(
EntityConverter parentEntityConverter,
EntityConverter childEntityConverter,...etc) {
Return Map.of(ParentEntity.type(),parentEntityConverter,
ChildEntity.type(), childEntityConverter,...);
}

Now my question, is that,
Since this map containing instance of ParentEntityConverter will be injected into ConverterUtil, and since converterUtil instance will be injected into ParentEntityConverter, doesn't this cause cyclic dependency indirectly? Because parentEntityConverter needs ConverterUtil instance, and ConverterUtil needs parentEntityConverter in map?

If no, then why? If yes, then how come this code is working, shouldn't cyclic dependencies error out in guice?(I have tested that it's working)

Also, is this the best code design for the problem? Or is there a better approach?

Also, will this code cause any garbage collection issues, given that ParentConverter is always referenced by Map, which is always referenced by converterUtil, which is always referenced by parentEntityConverter?

PS: Please ignore syntactically incorrect code, as it's just a pseudocode.

Thanks to everyone in advance.


问:
How do I write a condition?
Comparison of items of combobox with the value entered in the combobox in visual basic apps

```<code>Dim Check as integer

Check = activesheet.cm_code_itme.value
If cm_code_itme.rowsource = Check then
</code>```

Title: How do I write a condition?

Body:
Comparison of items of combobox with the value entered in the combobox in visual basic apps

Dim Check as integer

Check = activesheet.cm_code_itme.value
If cm_code_itme.rowsource = Check then


问:
OAuth 2Client: Invalid token signature
I wanted to handle my user auth by google.

```<code>async verify(token) {
try {

    const ticket = await client.verifyIdToken({
      idToken:token,
      audience: '245409008225-isc00em81fk0vs423pm4jmgc2hcma5jj.apps.googleusercontent.com',
  });

  const payload = ticket.getPayload();

  return payload
} catch (error) {
  console.log(error)
}
</code>```

this code works fine, only for first time to create user in DB. And i save this token to localstorage and retrieve it every time to validate that user is authentificated. Here is my code:

```<code>async isAuth(token) {
    if (!token) {
      false
    }
    const userData = tokenService.verify(token);
    const tokenFromDb = await tokenService.findToken(token);

    if (!userData || !tokenFromDb) {
      throw ApiError.UnAuthorizedError();
    }

    const user = await User.findOne({where: {email: userData.email}});
    await tokenService.saveToken(token);
    return true;
  }
</code>```

I did google, and i supposed to define jwk key for google auth api? But I can't find real solution. So, hope you guys can help me. I never used before google auth. For now I have this solution by making request to this api https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=token and getting from there my user email

Title: OAuth 2Client: Invalid token signature

Body:
I wanted to handle my user auth by google.

async verify(token) {
try {

    const ticket = await client.verifyIdToken({
      idToken:token,
      audience: '245409008225-isc00em81fk0vs423pm4jmgc2hcma5jj.apps.googleusercontent.com',
  });

  const payload = ticket.getPayload();

  return payload
} catch (error) {
  console.log(error)
}

this code works fine, only for first time to create user in DB. And i save this token to localstorage and retrieve it every time to validate that user is authentificated. Here is my code:

async isAuth(token) {
    if (!token) {
      false
    }
    const userData = tokenService.verify(token);
    const tokenFromDb = await tokenService.findToken(token);

    if (!userData || !tokenFromDb) {
      throw ApiError.UnAuthorizedError();
    }

    const user = await User.findOne({where: {email: userData.email}});
    await tokenService.saveToken(token);
    return true;
  }

I did google, and i supposed to define jwk key for google auth api? But I can't find real solution. So, hope you guys can help me. I never used before google auth. For now I have this solution by making request to this api https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=token and getting from there my user email


问:
Boto SNS ConnectTimeoutError exception does not execute in Lambda with connectivity issues
I have a python Lambda function that publishes to an SNS topic. The Lambda was published in the wrong VPC causing it to lose internet connection, making SNS unreachable. That's fine - easy fix.

The problem is that I want to avoid this timeout issue in the future should any connectivity issue arise again, but the Boto timeout configuration does not work - it continues trying to connect until the Lambda times out.

So, the Lambda, which is in a VPC that is NOT connected to the internet has the following:

```<code>import boto3
from botocore.exceptions import ConnectTimeoutError
from botocore.config import Config

# configure client to timeout after 1 second and 1 attempt
config = Config(connect_timeout=1, retries={"max_attempts": 1})
client = boto3.client("sns", config=config)

try:
    client.publish(
        TopicArn='arn:aws:sns:us-east-2:xxxxxxxx:my_topic',
        Message=json.dumps(data),
       )
except ConnectTimeoutError as e:
    print("SNS Publish Timed Out")
</code>```

When I deploy this in the Lambda server with no internet connectivity, I want the SNS publish to timeout, have the exception rescued, print the error and move on. Instead it continues trying to publish until the Lambda times out. Since this SNS message is not mission critical, I need to be able to ditch it if necessary but allow the process to continue.

When I run this locally and set the connect_timeout down to 0.05 it works fine.

Any ideas?

Body:
I have a python Lambda function that publishes to an SNS topic. The Lambda was published in the wrong VPC causing it to lose internet connection, making SNS unreachable. That's fine - easy fix.

The problem is that I want to avoid this timeout issue in the future should any connectivity issue arise again, but the Boto timeout configuration does not work - it continues trying to connect until the Lambda times out.

So, the Lambda, which is in a VPC that is NOT connected to the internet has the following:

import boto3
from botocore.exceptions import ConnectTimeoutError
from botocore.config import Config

# configure client to timeout after 1 second and 1 attempt
config = Config(connect_timeout=1, retries={"max_attempts": 1})
client = boto3.client("sns", config=config)

try:
    client.publish(
        TopicArn='arn:aws:sns:us-east-2:xxxxxxxx:my_topic',
        Message=json.dumps(data),
       )
except ConnectTimeoutError as e:
    print("SNS Publish Timed Out")

When I deploy this in the Lambda server with no internet connectivity, I want the SNS publish to timeout, have the exception rescued, print the error and move on. Instead it continues trying to publish until the Lambda times out. Since this SNS message is not mission critical, I need to be able to ditch it if necessary but allow the process to continue.

When I run this locally and set the connect_timeout down to 0.05 it works fine.

Any ideas?


问:
audio_metadata not shown picture in tkinter button function call

def selectFile():
    filename= fd.askopenfilenames(initialdir="/home/atif/Music/",title="Select an Audio File", filetypes=(("mp3 files", "*.mp3"),("mp4 files", "*.mp4"),("wave files", "*.wav")))
    for s in filename:
        s = s.replace("/home/atif/Music/","")
        songs_list.insert(END,s)

def musicPlay():
    song = songs_list.get(ACTIVE)
    song = f"/home/atif/Music/{song}"
    audioMetaData = audio_metadata.load(song)
    audioPicture = audioMetaData.pictures[0].data
    stream = BytesIO(audioPicture)
    thumImage = Image.open(stream)
    thumImage.thumbnail((300, 300))
    img = ImageTk.PhotoImage(thumImage)
    canvas = Canvas(master=root, width = 300, height = 300)
    canvas.pack()
    canvas.create_image(0, 0, anchor=NW, image=img)
    mixer.music.load(song)
    mixer.music.get_volume()
    mixer.music.play()
    mixer.music.get_busy()
```

Shows picture outside the musicPlay() function but not shown picture while in function

Body:
def selectFile():
    filename= fd.askopenfilenames(initialdir="/home/atif/Music/",title="Select an Audio File", filetypes=(("mp3 files", "*.mp3"),("mp4 files", "*.mp4"),("wave files", "*.wav")))
    for s in filename:
        s = s.replace("/home/atif/Music/","")
        songs_list.insert(END,s)

def musicPlay():
    song = songs_list.get(ACTIVE)
    song = f"/home/atif/Music/{song}"
    audioMetaData = audio_metadata.load(song)
    audioPicture = audioMetaData.pictures[0].data
    stream = BytesIO(audioPicture)
    thumImage = Image.open(stream)
    thumImage.thumbnail((300, 300))
    img = ImageTk.PhotoImage(thumImage)
    canvas = Canvas(master=root, width = 300, height = 300)
    canvas.pack()
    canvas.create_image(0, 0, anchor=NW, image=img)
    mixer.music.load(song)
    mixer.music.get_volume()
    mixer.music.play()
    mixer.music.get_busy()

Shows picture outside the musicPlay() function but not shown picture while in function


问:
Why my viewModel function won't load data from JSON using retrofit?
In my application i'm using Navigation Compose. After implementing it, my viewModel's function getExercises() won't fetch the data. Why is that?

MainActivity:

```<code>class MainActivity : ComponentActivity() {

lateinit var navController: NavHostController
lateinit var viewModel: ExerciseViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        GymEncV2Theme {
            // A surface container using the 'background' color from the theme

            navController = rememberNavController()
            viewModel = ExerciseViewModel()

            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colors.background
            ) {
                SetupNavGraph(navController = navController, viewModel = viewModel)
            }
        }
    }
}
</code>```

}

NavGraph:

```<code>@Composable
</code>```

fun SetupNavGraph(navController: NavHostController, viewModel: ExerciseViewModel) {

```<code>NavHost(navController = navController, startDestination = Screen.Home.route) {

    composable(
        route = Screen.Home.route
    ) {
        HomeScreen(navController = navController)
    }

    composable(
        route = Screen.SampleExercise.route,
        arguments = listOf(navArgument(SAMPLE_EXERCISE_SCREEN_KEY) {
            type = NavType.StringType
        })
    ) {
        SampleExerciseScreen(navController = navController, viewModel = viewModel, muscleGroup = it.arguments?.getString(
            SAMPLE_EXERCISE_SCREEN_KEY).toString())
    }

}
</code>```

}

ExerciseApi built with Retrofit:

```<code>interface ExerciseApi {

@GET("GymEnc_v2.JSON")
suspend fun getExercises() : List<Exercise>

companion object {
    private var exerciseApi: ExerciseApi? = null

    fun getInstance() : ExerciseApi {
        if (exerciseApi == null) {
            exerciseApi = Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(ExerciseApi::class.java)
        }
        return exerciseApi!!
    }
}
</code>```

}

Repository Implementation:

```<code>class ExerciseRepositoryImpl : ExerciseRepository {

private val api = ExerciseApi.getInstance()

override suspend fun getExercises(): List<Exercise> {
    return api.getExercises()

}
</code>```

}

And finally the viewModel:

```<code>class ExerciseViewModel : ViewModel() {

private val repository = ExerciseRepositoryImpl()

var exerciseListResponse : List<Exercise> by mutableStateOf(arrayListOf())
var errorMessage: String by mutableStateOf("")

fun getExercises(): List<Exercise>{
    viewModelScope.launch {

        try {
            val exerciseList = repository.getExercises()
            exerciseListResponse = exerciseList
        } catch (e: Exception) {
            errorMessage = e.message.toString()
        }

    }
    return exerciseListResponse
}
</code>```

}

SampleExercisesScreen:

```<code>@Composable
</code>```

fun SampleExerciseScreen(navController: NavController, muscleGroup: String, viewModel: ExerciseViewModel) {

```<code>val exerciseList = viewModel.getExercises().filter { it.muscle == muscleGroup }

Surface(modifier = Modifier.fillMaxSize(),
color = AppColors.mBackground) {

    Column {

        MyTopBar(navController = navController)

        Text(text = muscleGroup,
        style = MaterialTheme.typography.h3,
        color = AppColors.mDetails,
        fontWeight = FontWeight.Bold,
        textAlign = TextAlign.Center)

        UserExercisesButton()
    }

}
</code>```

}

After using viewModel.getExercises() in SampleExercisesScreen, they simply won't load, leaving me with an empty list.

Body:
In my application i'm using Navigation Compose. After implementing it, my viewModel's function getExercises() won't fetch the data. Why is that?

MainActivity:

class MainActivity : ComponentActivity() {

lateinit var navController: NavHostController
lateinit var viewModel: ExerciseViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        GymEncV2Theme {
            // A surface container using the 'background' color from the theme

            navController = rememberNavController()
            viewModel = ExerciseViewModel()

            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colors.background
            ) {
                SetupNavGraph(navController = navController, viewModel = viewModel)
            }
        }
    }
}

}

NavGraph:

@Composable

fun SetupNavGraph(navController: NavHostController, viewModel: ExerciseViewModel) {

NavHost(navController = navController, startDestination = Screen.Home.route) {

    composable(
        route = Screen.Home.route
    ) {
        HomeScreen(navController = navController)
    }

    composable(
        route = Screen.SampleExercise.route,
        arguments = listOf(navArgument(SAMPLE_EXERCISE_SCREEN_KEY) {
            type = NavType.StringType
        })
    ) {
        SampleExerciseScreen(navController = navController, viewModel = viewModel, muscleGroup = it.arguments?.getString(
            SAMPLE_EXERCISE_SCREEN_KEY).toString())
    }

}

}

ExerciseApi built with Retrofit:

interface ExerciseApi {

@GET("GymEnc_v2.JSON")
suspend fun getExercises() : List<Exercise>

companion object {
    private var exerciseApi: ExerciseApi? = null

    fun getInstance() : ExerciseApi {
        if (exerciseApi == null) {
            exerciseApi = Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(ExerciseApi::class.java)
        }
        return exerciseApi!!
    }
}

}

Repository Implementation:

class ExerciseRepositoryImpl : ExerciseRepository {

private val api = ExerciseApi.getInstance()

override suspend fun getExercises(): List<Exercise> {
    return api.getExercises()

}

}

And finally the viewModel:

class ExerciseViewModel : ViewModel() {

private val repository = ExerciseRepositoryImpl()

var exerciseListResponse : List<Exercise> by mutableStateOf(arrayListOf())
var errorMessage: String by mutableStateOf("")

fun getExercises(): List<Exercise>{
    viewModelScope.launch {

        try {
            val exerciseList = repository.getExercises()
            exerciseListResponse = exerciseList
        } catch (e: Exception) {
            errorMessage = e.message.toString()
        }

    }
    return exerciseListResponse
}

}

SampleExercisesScreen:

@Composable

fun SampleExerciseScreen(navController: NavController, muscleGroup: String, viewModel: ExerciseViewModel) {

val exerciseList = viewModel.getExercises().filter { it.muscle == muscleGroup }

Surface(modifier = Modifier.fillMaxSize(),
color = AppColors.mBackground) {

    Column {

        MyTopBar(navController = navController)

        Text(text = muscleGroup,
        style = MaterialTheme.typography.h3,
        color = AppColors.mDetails,
        fontWeight = FontWeight.Bold,
        textAlign = TextAlign.Center)

        UserExercisesButton()
    }

}

}

After using viewModel.getExercises() in SampleExercisesScreen, they simply won't load, leaving me with an empty list.


问:
Problems with $lookup pyMongo
I am trying to join two different collections from the same database with $lookup. They both share a field "escala". Here I show you both collections.

The first is called "act" and looks like this:

```<code>{'_id': ObjectId('63ab25f01dc3bb3cab48d0ba'), 'actividad': 10388, 'escala': 'BCN'}
{'_id': ObjectId('63ab25f01dc3bb3cab48d0bb'), 'actividad': 8646, 'escala': 'MAD'}
{'_id': ObjectId('63ab25f01dc3bb3cab48d0bc'), 'actividad': 4168, 'escala': 'PMI'}
{'_id': ObjectId('63ab25f01dc3bb3cab48d0bd'), 'actividad': 2778, 'escala': 'IBZ'}
{'_id': ObjectId('63ab25f01dc3bb3cab48d0be'), 'actividad': 2495, 'escala': 'AGP'}
</code>```

...

The other is called "retr" and the documents are like this:

```<code>{'_id': ObjectId('63ab25f91dc3bb3cab48d0d6'), 'retrasos': 2560, 'escala': 'MAD'}
{'_id': ObjectId('63ab25f91dc3bb3cab48d0d7'), 'retrasos': 2463, 'escala': 'BCN'}
{'_id': ObjectId('63ab25f91dc3bb3cab48d0d8'), 'retrasos': 1180, 'escala': 'PMI'}

...
</code>```

As you can see, they both share the field  "escala". There is only a document for each value in "escala" in both documents, so I want to join them.

I run this code:

```<code>puntualidad = retr.aggregate([
{
    "$lookup" : {
        "from": "act",
        "localField": "escala",
        "foreignField": "escala",
        "as" : "result"
    }
}
</code>```

])

And this is what i got:

```<code>{'_id': ObjectId('63ab25f91dc3bb3cab48d0d6'), 'retrasos': 2560, 'escala': 'MAD', 'result': []}
{'_id': ObjectId('63ab25f91dc3bb3cab48d0d7'), 'retrasos': 2463, 'escala': 'BCN', 'result': []}
{'_id': ObjectId('63ab25f91dc3bb3cab48d0d8'), 'retrasos': 1180, 'escala': 'PMI', 'result': []}

...
</code>```

As you can see, the result field is empty. WHY? I'm desperated...

Thanks!!!

Title: Problems with $lookup pyMongo

Body:
I am trying to join two different collections from the same database with $lookup. They both share a field "escala". Here I show you both collections.

The first is called "act" and looks like this:

{'_id': ObjectId('63ab25f01dc3bb3cab48d0ba'), 'actividad': 10388, 'escala': 'BCN'}
{'_id': ObjectId('63ab25f01dc3bb3cab48d0bb'), 'actividad': 8646, 'escala': 'MAD'}
{'_id': ObjectId('63ab25f01dc3bb3cab48d0bc'), 'actividad': 4168, 'escala': 'PMI'}
{'_id': ObjectId('63ab25f01dc3bb3cab48d0bd'), 'actividad': 2778, 'escala': 'IBZ'}
{'_id': ObjectId('63ab25f01dc3bb3cab48d0be'), 'actividad': 2495, 'escala': 'AGP'}

...

The other is called "retr" and the documents are like this:

{'_id': ObjectId('63ab25f91dc3bb3cab48d0d6'), 'retrasos': 2560, 'escala': 'MAD'}
{'_id': ObjectId('63ab25f91dc3bb3cab48d0d7'), 'retrasos': 2463, 'escala': 'BCN'}
{'_id': ObjectId('63ab25f91dc3bb3cab48d0d8'), 'retrasos': 1180, 'escala': 'PMI'}

...

As you can see, they both share the field  "escala". There is only a document for each value in "escala" in both documents, so I want to join them.

I run this code:

puntualidad = retr.aggregate([
{
    "$lookup" : {
        "from": "act",
        "localField": "escala",
        "foreignField": "escala",
        "as" : "result"
    }
}

])

And this is what i got:

{'_id': ObjectId('63ab25f91dc3bb3cab48d0d6'), 'retrasos': 2560, 'escala': 'MAD', 'result': []}
{'_id': ObjectId('63ab25f91dc3bb3cab48d0d7'), 'retrasos': 2463, 'escala': 'BCN', 'result': []}
{'_id': ObjectId('63ab25f91dc3bb3cab48d0d8'), 'retrasos': 1180, 'escala': 'PMI', 'result': []}

...

As you can see, the result field is empty. WHY? I'm desperated...

Thanks!!!


问:
R: Make a box plot using different shapes for data points with no overlapping data points using geom_dotplot()
I have a dataset that looks like this. It's saved as a file called "prescriptivism_scores.csv":

Usage_Guide
Usage_Problem
Prescriptivism_Index

Book 1
who/whom
2

Book 2
who/whom
2

Book 3
who/whom
2.5

Book 4
who/whom
4

Book 5
who/whom
2

Book 6
who/whom
1.5

Book 7
who/whom
3

Book 8
who/whom
2

Book 9
who/whom
4

Book 10
who/whom
4

Book 11
who/whom
2

I used this code

```<code>library(ggplot2)

df <- read.csv(file = 'prescriptivism_scores.csv')
ggplot(df, aes(y = Prescriptivism_Index, x = Usage_Problem)) +
  geom_boxplot(color = "#838383") +

  geom_dotplot(binaxis = "y", stackdir = "center", dotsize = 0.5, color = "#00853E", fill = "#C4D600", stackratio = 1.5) +

  scale_x_discrete(name = "Usage Problem",
                   breaks = c("different_to_than_from", "I_for_me", "lay_lie", "less_fewer", "none", "singular_they", "split_infinitive", "who_whom"),
                   labels = c("DIFF TO/THAN/FROM", "I FOR ME", "LAY/LIE", "LESS/FEWER", "NONE", "SG THEY", "SPLIT INF", "WHO/WHOM")) +

  ylab("Prescriptivism Index") +

  stat_summary(fun.y = mean, geom="point", shape=3, size=3, color="#EF4B81") +

  theme(panel.background = element_blank()) +

  geom_hline(yintercept = 1, linetype = "dashed", linewidth = 0.25, color = "darkgray") +
  geom_hline(yintercept = 2, linetype = "dashed", linewidth = 0.25, color = "darkgray") +
  geom_hline(yintercept = 3, linetype = "dashed", linewidth = 0.25, color = "darkgray") +
  geom_hline(yintercept = 4, linetype = "dashed", linewidth = 0.25, color = "darkgray")

</code>```

to create this box plot

Box plot with no overlapping data points

I'm happy with everything about this box plot except for one thing: I want each dot in the plot to be a different shape to represent the different books in the "Usage_Guide" column of my data. I want to do this so I know which data points correspond to which books.

I've tried adding "shape = Usage_Guide" to the aes() function.

```<code>ggplot(df, aes(y = Prescriptivism_Index, x = Usage_Problem, shape = Usage_Guide)) +
</code>```

But when I do, the dots don't actually change shape, and the dotplot changes so that the dots are overlapping. It also adds dashes to the plot:

Box plot with no box, overlapping data points, and dashes added

If I try to change the color of the dots instead of the shape, I get closer to my end goal, but strange things also happen.

For example, adding a color call to the aes() function and changing the fill to white in the geom_dotplot() function, as shown in the code below, changes the colors of the dots and maintains the box plots, but it causes the data points to overlap.

```<code>ggplot(df, aes(y = Prescriptivism_Index, x = Usage_Problem, color = Usage_Guide)) +
  geom_boxplot(color = "#838383") +

  geom_dotplot(binaxis = "y", stackdir = "center", dotsize = 0.5, fill = "#FFFFFF", stackratio = 1.5) +
</code>```

Box plot with colored overlapping data points

But just reversing the fill and outline so the fill call is in the aes() function the color call is in the geom_dotplot() function breaks something so that the box plots no longer show.

```<code>ggplot(df, aes(y = Prescriptivism_Index, x = Usage_Problem, fill = Usage_Guide)) +
  geom_boxplot(color = "#838383") +

  geom_dotplot(binaxis = "y", stackdir = "center", dotsize = 0.5, color = "#FFFFFF", stackratio = 1.5) +
</code>```

Box plot with no box and overlapping colored data points

How can I maintain the look of my original box plot, but with different shapes for each data point?

Body:
I have a dataset that looks like this. It's saved as a file called "prescriptivism_scores.csv":

Usage_Guide
Usage_Problem
Prescriptivism_Index

Book 1
who/whom
2

Book 2
who/whom
2

Book 3
who/whom
2.5

Book 4
who/whom
4

Book 5
who/whom
2

Book 6
who/whom
1.5

Book 7
who/whom
3

Book 8
who/whom
2

Book 9
who/whom
4

Book 10
who/whom
4

Book 11
who/whom
2

I used this code

library(ggplot2)

df <- read.csv(file = 'prescriptivism_scores.csv')
ggplot(df, aes(y = Prescriptivism_Index, x = Usage_Problem)) +
  geom_boxplot(color = "#838383") +

  geom_dotplot(binaxis = "y", stackdir = "center", dotsize = 0.5, color = "#00853E", fill = "#C4D600", stackratio = 1.5) +

  scale_x_discrete(name = "Usage Problem",
                   breaks = c("different_to_than_from", "I_for_me", "lay_lie", "less_fewer", "none", "singular_they", "split_infinitive", "who_whom"),
                   labels = c("DIFF TO/THAN/FROM", "I FOR ME", "LAY/LIE", "LESS/FEWER", "NONE", "SG THEY", "SPLIT INF", "WHO/WHOM")) +

  ylab("Prescriptivism Index") +

  stat_summary(fun.y = mean, geom="point", shape=3, size=3, color="#EF4B81") +

  theme(panel.background = element_blank()) +

  geom_hline(yintercept = 1, linetype = "dashed", linewidth = 0.25, color = "darkgray") +
  geom_hline(yintercept = 2, linetype = "dashed", linewidth = 0.25, color = "darkgray") +
  geom_hline(yintercept = 3, linetype = "dashed", linewidth = 0.25, color = "darkgray") +
  geom_hline(yintercept = 4, linetype = "dashed", linewidth = 0.25, color = "darkgray")

to create this box plot

Box plot with no overlapping data points

I'm happy with everything about this box plot except for one thing: I want each dot in the plot to be a different shape to represent the different books in the "Usage_Guide" column of my data. I want to do this so I know which data points correspond to which books.

I've tried adding "shape = Usage_Guide" to the aes() function.

ggplot(df, aes(y = Prescriptivism_Index, x = Usage_Problem, shape = Usage_Guide)) +

But when I do, the dots don't actually change shape, and the dotplot changes so that the dots are overlapping. It also adds dashes to the plot:

Box plot with no box, overlapping data points, and dashes added

If I try to change the color of the dots instead of the shape, I get closer to my end goal, but strange things also happen.

For example, adding a color call to the aes() function and changing the fill to white in the geom_dotplot() function, as shown in the code below, changes the colors of the dots and maintains the box plots, but it causes the data points to overlap.

ggplot(df, aes(y = Prescriptivism_Index, x = Usage_Problem, color = Usage_Guide)) +
  geom_boxplot(color = "#838383") +

  geom_dotplot(binaxis = "y", stackdir = "center", dotsize = 0.5, fill = "#FFFFFF", stackratio = 1.5) +

Box plot with colored overlapping data points

But just reversing the fill and outline so the fill call is in the aes() function the color call is in the geom_dotplot() function breaks something so that the box plots no longer show.

ggplot(df, aes(y = Prescriptivism_Index, x = Usage_Problem, fill = Usage_Guide)) +
  geom_boxplot(color = "#838383") +

  geom_dotplot(binaxis = "y", stackdir = "center", dotsize = 0.5, color = "#FFFFFF", stackratio = 1.5) +

Box plot with no box and overlapping colored data points

How can I maintain the look of my original box plot, but with different shapes for each data point?


问:
Object Image not showing
I have done the event handling method for Vue JS, Good news the button click event is working, but the bad news is that my image is not coming through.

What I do find interesting though is if I put the innerHTML in the HTML side of things the image does show.

Anything I am doing wrong?

const app = Vue.createApp({
  baby: [

    {
      id: "botamon",
      name: "Botamon",
      stage: "Baby",
      type: "Data",
      digivolution: ["Koromon"],
      image: "https://www.grindosaur.com/img/games/digimon-world/digimon/12-botamon.jpg"
    },

    {
      id: "poyomon",
      name: "Poyomon",
      stage: "Baby",
      type: "Data",
      digivolution: ["tokomon"],
      image: "https://www.grindosaur.com/img/games/digimon-world/digimon/86-poyomon.jpg"
    },

    {
      id: "punimon",
      name: "Punimon",
      stage: "Baby",
      type: "Data",
      digivolution: ["tsunomon"],
      image: "https://www.grindosaur.com/img/games/digimon-world/digimon/88-punimon.jpg"
    },

    {
      id: "yuramon",
      name: "Yuramon",
      stage: "Baby",
      type: "Data",
      digivolution: ["tanemon"],
      image: "https://www.grindosaur.com/img/games/digimon-world/digimon/123-yuramon.jpg"
    },
  ],

  methods: {
    blueEgg() {
      let container = document.querySelector(".container");
      container.innerHTML = `

In-training Stage

            <button class="close">X</button>

            `

    },
  },

})

app.mount('#app')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.heading {
  display: flex;
}

.heading h1 {
  color: var(--green-color);
  font-size: 15px;
  margin: 0.5em 4em;
}

.close {
  position: relative;
  background-color: var(--green-color);
  border: none;
  padding: 0 0.3em;
}

.close {
  margin-top: 0.3em;
  font-size: 10px;
}

.punimon-image {
  margin: 1.5em 1em;
}

.punimon-image img {
  width: 25%;
  height: 25%;
}</code>```

Which egg do you want?

```

Title: Object Image not showing

Body:
I have done the event handling method for Vue JS, Good news the button click event is working, but the bad news is that my image is not coming through.

What I do find interesting though is if I put the innerHTML in the HTML side of things the image does show.

Anything I am doing wrong?

const app = Vue.createApp({
  baby: [

    {
      id: "botamon",
      name: "Botamon",
      stage: "Baby",
      type: "Data",
      digivolution: ["Koromon"],
      image: "https://www.grindosaur.com/img/games/digimon-world/digimon/12-botamon.jpg"
    },

    {
      id: "poyomon",
      name: "Poyomon",
      stage: "Baby",
      type: "Data",
      digivolution: ["tokomon"],
      image: "https://www.grindosaur.com/img/games/digimon-world/digimon/86-poyomon.jpg"
    },

    {
      id: "punimon",
      name: "Punimon",
      stage: "Baby",
      type: "Data",
      digivolution: ["tsunomon"],
      image: "https://www.grindosaur.com/img/games/digimon-world/digimon/88-punimon.jpg"
    },

    {
      id: "yuramon",
      name: "Yuramon",
      stage: "Baby",
      type: "Data",
      digivolution: ["tanemon"],
      image: "https://www.grindosaur.com/img/games/digimon-world/digimon/123-yuramon.jpg"
    },
  ],

  methods: {
    blueEgg() {
      let container = document.querySelector(".container");
      container.innerHTML = `

In-training Stage

            <button class="close">X</button>

            `

    },
  },

})

app.mount('#app')

.heading {
  display: flex;
}

.heading h1 {
  color: var(--green-color);
  font-size: 15px;
  margin: 0.5em 4em;
}

.close {
  position: relative;
  background-color: var(--green-color);
  border: none;
  padding: 0 0.3em;
}

.close {
  margin-top: 0.3em;
  font-size: 10px;
}

.punimon-image {
  margin: 1.5em 1em;
}

.punimon-image img {
  width: 25%;
  height: 25%;
}

Which egg do you want?


问:
FileNotFoundError: [WinError 2] The system cannot find the file specified
I am trying to open a shortcut for Notepad called Notepad.lnk.

Because I want to learn how to open applications so I can use the pygui library to manipulate them.

Got FileNotFoundError

I got this error:

```<code>Traceback (most recent call last):
  File "C:\Users\{my_name}\PycharmProjects\texture-gen\main.py", line 185, in <module>
    subprocess.run(['start', shortcut_path], check=True)
  File "C:\Users\{my_name}\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 505, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\{my_name}\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\{my_name}\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1420, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
</code>```

Code

This is my python code:

```<code>if __name__ == '__main__':
import os
import subprocess

cwd = os.getcwd()

shortcut_path = os.path.join(cwd, 'Notepad.lnk')
if not os.path.exists(shortcut_path):
    print('Error: "Notepad.lnk" shortcut not found')

subprocess.run(['start', shortcut_path], check=True)
</code>```

Debugging

I have checked the name of the shortcut is Notepad.lnk and is in the current working directory.

Why is this not working?

Body:
I am trying to open a shortcut for Notepad called Notepad.lnk.

Because I want to learn how to open applications so I can use the pygui library to manipulate them.

Got FileNotFoundError

I got this error:

Traceback (most recent call last):
  File "C:\Users\{my_name}\PycharmProjects\texture-gen\main.py", line 185, in <module>
    subprocess.run(['start', shortcut_path], check=True)
  File "C:\Users\{my_name}\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 505, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\{my_name}\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\{my_name}\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1420, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

Code

This is my python code:

if __name__ == '__main__':
import os
import subprocess

cwd = os.getcwd()

shortcut_path = os.path.join(cwd, 'Notepad.lnk')
if not os.path.exists(shortcut_path):
    print('Error: "Notepad.lnk" shortcut not found')

subprocess.run(['start', shortcut_path], check=True)

Debugging

I have checked the name of the shortcut is Notepad.lnk and is in the current working directory.

Why is this not working?


问:
MAUI multiple capture photo
is it possible to take several photos in a row in MAUI? it wants confirmation after each photo. Does this task have a solution? Thanks for any direction to go</p>

Title: MAUI multiple capture photo


问:
Adding variables in a string with multiple quotation marks
I want these 2 string variables in my other string :

```<code>{"prompt":"**String 1**","completion":" **String 2**"}
</code>```

The problem is I run into a problem because of the multiple quotations.

```<code>file_object = open('Sample.txt', 'a')
x = "hello"
y = "hi"
file_object.write('{"prompt":"{}","completion":" {}"}'.format(x,y))
</code>```

This is what I have tried but It doesn't work.

My intended output : {"prompt":"hello","completion":" hi"}

Body:
I want these 2 string variables in my other string :

{"prompt":"**String 1**","completion":" **String 2**"}

The problem is I run into a problem because of the multiple quotations.

file_object = open('Sample.txt', 'a')
x = "hello"
y = "hi"
file_object.write('{"prompt":"{}","completion":" {}"}'.format(x,y))

This is what I have tried but It doesn't work.

My intended output : {"prompt":"hello","completion":" hi"}


问:
¿Can I convert Audio .webm to .ogg with Salesforce?
I am working with an application that uses Aura component to Record Audio with navigator.mediaDevices functionality; the component allows me to record audio and save it in "audio/webm; codecs=opus" with a Blob format, but I am looking for a way to change the audio format to .mp3 or .ogg since I have to send it to another system that does not allow the .webm format.
Note: firefox supports .ogg format but chrome doesn't, only .webm

Is there any way to be able to change the format either by the client or the server side?


问:
Uploaded debug symbols for Android App Bundle

Warning - This App Bundle contains native code, and you've not uploaded debug symbols. We recommend that you upload a symbol file to make your crashes and ANRs easier to analyse and debug.

This message in Playconsole while releasing a Internal test in .aab (Android Studio)

```<code>defaultConfig {
    applicationId "com........"
    minSdk 21
    targetSdk 33
    multiDexEnabled true
    versionCode 2
    versionName "2.2"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
</code>```

Gradle -

```<code>classpath 'com.google.gms:google-services:4.3.14'
</code>```

Where should I add

```<code>android.buildTypes.release.ndk.debugSymbolLevel = { SYMBOL_TABLE | FULL }
</code>```

for Automatic symbol file attachment in .aab ?

Body:
Warning - This App Bundle contains native code, and you've not uploaded debug symbols. We recommend that you upload a symbol file to make your crashes and ANRs easier to analyse and debug.

This message in Playconsole while releasing a Internal test in .aab (Android Studio)

defaultConfig {
    applicationId "com........"
    minSdk 21
    targetSdk 33
    multiDexEnabled true
    versionCode 2
    versionName "2.2"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

Gradle -

classpath 'com.google.gms:google-services:4.3.14'

Where should I add

android.buildTypes.release.ndk.debugSymbolLevel = { SYMBOL_TABLE | FULL }

for Automatic symbol file attachment in .aab ?


问:
Firefox Shortens Urls in Console with dot-dot-dot (...)
I was trying to extract the URLs of certain links on a webpage, using this:

```<code>var links = document.querySelectorAll('a[href*="whatever"]');
for(var i = 0; i < links.length; i++){
  console.log(links[i].href);
};
</code>```

While this works well on Chrome, Firefox shortens the URLs with '...' in console, and trying to save the console content to a file uses the shortened URLs, so not useful:

Any idea on how to fix this?

Body:
I was trying to extract the URLs of certain links on a webpage, using this:

var links = document.querySelectorAll('a[href*="whatever"]');
for(var i = 0; i < links.length; i++){
  console.log(links[i].href);
};

While this works well on Chrome, Firefox shortens the URLs with '...' in console, and trying to save the console content to a file uses the shortened URLs, so not useful:

Any idea on how to fix this?


问:
C++: Large integer values
I have the following C++17 program, which I am running on GNU G++17 7.3.0, which merely adds two square sums as shown below:
`

```<code>#include <iostream>
using namespace std;
int main ()
{
  int lines;
  cin>>lines;
  for(int i = 0; i<lines; i++){
  int m;
  int n;
  cin>>n>>m;
  long sum = m*n*(n+1)/2;
  sum=sum+(m-1)*m/2;

  cout<<sum<<endl;
}
  return 0;
}
</code>```

`

The code works fine for small values, but when I input the values 10000 10000 for n and m, I get a weird answer. I am supposed to get sum = 500099995000. However, I get sum = -263694984. I suspect the value is just too big, so I changed the n and m to long datatypes, but I still get the same error. What is happening here? Furthermore, what are the conventions around these datatype sizes? I hate when I have an algorithm working but not for large input values, which wrap around or overflow.

Thanks in advance!

Title: C++: Large integer values

Body:
I have the following C++17 program, which I am running on GNU G++17 7.3.0, which merely adds two square sums as shown below:
`

#include <iostream>
using namespace std;
int main ()
{
  int lines;
  cin>>lines;
  for(int i = 0; i<lines; i++){
  int m;
  int n;
  cin>>n>>m;
  long sum = m*n*(n+1)/2;
  sum=sum+(m-1)*m/2;

  cout<<sum<<endl;
}
  return 0;
}

`

The code works fine for small values, but when I input the values 10000 10000 for n and m, I get a weird answer. I am supposed to get sum = 500099995000. However, I get sum = -263694984. I suspect the value is just too big, so I changed the n and m to long datatypes, but I still get the same error. What is happening here? Furthermore, what are the conventions around these datatype sizes? I hate when I have an algorithm working but not for large input values, which wrap around or overflow.

Thanks in advance!


问:
Invocation of Python Lambda from AWS CodePipeline takes much longer than Lambda runtime
I have a Lambda written in Python that runs in about 150ms. When I call that Lambda from a CodePipeline, it takes about 30 seconds to complete.

There's no information in the CodePipeline nor the Lambda's logs that indicates where the extra time is being spent.

Now I fully appreciate that this is a very, very minor issue but I'm curious as to what's really going on in those 30 seconds. Does anybody know?

It appears that the vast majority of the time is being spent in CodePipeline, not in Lambda. I wish CodePipeline could explain what it's doing for those extra seconds, but I've found the logs to be quite inadequate.

I would consider this solved, since I don't think it's worth digging into more.


问:
while bool variable is true I want to display CurcularProgressIndicator() for some duration, but its not showing in flutter
//This is the Class of one of my app page (MainPage)

It has showindicator() function which is turning _isloader into true for 10 seconds.

```<code>class MainPage extends StatefulWidget {
  MainPage({Key? key}) : super(key: key);

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  bool _isloader = false;

Future<void> showindicator() async {
    _isloader = true;
    print("_isloader before $_isloader");
    await Future.delayed(Duration(seconds: 10));
    print("_isloader after$_isloader");
    _isloader = false;
    Get.to(PersonalAssessment());
    print("_isloader afteroperation$_isloader");
  }
</code>```

//This the Main Widget Build function

```<code>  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: MyColors.backgrey,
      body: ListView(
        children: [
          Stack(
            children: [
              Center(
                child: Container(
                  margin: EdgeInsets.only(
                    left: 20,
                    right: 20,
                    top: 20,
                  ),
                  child: GlowGlass(
                    Customheight: 200,
                    Customwidth: double.maxFinite,
                    Firstcolor: Colors.black.withOpacity(.8),
                    Secondcolor: MyColors.Primarypurple.withOpacity(.4),
                  ),
                ),
              ),
              Center(
                child: Container(
                  height: 200,
                  width: 250,
                  margin: EdgeInsets.only(
                    left: 20,
                    right: 20,
                    top: 20,
                  ),
                  child: CarouselSlider(
                      items: Appconstants.mainimages
                          .map(
                            (e) => Container(
                              height: 200,
                              width: double.maxFinite,
                              decoration: BoxDecoration(
                                // color: MyColors.Primarypurple,

                                image: DecorationImage(
                                  fit: BoxFit.cover,
                                  image: AssetImage(
                                    e,
                                  ),
                                ),
                              ),
                            ),
                          )
                          .toList(),
                      options: CarouselOptions(
                        scrollDirection: Axis.vertical,
                        autoPlay: true,
                        aspectRatio: 16 / 9,
                        viewportFraction: 1,
                        enlargeCenterPage: true,
                      )),
                ),
              ),
              Center(
                  child: Container(
                margin: EdgeInsets.only(
                  top: 230,
                  left: 10,
                  right: 10,
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(30),
                  child: Container(
                    height: 400,
                    width: 400,
                    color: Colors.white,
                    child: Column(
                      children: [
                        SizedBox(height: 20),

</code>```

//here I wrapped Widgets into GestureDetector, so when I tap
showindicator() runs _isloader turn to true for 10 seconds and for 10 seconds CircularProgressIndicator() displays on screen but unfortunately its not showing on screen although showindicator() works perfectly.

```<code>                              GestureDetector(
                              onTap: () {
                                showindicator();
Center(child:
CircularProgressIndicator());
                              },
                              child: Column(
                                children: [
                                  Container(
                                    height: 200,
                                    width: 360,
                                    decoration: BoxDecoration(
                                      boxShadow: [
                                        BoxShadow(
                                          color: Colors.black54,
                                          blurRadius: 10,
                                        )
                                      ],
                                      color: MyColors.backgrey,
                                      borderRadius: BorderRadius.circular(20),
                                    ),
                                    child: Row(
                                      children: [
                                        Container(
                                          margin: EdgeInsets.only(left: 10),
                                          height: 170,
                                          width: 150,
                                          decoration: BoxDecoration(
                                            boxShadow: [
                                              BoxShadow(
                                                color: MyColors.Primarypurple,
                                                blurRadius: 10,
                                              )
                                            ],
                                            // color: Colors.blue,
                                            borderRadius: BorderRadius.only(
                                              topLeft: Radius.circular(30),
                                              bottomLeft: Radius.circular(30),
                                              bottomRight: Radius.circular(30),
                                              topRight: Radius.circular(30),
                                            ),
                                            image: DecorationImage(
                                              fit: BoxFit.cover,
                                              image: AssetImage(
                                                  "lib/Assets/images/dekstop.PNG"),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  )),
                ],
              ),
            ],
          ),
        );
      }
    }
</code>```

Body:
//This is the Class of one of my app page (MainPage)

It has showindicator() function which is turning _isloader into true for 10 seconds.

class MainPage extends StatefulWidget {
  MainPage({Key? key}) : super(key: key);

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  bool _isloader = false;

Future<void> showindicator() async {
    _isloader = true;
    print("_isloader before $_isloader");
    await Future.delayed(Duration(seconds: 10));
    print("_isloader after$_isloader");
    _isloader = false;
    Get.to(PersonalAssessment());
    print("_isloader afteroperation$_isloader");
  }

//This the Main Widget Build function

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: MyColors.backgrey,
      body: ListView(
        children: [
          Stack(
            children: [
              Center(
                child: Container(
                  margin: EdgeInsets.only(
                    left: 20,
                    right: 20,
                    top: 20,
                  ),
                  child: GlowGlass(
                    Customheight: 200,
                    Customwidth: double.maxFinite,
                    Firstcolor: Colors.black.withOpacity(.8),
                    Secondcolor: MyColors.Primarypurple.withOpacity(.4),
                  ),
                ),
              ),
              Center(
                child: Container(
                  height: 200,
                  width: 250,
                  margin: EdgeInsets.only(
                    left: 20,
                    right: 20,
                    top: 20,
                  ),
                  child: CarouselSlider(
                      items: Appconstants.mainimages
                          .map(
                            (e) => Container(
                              height: 200,
                              width: double.maxFinite,
                              decoration: BoxDecoration(
                                // color: MyColors.Primarypurple,

                                image: DecorationImage(
                                  fit: BoxFit.cover,
                                  image: AssetImage(
                                    e,
                                  ),
                                ),
                              ),
                            ),
                          )
                          .toList(),
                      options: CarouselOptions(
                        scrollDirection: Axis.vertical,
                        autoPlay: true,
                        aspectRatio: 16 / 9,
                        viewportFraction: 1,
                        enlargeCenterPage: true,
                      )),
                ),
              ),
              Center(
                  child: Container(
                margin: EdgeInsets.only(
                  top: 230,
                  left: 10,
                  right: 10,
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(30),
                  child: Container(
                    height: 400,
                    width: 400,
                    color: Colors.white,
                    child: Column(
                      children: [
                        SizedBox(height: 20),

//here I wrapped Widgets into GestureDetector, so when I tap
showindicator() runs _isloader turn to true for 10 seconds and for 10 seconds CircularProgressIndicator() displays on screen but unfortunately its not showing on screen although showindicator() works perfectly.

                              GestureDetector(
                              onTap: () {
                                showindicator();
Center(child:
CircularProgressIndicator());
                              },
                              child: Column(
                                children: [
                                  Container(
                                    height: 200,
                                    width: 360,
                                    decoration: BoxDecoration(
                                      boxShadow: [
                                        BoxShadow(
                                          color: Colors.black54,
                                          blurRadius: 10,
                                        )
                                      ],
                                      color: MyColors.backgrey,
                                      borderRadius: BorderRadius.circular(20),
                                    ),
                                    child: Row(
                                      children: [
                                        Container(
                                          margin: EdgeInsets.only(left: 10),
                                          height: 170,
                                          width: 150,
                                          decoration: BoxDecoration(
                                            boxShadow: [
                                              BoxShadow(
                                                color: MyColors.Primarypurple,
                                                blurRadius: 10,
                                              )
                                            ],
                                            // color: Colors.blue,
                                            borderRadius: BorderRadius.only(
                                              topLeft: Radius.circular(30),
                                              bottomLeft: Radius.circular(30),
                                              bottomRight: Radius.circular(30),
                                              topRight: Radius.circular(30),
                                            ),
                                            image: DecorationImage(
                                              fit: BoxFit.cover,
                                              image: AssetImage(
                                                  "lib/Assets/images/dekstop.PNG"),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  )),
                ],
              ),
            ],
          ),
        );
      }
    }


问:
Concatenating json artifacts from a previous set of parallel jobs
We split our regression tests into several parallel jobs that each produce a json artifact providing some data about the test results. I would like to create a new job that produces a single artifact with all regression results concatenate. The number of parallel jobs is not necessarily static. The most similar post I've seen is this, Get artifacts from previous GIT jobs, but my jobs are parallel jobs that produce the same file name (although I suppose output names can include node number for simplicity).

I've read that a job will automatically download artifacts from previous jobs, but how can I actually load/use this data in a script?


问:
Linear Optimization in R with multiple variables
I was wondering if this was an linear optimization problem or something else.

I've multiple assets, with x cash invested on them (x1,x2,x3,...x100), each asset has a gain or loss associated with it (y1,y2,y3,...y100).

I need to find the combination of assets, no matter the number of assets, that maximizes the cash I receive and minimizes the loss.

The restriction would be a random number of sum of cash to be received

Thanks in advance


问:
How to store user messages without losing markup in telegram bots?
How do I store user messages without losing markup (HTML or Markdown) in the Telegram bots?
I'm working with node_telegram_bot_api

It's clear when sending a message from the bot to the user: specify parse_mode and everything is fine.

```<code>await bot.sendMessage(chatId, message, {reply_markup: JSON.stringify({inline_keyboard: keyboard}), parse_mode: 'HTML'});
</code>```

But how to process messages with user markup and then store them in a database, for example, without losing the markup?

Body:
How do I store user messages without losing markup (HTML or Markdown) in the Telegram bots?
I'm working with node_telegram_bot_api

It's clear when sending a message from the bot to the user: specify parse_mode and everything is fine.

await bot.sendMessage(chatId, message, {reply_markup: JSON.stringify({inline_keyboard: keyboard}), parse_mode: 'HTML'});

But how to process messages with user markup and then store them in a database, for example, without losing the markup?


问:
Need help exploiting preg_replace() vulnerability
I'm doing a CTF security challenge, I found a "downloader.php" page with a possible vulnerability.

it lets me download any file from the server, including "downloader.php" itself, the problem is running through all known php files, I couldn't find an access point.

I'm thinking of entering through the downloader.php itself, but it has a filename treatment with preg_replace, and I need to work around that.

Here is the code of the file "download.php":

```<code><?php

$dnpath = $_GET['name'];
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = preg_replace("/[ #\&\+\%@=\\\:;,'\"\^`~|\!\?\*$#<>()\[\]\{\}]/i", "", $dnpath);

$lastDate = '0';

$file = "C:/test_root/".$dnpath;
if (!file_exists($file))
{
    echo "File not exist : ";
    echo $file;
    exit;
}

Header("Content-type: application/octet-stream");
Header("Content-Length: ".filesize($file));
Header("Content-Disposition: attachment; filename=\"$dnpath\"");
Header("Pragma: no-cache");

ob_clean();
flush();
readfile($file);
return true;
?>
</code>```

i tried something like:

downloader.php?name=alert(%22XSS%22)

but without success because of preg_replace

Body:
I'm doing a CTF security challenge, I found a "downloader.php" page with a possible vulnerability.

it lets me download any file from the server, including "downloader.php" itself, the problem is running through all known php files, I couldn't find an access point.

I'm thinking of entering through the downloader.php itself, but it has a filename treatment with preg_replace, and I need to work around that.

Here is the code of the file "download.php":

<?php

$dnpath = $_GET['name'];
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = str_replace("..",".", $dnpath);
$dnpath = preg_replace("/[ #\&\+\%@=\\\:;,'\"\^`~|\!\?\*$#<>()\[\]\{\}]/i", "", $dnpath);

$lastDate = '0';

$file = "C:/test_root/".$dnpath;
if (!file_exists($file))
{
    echo "File not exist : ";
    echo $file;
    exit;
}

Header("Content-type: application/octet-stream");
Header("Content-Length: ".filesize($file));
Header("Content-Disposition: attachment; filename=\"$dnpath\"");
Header("Pragma: no-cache");

ob_clean();
flush();
readfile($file);
return true;
?>

i tried something like:

downloader.php?name=alert(%22XSS%22)

but without success because of preg_replace


问:
RAM errors on Adobe Premiere
I have a question:

Every time I open adobe premiere, the PC starts to go super slow, I get notices that adobe runs with low memory and I can't open any application, or the blue screen jumps out...
The thing is that I have 16GB and when I enter the task manager, I see that adobe is using at most 4.
How do I fix this?

Title: RAM errors on Adobe Premiere


问:
Getting cURL error 56: Recv failure: Connection reset by peer error when I want to send request to other service
I researched a lot but I didn't find any solution to solve my problem so I decided to ask a question here. I have 2 services that are written in Lumen and They're correctly running with docker.
This is my product service's docker-compose.yml:

```<code>services:

product_nginx:
  image: nginx:alpine
  container_name: product_nginx
  ports:
    - "8080:80"
  volumes:
    - ./src:/var/www
    - ./nginx/conf.d/:/etc/nginx/conf.d/
  depends_on:
    - product_app
    - product_db
  networks:
    - shopnet

product_app:
  container_name: product_app
  build:
    context: ./php
    dockerfile: Dockerfile
  volumes:
    - ./src:/var/www
  ports:
    - "9000:9000"
  working_dir: /var/www
  expose:
    - 9000
  networks:
    - shopnet

networks:
  shopnet:
    external: true
</code>```

There is a route that is just for returning a string in product service:

```<code>$router->group(['prefix' => 'api'], function () use ($router) {
   $router->group(['prefix' => 'products'], function () use ($router) {
      $router->get('/', function () {
        return 'List of Products';
      });
   });
});
</code>```

and Here is the nginx/conf.d/default.conf:

```<code>server {
 listen 80;
 index index.php index.htm index.html;
 error_log /var/log/nginx/error.log;
 access_log /var/log/nginx/access.log;
 server_name localhost;
 root /var/www/public;

 location /index.php {
    try_files $uri = 404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass product_app:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
 }
}
</code>```

The second service has the same structure but its web server is running on port 8888 with gateway_nginx name and the app service has gateway_app name and is running on port 9002, I want to send a request to the product service. with the below code:

```<code>$router->group(['prefix' => 'api'], function () use ($router)
 {
   $router->group(['prefix' => 'service1'], function () use ($router)
   {
    $router->get('/', function()
    {
        $response = Http::get('http://product_app:9000/api/products');
        return $response;
     });
  });
});
</code>```

But after calling the 127.0.0.1:8888/api/service1 I get the below error:

How can I solve this problem?

Body:
I researched a lot but I didn't find any solution to solve my problem so I decided to ask a question here. I have 2 services that are written in Lumen and They're correctly running with docker.
This is my product service's docker-compose.yml:

services:

product_nginx:
  image: nginx:alpine
  container_name: product_nginx
  ports:
    - "8080:80"
  volumes:
    - ./src:/var/www
    - ./nginx/conf.d/:/etc/nginx/conf.d/
  depends_on:
    - product_app
    - product_db
  networks:
    - shopnet

product_app:
  container_name: product_app
  build:
    context: ./php
    dockerfile: Dockerfile
  volumes:
    - ./src:/var/www
  ports:
    - "9000:9000"
  working_dir: /var/www
  expose:
    - 9000
  networks:
    - shopnet

networks:
  shopnet:
    external: true

There is a route that is just for returning a string in product service:

$router->group(['prefix' => 'api'], function () use ($router) {
   $router->group(['prefix' => 'products'], function () use ($router) {
      $router->get('/', function () {
        return 'List of Products';
      });
   });
});

and Here is the nginx/conf.d/default.conf:

server {
 listen 80;
 index index.php index.htm index.html;
 error_log /var/log/nginx/error.log;
 access_log /var/log/nginx/access.log;
 server_name localhost;
 root /var/www/public;

 location /index.php {
    try_files $uri = 404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass product_app:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
 }
}

The second service has the same structure but its web server is running on port 8888 with gateway_nginx name and the app service has gateway_app name and is running on port 9002, I want to send a request to the product service. with the below code:

$router->group(['prefix' => 'api'], function () use ($router)
 {
   $router->group(['prefix' => 'service1'], function () use ($router)
   {
    $router->get('/', function()
    {
        $response = Http::get('http://product_app:9000/api/products');
        return $response;
     });
  });
});

But after calling the 127.0.0.1:8888/api/service1 I get the below error:

How can I solve this problem?


问:
iframe is loaded successfully but element is not available, displaying blank screen
When I run the spec, it runs successfully after loading the iframe but elements are not visible from the iframe. Below are the screenshots for same. Also added

```<code> chromeWebSecurity: false
</code>```

in the cypress.config.js file and imported cypress-iframe in the spec file
[[enter image description here]enter image description here(https://i.stack.imgur.com/UkloV.png)](https://i.stack.imgur.com/xSUXG.png)

Expected to get all the elements loaded after the iframe was successfully located

Body:
When I run the spec, it runs successfully after loading the iframe but elements are not visible from the iframe. Below are the screenshots for same. Also added

 chromeWebSecurity: false

in the cypress.config.js file and imported cypress-iframe in the spec file
[[enter image description here]enter image description here(https://i.stack.imgur.com/UkloV.png)](https://i.stack.imgur.com/xSUXG.png)

Expected to get all the elements loaded after the iframe was successfully located


问:
How to Logout from Firebase Account to Login Screen from Fragment
My idea is to log out of the firebase account through a fragment, i.e. on the icon in the navigation menu (which is below), the active account is logged out and the login activity is switched to. I did it, but it doesn’t work the way I wanted, that is, the exit occurs after switching to the fragment and you need to click on the icon again. And when you press the back button on your smartphone, it opens the previous activity that was, how to remove it? The code which is in the fragment:

```<code>View exit;
    FirebaseAuth firebaseAuth;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        exit = getActivity().findViewById(R.id.exit);

        firebaseAuth = FirebaseAuth.getInstance();

        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirebaseAuth.getInstance().signOut();
                Intent intent = new Intent(new Intent(ExitFragment.this.getParentFragment().getActivity(), MainActivityEntrance.class));
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

                startActivity(intent);

            }
        });
</code>```

Screenshot of navigation menu:
enter image description here

Body:
My idea is to log out of the firebase account through a fragment, i.e. on the icon in the navigation menu (which is below), the active account is logged out and the login activity is switched to. I did it, but it doesn’t work the way I wanted, that is, the exit occurs after switching to the fragment and you need to click on the icon again. And when you press the back button on your smartphone, it opens the previous activity that was, how to remove it? The code which is in the fragment:

View exit;
    FirebaseAuth firebaseAuth;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        exit = getActivity().findViewById(R.id.exit);

        firebaseAuth = FirebaseAuth.getInstance();

        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirebaseAuth.getInstance().signOut();
                Intent intent = new Intent(new Intent(ExitFragment.this.getParentFragment().getActivity(), MainActivityEntrance.class));
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

                startActivity(intent);

            }
        });

Screenshot of navigation menu:
enter image description here


问:
How can one parse whole XML documents using the LXML Sax module?
I have a script that goes through a directory with many XML files and extracts or adds information to these files. I use XPath to identify the elements of interest.

The relevant piece of code is this:

```<code>import lxml.etree as et
import lxml.sax

# deleted non relevant code

 for root, dirs, files in os.walk(ROOT):

        # iterate all files
        for file in files:

            if file.endswith('.xml'):

                # join root dir and file name
                file_path = os.path.join(ROOT, file)

                # load root element from file
                file_root = et.parse(file_path).getroot()

                # This is a function that I define elsewhere in which I use XPath to identify relevant
                # elements and extract, change or add some information
                xml_dosomething(file_root)

                # init tree object from file_root
                tree = et.ElementTree(file_root)

                # save modified xml tree object to file with an added text so that I can keep a copy of original.

                tree.write(file_path.replace('.xml', '-clean.xml'), encoding='utf-8', doctype='<!DOCTYPE document SYSTEM "estcorpus.dtd">', xml_declaration=True)

</code>```

I have seen in various places that people recommend using Sax(on) to speed up the processing of large files. After checking the documentation of the LXML Sax module in (https://lxml.de/sax.html) I'm at a loss as to how to modify my code so that I can leverage the Sax module. I can see the following in the documentation:

```<code>handler = lxml.sax.ElementTreeContentHandler()
</code>```

then there is a list of statements like (handler.startElementNS((None, 'a'), 'a', {})) that would populate the 'handler' "document" (?) with what would be the elements of a the XML document. After that I see:

```<code>tree = handler.etree
lxml.etree.tostring(tree.getroot())
</code>```

I think I understand what handler.etree does but my problem is that I want 'handler' to be the files in the directory that I'm working with rather than a string that I create by using 'handler.startElementNS' and the like. What do I need to change in my code to get the Sax module to do the work that needs to be done with the files as input?

Body:
I have a script that goes through a directory with many XML files and extracts or adds information to these files. I use XPath to identify the elements of interest.

The relevant piece of code is this:

import lxml.etree as et
import lxml.sax

# deleted non relevant code

 for root, dirs, files in os.walk(ROOT):

        # iterate all files
        for file in files:

            if file.endswith('.xml'):

                # join root dir and file name
                file_path = os.path.join(ROOT, file)

                # load root element from file
                file_root = et.parse(file_path).getroot()

                # This is a function that I define elsewhere in which I use XPath to identify relevant
                # elements and extract, change or add some information
                xml_dosomething(file_root)

                # init tree object from file_root
                tree = et.ElementTree(file_root)

                # save modified xml tree object to file with an added text so that I can keep a copy of original.

                tree.write(file_path.replace('.xml', '-clean.xml'), encoding='utf-8', doctype='<!DOCTYPE document SYSTEM "estcorpus.dtd">', xml_declaration=True)

I have seen in various places that people recommend using Sax(on) to speed up the processing of large files. After checking the documentation of the LXML Sax module in (https://lxml.de/sax.html) I'm at a loss as to how to modify my code so that I can leverage the Sax module. I can see the following in the documentation:

handler = lxml.sax.ElementTreeContentHandler()

then there is a list of statements like (handler.startElementNS((None, 'a'), 'a', {})) that would populate the 'handler' "document" (?) with what would be the elements of a the XML document. After that I see:

tree = handler.etree
lxml.etree.tostring(tree.getroot())

I think I understand what handler.etree does but my problem is that I want 'handler' to be the files in the directory that I'm working with rather than a string that I create by using 'handler.startElementNS' and the like. What do I need to change in my code to get the Sax module to do the work that needs to be done with the files as input?


问:
How I install wxWidgets in msys2 correctly?
I'm having trouble installing wxWidgets in msys2, I used pacman to install the library

```<code>pacman -S mingw-w64-clang-x86_64-wxwidgets3.0-msw
</code>```

But when I try to execute a test file it gives me this error

fatal error: wx/wx.h: No such file or directory

Reading online I see that are in another methods of installing the library you have to compile it, but I can't find any information in regards to installing it with pacman.

I also tried to compile it myself with Cmake following the instructions in the wxwidgets page but I failed and I want to see what should I do now.

What I need to do to get this to work?

Body:
I'm having trouble installing wxWidgets in msys2, I used pacman to install the library

pacman -S mingw-w64-clang-x86_64-wxwidgets3.0-msw

But when I try to execute a test file it gives me this error

fatal error: wx/wx.h: No such file or directory

Reading online I see that are in another methods of installing the library you have to compile it, but I can't find any information in regards to installing it with pacman.

I also tried to compile it myself with Cmake following the instructions in the wxwidgets page but I failed and I want to see what should I do now.

What I need to do to get this to work?


问:
I am having problems with booleans staying as I define them
```<code>B=False

def func1():
    def func2():
        global B
        if B == True:
            print("True")
            B=False
        else:
            print("False")

    B=True
    func2()
func1()
</code>```

This is an example of the problem I am having, when I set a variable as a Boolean within a function, the Boolean seems to change when brought to another function, e.g. here the Boolean B is set to True in func1() but in func2(), where B should still be True, the output of the code is False, signifying the Boolean has become False.

Body:
B=False

def func1():
    def func2():
        global B
        if B == True:
            print("True")
            B=False
        else:
            print("False")

    B=True
    func2()
func1()

This is an example of the problem I am having, when I set a variable as a Boolean within a function, the Boolean seems to change when brought to another function, e.g. here the Boolean B is set to True in func1() but in func2(), where B should still be True, the output of the code is False, signifying the Boolean has become False.


问:
How can I append json data in memory to the end of a new-line delimited json file without reading the file into memory in Rust?
If I have a new-line delimited json file that looks something like this:

{"name":"butthead"}
{"name":"second-butthead"}
{"name":"third-butthead"}
```
<p>And I have data loaded into memory that looks like this:</p>
<pre class="lang-json prettyprint-override"><code>{"name":"fourth-butthead"}
</code>```

How can I append the data I have in memory to the end of the json file without reading the json file into memory, using Rust, so that the json file ends like this:

{"name":"butthead"}
{"name":"second-butthead"}
{"name":"third-butthead"}
{"name":"fourth-butthead"}
```

Body:
If I have a new-line delimited json file that looks something like this:

{"name":"butthead"}
{"name":"second-butthead"}
{"name":"third-butthead"}

And I have data loaded into memory that looks like this:

{"name":"fourth-butthead"}

How can I append the data I have in memory to the end of the json file without reading the json file into memory, using Rust, so that the json file ends like this:

{"name":"butthead"}
{"name":"second-butthead"}
{"name":"third-butthead"}
{"name":"fourth-butthead"}


问:
NextRouter was not mounted
I am trying to implement a search feature for my property renting app. I added the Nextjs Router. When I go to localhost:3000/search, however, I get this error:

```<code>Server Error
Error: Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
useRouter
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/next/dist/client/router.js (122:15)
pages\search.tsx (10:28) @ Search

   8 | const Search = () => {
   9 | const [searchFilters, setSearchFilters] = useState(false);
> 10 | const router = useRouter();
     |                        ^
  11 |
  12 | return (
  13 |     <Box>
Call Stack
renderWithHooks
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5658:16)
renderIndeterminateComponent
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5731:15)
renderElement
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5946:7)
renderNodeDestructiveImpl
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6104:11)
renderNodeDestructive
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6076:14)
renderNode
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6259:12)
renderHostElement
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5642:3)
renderElement
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5952:5)
</code>```

My code in search.tsx is as follows, it is not as of yet complete:

```<code>import {useState} from 'react';
import { useRouter } from 'next/router';
import Image from 'next/image';
import {Flex, Box, Text, Icon} from '@chakra-ui/react';
import { BsFilter } from 'react-icons/bs';
import SearchFilters from '../components/SearchFilters';

const Search = () => {
    const [searchFilters, setSearchFilters] = useState(false);
    const router = useRouter();

    return (
        <Box>
            <Flex
            cursor="pointer"
            bg="gray.100"
            borderBottom="1px"
            borderColor="gray.200"
            p="2"
            fontWeight="black"
            fontSize="lg"
            justifyContent="center"
            alignItems="center"
            onClick={() => setSearchFilters((prevFilters) => !prevFilters)}
            >
        <Text>Filtrele</Text>
        <Icon paddingLeft="2" w="7" as={BsFilter}></Icon>
            </Flex>
            {searchFilters && <SearchFilters />}
        </Box>
    )
}

export default Search;
</code>```

I read the Nextjs docs, and I've checked Stackoverflow for answers but none works. This should be fairly straightforward but I don't get what I am doing wrong.

Title: NextRouter was not mounted

Body:
I am trying to implement a search feature for my property renting app. I added the Nextjs Router. When I go to localhost:3000/search, however, I get this error:

Server Error
Error: Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
useRouter
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/next/dist/client/router.js (122:15)
pages\search.tsx (10:28) @ Search

   8 | const Search = () => {
   9 | const [searchFilters, setSearchFilters] = useState(false);
> 10 | const router = useRouter();
     |                        ^
  11 |
  12 | return (
  13 |     <Box>
Call Stack
renderWithHooks
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5658:16)
renderIndeterminateComponent
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5731:15)
renderElement
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5946:7)
renderNodeDestructiveImpl
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6104:11)
renderNodeDestructive
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6076:14)
renderNode
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6259:12)
renderHostElement
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5642:3)
renderElement
file:///C:/Users/doguk/Desktop/emlakuygulamasi/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5952:5)

My code in search.tsx is as follows, it is not as of yet complete:

import {useState} from 'react';
import { useRouter } from 'next/router';
import Image from 'next/image';
import {Flex, Box, Text, Icon} from '@chakra-ui/react';
import { BsFilter } from 'react-icons/bs';
import SearchFilters from '../components/SearchFilters';

const Search = () => {
    const [searchFilters, setSearchFilters] = useState(false);
    const router = useRouter();

    return (
        <Box>
            <Flex
            cursor="pointer"
            bg="gray.100"
            borderBottom="1px"
            borderColor="gray.200"
            p="2"
            fontWeight="black"
            fontSize="lg"
            justifyContent="center"
            alignItems="center"
            onClick={() => setSearchFilters((prevFilters) => !prevFilters)}
            >
        <Text>Filtrele</Text>
        <Icon paddingLeft="2" w="7" as={BsFilter}></Icon>
            </Flex>
            {searchFilters && <SearchFilters />}
        </Box>
    )
}

export default Search;

I read the Nextjs docs, and I've checked Stackoverflow for answers but none works. This should be fairly straightforward but I don't get what I am doing wrong.


问:
Adding a keybind that will split Nvim window into two with vimwiki diary
As the title says.
I want to be able to open from anywhere a split window with today's diary ready to write.
I'm pretty new to NVim so excuse my naivete.

I have written in my vimrc the following:

nnoremap <leader>nd <C>wv2<leader>w<leader>w

I want to bind <leader>nd (as in new diary) to the two actions: <C>wv (a vertical window split) followed by 2<leader>w<leader>w (accessing my 2nd wikis diary)

So when the motion is complete, I should have today's diary open split from what I am presently working on, with my cursor in the diary.

Is this even the right approach to executing something like this or do I need to do something entirely different?

I hoped it would do what I wanted it to do. But instead NVim isn't recognizing what I'm inputting at all. Only recognizing that I hit n. And thus does the last-search-action that is the default action corresponding to n in vims normal mode.


问:
Read owl file using jena
I'm still learning about JENA and I want to read an OWL file using JENA inside JAVA but I'm completely lost how to read it

I don't have any code since I don't know how to actually do it

I tried to use the Model class but I got an error after importing the Model library

Title: Read owl file using jena