问:
Laravel join sum query fetch error double sums
I got the two following tables:

table name: formulario id primary bigint(20) mes_ano varchar(255) matricula varchar(255)

table name: reparacoes id primary bigint(11) matricula varchar(255) valor varchar(255)

What I want to accomplish is joining on the valor with formulario's values and fetch the data in Laravel view dashboard. I tried the following way, but with the join it doesn't show accurate values.

```<code>public function index(Request $request, Formulario $id, Reparacoes $valor)
    {
        $data = Reparacoes::select(DB::raw("SUM(reparacoes.valor) as sum"))
        ->join('formulario', 'reparacoes.matricula', '=', 'formulario.matricula')
        ->orderBy("reparacoes.matricula")
        ->groupBy(DB::raw("reparacoes.matricula"))
        ->get();

        return view('admin.page', ['data' => $data]);
    }
 <tbody>
                        @foreach ($data as $item)
                        <tr>
                            <td>{{ $item->matricula }}</td>
                            <td>{{ $item->sum }}</td>
                            <td>{{ $item->mes_ano }}</td>
                        </tr>
                        @endforeach
                    </tbody>
</code>```

I don't even put on the select the mes_ano because the sum it's not working I got two repairs on one matricula that summing up gives 30 in value, and the other matricula that have reparacao has just one of 10 when I apply the join in controller, it shows up as the first matricula having a sum of 420. Thanks for whoever helps me doing this join query sum.

Body:
I got the two following tables:

table name: formulario id primary bigint(20) mes_ano varchar(255) matricula varchar(255)

table name: reparacoes id primary bigint(11) matricula varchar(255) valor varchar(255)

What I want to accomplish is joining on the valor with formulario's values and fetch the data in Laravel view dashboard. I tried the following way, but with the join it doesn't show accurate values.

public function index(Request $request, Formulario $id, Reparacoes $valor)
    {
        $data = Reparacoes::select(DB::raw("SUM(reparacoes.valor) as sum"))
        ->join('formulario', 'reparacoes.matricula', '=', 'formulario.matricula')
        ->orderBy("reparacoes.matricula")
        ->groupBy(DB::raw("reparacoes.matricula"))
        ->get();

        return view('admin.page', ['data' => $data]);
    }

                        @foreach ($data as $item)

                            {{ $item->matricula }}
                            {{ $item->sum }}
                            {{ $item->mes_ano }}

                        @endforeach

I don't even put on the select the mes_ano because the sum it's not working I got two repairs on one matricula that summing up gives 30 in value, and the other matricula that have reparacao has just one of 10 when I apply the join in controller, it shows up as the first matricula having a sum of 420. Thanks for whoever helps me doing this join query sum.


来源: stackexchange

问:
Is there any way to display exact address from google map place api?
I got vicinity(address) from google map api in flutter but this vicinity contains extra keywords including number,operator etc(like QCPM+777, XYZ). All, i want to display only exact address (XYZ) without any numbers or operators. How can i do that?

I try to replace extra keywords with empty string "" using replaceAll method but it can't work properly.

ContentLicense: CC BY-SA 4.0


问:
how to hide the leaflet tooltip (visibility already depending on zoom level) when activating a layer?
I am interested in showing the tooltip only for a specific zoom range (>=12) at any time. With the help of this other article I could manage to almost get there but I still have the problem that the tooltip come to appear when I activate the layer in my OverlayMaps-menu, disregarding the current zoom level.

In my leaflet map I have implemented a OverlayMaps-menu, in which almost all layers are deactivated from the start. For one of these deactivated layers, my aim is to show the tooltips for all features only from a zoom level of 12 or bigger. The code is as follows:

Declaration of the variable from a geoJSON object:

```<code>var vibro_offshore = L.geoJson (vbc_offshore, {
  pointToLayer: function (feature, latlng) {
    return new L.Circle (latlng, {
    color:'#a13c02',
    })
  },
  onEachFeature: enCadaVBC
});
</code>```

In the onEachFeature function, beside some other code regarding popup, I also have defined the tooltips:

```<code>function enCadaVBC (feature, layer) {
    //declaramos un tooltip
    var tooltip = L.tooltip({
        content: feature.properties.Location,
        permanent: true,
        direction:'right',
        className:'tooltip'
    });
    //introducimos un tooltip
    layer.bindTooltip(tooltip);
</code>```

Finally, I have managed to govern the visibility of the tooltips depending on the zoom level with the code suggested in the article referred above:

```<code>var lastZoom;
map.on('zoomend', function() {
    var zoom = map.getZoom();
    console.log(zoom);
    if (zoom < 12 && (!lastZoom || lastZoom >= 12)) {
        map.eachLayer(function(l) {
            if (l.getTooltip) {
                var toolTip = l.getTooltip();
                if (toolTip) {
                    this.map.closeTooltip(toolTip);
                }
            }
        });
    } else if (zoom >= 12 && (!lastZoom || lastZoom < 12)) {
        map.eachLayer(function(l) {
            if (l.getTooltip) {
                var toolTip = l.getTooltip();
                if (toolTip) {
                    console.log(toolTip);
                    this.map.addLayer(toolTip);
                }
            }
        });
    }
    lastZoom = zoom;
})
</code>```

All this works pretty good, but when I activate the layer via mouseclick on the OverlayMaps-menu, lets say when the zoom level is 9, all the tooltips suddenly appear. I want to avoid this.

I have tried to add a closeTooltip() command right after the bindTooltip-command, but this hasnt have any effect. A consol.log for Is Tooltipopen leads to an undefined...(?)

I also tried to relocate the layer.bindTooltip command into the if-loop, but here I do get some other error related to Mercator projection and latlng, which I do not really understand...

Body:
I am interested in showing the tooltip only for a specific zoom range (>=12) at any time. With the help of this other article I could manage to almost get there but I still have the problem that the tooltip come to appear when I activate the layer in my OverlayMaps-menu, disregarding the current zoom level.

In my leaflet map I have implemented a OverlayMaps-menu, in which almost all layers are deactivated from the start. For one of these deactivated layers, my aim is to show the tooltips for all features only from a zoom level of 12 or bigger. The code is as follows:

Declaration of the variable from a geoJSON object:

var vibro_offshore = L.geoJson (vbc_offshore, {
  pointToLayer: function (feature, latlng) {
    return new L.Circle (latlng, {
    color:'#a13c02',
    })
  },
  onEachFeature: enCadaVBC
});

In the onEachFeature function, beside some other code regarding popup, I also have defined the tooltips:

function enCadaVBC (feature, layer) {
    //declaramos un tooltip
    var tooltip = L.tooltip({
        content: feature.properties.Location,
        permanent: true,
        direction:'right',
        className:'tooltip'
    });
    //introducimos un tooltip
    layer.bindTooltip(tooltip);

Finally, I have managed to govern the visibility of the tooltips depending on the zoom level with the code suggested in the article referred above:

var lastZoom;
map.on('zoomend', function() {
    var zoom = map.getZoom();
    console.log(zoom);
    if (zoom < 12 && (!lastZoom || lastZoom >= 12)) {
        map.eachLayer(function(l) {
            if (l.getTooltip) {
                var toolTip = l.getTooltip();
                if (toolTip) {
                    this.map.closeTooltip(toolTip);
                }
            }
        });
    } else if (zoom >= 12 && (!lastZoom || lastZoom < 12)) {
        map.eachLayer(function(l) {
            if (l.getTooltip) {
                var toolTip = l.getTooltip();
                if (toolTip) {
                    console.log(toolTip);
                    this.map.addLayer(toolTip);
                }
            }
        });
    }
    lastZoom = zoom;
})

All this works pretty good, but when I activate the layer via mouseclick on the OverlayMaps-menu, lets say when the zoom level is 9, all the tooltips suddenly appear. I want to avoid this.

I have tried to add a closeTooltip() command right after the bindTooltip-command, but this hasnt have any effect. A consol.log for Is Tooltipopen leads to an undefined...(?)

I also tried to relocate the layer.bindTooltip command into the if-loop, but here I do get some other error related to Mercator projection and latlng, which I do not really understand...


问:
Why I am getting Replace "com.apple.springboard" when I want to run widget extension schema?
Usually, to debug a share extension, I will run the schema as share extension, so that I can get all the print message in XCode console.

If I run the schema as main app, I will not able to get any output from share extension.

This is how it looks like, when I am debugging my share extension.

Now, I want to debug my widget extension.

I try the run schema as widget extension.

However, I am getting

```<code>Replace "com.apple.springboard"
</code>```

message. When I click Replace and run, I am not getting any print output from widget extension.

May I know, how can I debug my widget extension properly? Thanks.

Body:
Usually, to debug a share extension, I will run the schema as share extension, so that I can get all the print message in XCode console.

If I run the schema as main app, I will not able to get any output from share extension.

This is how it looks like, when I am debugging my share extension.

Now, I want to debug my widget extension.

I try the run schema as widget extension.

However, I am getting

Replace "com.apple.springboard"

message. When I click Replace and run, I am not getting any print output from widget extension.

May I know, how can I debug my widget extension properly? Thanks.


问:
CASE WHEN with aggregate functions
I can't understand the purpose of the query using conditional function :"CASE WHEN with aggregate functions"..

1. what is the purpose of the aggregate function in this causes ?

2. what is the difference between putting the aggregate function inside the sentence for example: case when max()..

compared to max(case when...)

Below: find the columns include null values in the table that the rows known.

```<code>SELECT *
FROM (
   SELECT (CASE WHEN MAX(customer_id) IS NULL THEN 'customer_id' ELSE NULL  END ) AS 'Name' FROM customers
   UNION ALL
   SELECT (CASE WHEN MAX(customer_name) IS NULL THEN 'customer_name' ELSE NULL  END ) FROM customers
   UNION ALL
   SELECT (CASE WHEN MAX(customer_address) IS NULL THEN 'customer_address' ELSE NULL  END ) FROM customers
   UNION ALL
   SELECT (CASE WHEN MAX(customer_age) IS NULL THEN 'customer_age' ELSE NULL  END ) FROM customers
   ) tbl
WHERE tbl.Name IS NOT NULL
</code>```

Title: CASE WHEN with aggregate functions

Body:
I can't understand the purpose of the query using conditional function :"CASE WHEN with aggregate functions"..

1. what is the purpose of the aggregate function in this causes ?

2. what is the difference between putting the aggregate function inside the sentence for example: case when max()..

compared to max(case when...)

Below: find the columns include null values in the table that the rows known.

SELECT *
FROM (
   SELECT (CASE WHEN MAX(customer_id) IS NULL THEN 'customer_id' ELSE NULL  END ) AS 'Name' FROM customers
   UNION ALL
   SELECT (CASE WHEN MAX(customer_name) IS NULL THEN 'customer_name' ELSE NULL  END ) FROM customers
   UNION ALL
   SELECT (CASE WHEN MAX(customer_address) IS NULL THEN 'customer_address' ELSE NULL  END ) FROM customers
   UNION ALL
   SELECT (CASE WHEN MAX(customer_age) IS NULL THEN 'customer_age' ELSE NULL  END ) FROM customers
   ) tbl
WHERE tbl.Name IS NOT NULL


问:
Python Regex applying split to a capturing group
I'm trying to get create statement from ctas statement by adding limit 0 to all tables as I don't want to load the table. Using python for the same

Input :

```<code>create table new_table as select
mytable.column1, mytable2.column2
from schema.mytable  left join mytable2 ;
</code>```

Expected Output:

```<code>create table new_table IF NOT EXISTS  as select
mytable.column1, mytable2.column2
from  (select * from mytable limit 0) mytable   join  (select * from mytable2 limit 0) mytable2
</code>```

I have to replace all the tables in from and join clause to (select * from tablename limit 0) and alias.

However I'm only able to generate below, not able to get the table name and add it as alias. Also not able to change the last name in the join clause. If the input has alias explicitly mentioned, I'm able to generate it. I'm very new to using regex and feel very overwhelmed. Appreciate support from the experts here.

Output obtained:

```<code>create table new_table as select
mytable.column1, mytable2.column2
from  (select * from schema.mytable limit 0)   join mytable2 ;
</code>```

Code I tried: (First tried to capture if there's already alias and put it in capture group 4. I would like to generate alias when tables do not have alias explicitly mentioned. Capture group 2 would get the schema_name.table_name. If I can use python function split to the capturing group. Also the last table in the sql I'm not able to translate

```<code>import re
sql = """
        create table new_table as select
        mytable.column1, mytable2.column2
        from schema.mytable  left join mytable2 ;"""
 rgxsubtable = re.compile(r"\b((?:from|join)\s+)([\w.\"]+)([\)\s]+)(\bleft|on|cross|join|inner\b)",re.MULTILINE|re.IGNORECASE) # look for table names in from and join clauses
rgxalias = re.compile(r"\b((?:from|join)\s+)([\w.\"]+)(\s+)(\b(?!left|on|cross|join|inner\b)\w+)",re.MULTILINE|re.IGNORECASE) # look for table names in from and join clauses but with aliases
sql = rgxalias.sub(r"\1 (select * from \2 limit 0) \4 ", sql)
sql = rgxsubtable.sub(r"\1 (select * from \2 limit 0)  ", sql)
</code>```

Body:
I'm trying to get create statement from ctas statement by adding limit 0 to all tables as I don't want to load the table. Using python for the same

Input :

create table new_table as select
mytable.column1, mytable2.column2
from schema.mytable  left join mytable2 ;

Expected Output:

create table new_table IF NOT EXISTS  as select
mytable.column1, mytable2.column2
from  (select * from mytable limit 0) mytable   join  (select * from mytable2 limit 0) mytable2

I have to replace all the tables in from and join clause to (select * from tablename limit 0) and alias.

However I'm only able to generate below, not able to get the table name and add it as alias. Also not able to change the last name in the join clause. If the input has alias explicitly mentioned, I'm able to generate it. I'm very new to using regex and feel very overwhelmed. Appreciate support from the experts here.

Output obtained:

create table new_table as select
mytable.column1, mytable2.column2
from  (select * from schema.mytable limit 0)   join mytable2 ;

Code I tried: (First tried to capture if there's already alias and put it in capture group 4. I would like to generate alias when tables do not have alias explicitly mentioned. Capture group 2 would get the schema_name.table_name. If I can use python function split to the capturing group. Also the last table in the sql I'm not able to translate

import re
sql = """
        create table new_table as select
        mytable.column1, mytable2.column2
        from schema.mytable  left join mytable2 ;"""
 rgxsubtable = re.compile(r"\b((?:from|join)\s+)([\w.\"]+)([\)\s]+)(\bleft|on|cross|join|inner\b)",re.MULTILINE|re.IGNORECASE) # look for table names in from and join clauses
rgxalias = re.compile(r"\b((?:from|join)\s+)([\w.\"]+)(\s+)(\b(?!left|on|cross|join|inner\b)\w+)",re.MULTILINE|re.IGNORECASE) # look for table names in from and join clauses but with aliases
sql = rgxalias.sub(r"\1 (select * from \2 limit 0) \4 ", sql)
sql = rgxsubtable.sub(r"\1 (select * from \2 limit 0)  ", sql)


问:
::after and ::before it appears on chrome but not on mozilla
I have a problem with a personal project that generates passwords. On an input range I put two elements above that contain with the minimum and maximum characters that can be selected in ::after and ::before, the problem is that they appear on chrome and not on mozilla. What would be the cause?

Here is the HTML code:

```<code><input id="characterAmount" type="range" value="16" min="6" max="26" name="nrcharacters">
</code>```

CSS:

```<code>input[type=range]::before {
    content: attr(min);
    position: absolute;
    width: 10px;
    height: 10px;
    top: -18px;
    left: 0;
    color: var(--password-hover);
}

input[type=range]::after {
    content: attr(max);
    position: absolute;
    width: 10px;
    height: 10px;
    top: -18px;
    right: 5px;
    color: var(--password-hover);
}
</code>```

it should to show like that

this is the demo

i tried with

```<code>input[type=range]::-moz-range-track::before
///
input[type=range]::-moz-range-progress::before
</code>```

Body:
I have a problem with a personal project that generates passwords. On an input range I put two elements above that contain with the minimum and maximum characters that can be selected in ::after and ::before, the problem is that they appear on chrome and not on mozilla. What would be the cause?

Here is the HTML code:

<input id="characterAmount" type="range" value="16" min="6" max="26" name="nrcharacters">

CSS:

input[type=range]::before {
    content: attr(min);
    position: absolute;
    width: 10px;
    height: 10px;
    top: -18px;
    left: 0;
    color: var(--password-hover);
}

input[type=range]::after {
    content: attr(max);
    position: absolute;
    width: 10px;
    height: 10px;
    top: -18px;
    right: 5px;
    color: var(--password-hover);
}

it should to show like that

this is the demo

i tried with

input[type=range]::-moz-range-track::before
///
input[type=range]::-moz-range-progress::before


问:
YUM/RPM: check if all the package dependencies are installed?
I need a way to check if all the package dependencies have been installed and if there are any broken packages in the system. How can this be done?

On other systems I used apt-get install --fix-broken is there an alternative for yum or rpm?


问:
ElasticSearch works although it was terminated
I start ElasticSearch localy through starting the bat file on a console window.

I can search my elastic using my app or Kibana.
Than I stop ElasticSearch through closing the console window,
but my app is still able to search at Elastic.
Also when I call https://localhost:9200/ I get "You Know, for Search".
I can't find ElasticSearch at my Task Manager.

How does it come that elastic works after terminating?

And how can I terminate ElasticSearch properly?


问:
Got error in react app You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports
This is my code:

```<code>import * as Unicons from '@iconscout/react-unicons';
interface Props {
  icon: string;
  color?: string;
  size?: string;
}
export const UniconsCustom = ({ icon, color, size }: Props) => {
  const SelectedIcon = Unicons[icon];
  return <SelectedIcon size={size || '20'} color={color} />;
};
</code>```

When I comment this line const SelectedIcon = Unicons[icon]; and send an empty fragment on return, it works but doesn't render the icons. Please help.

I'm expecting to render the icon dynamically.

Body:
This is my code:

import * as Unicons from '@iconscout/react-unicons';
interface Props {
  icon: string;
  color?: string;
  size?: string;
}
export const UniconsCustom = ({ icon, color, size }: Props) => {
  const SelectedIcon = Unicons[icon];
  return <SelectedIcon size={size || '20'} color={color} />;
};

When I comment this line const SelectedIcon = Unicons[icon]; and send an empty fragment on return, it works but doesn't render the icons. Please help.

I'm expecting to render the icon dynamically.


问:
A theme dark/light toggle not loading desired state
I am using local storage and when ever its in light mode it works fine, switches to dark mode and all is good, but it wont switch out, it will show the local variable color_mode as light, but it loads dark, which doesn't make any sense, and when I check local storage, it shows dark.

It should just switch in between the two modes and save the switched to mode after. I don't know if its anything obvious or a problem with my browser.

var head;
var link;
var color_mode = "light";

function load() {
    const color_mode_stored = localStorage.getItem("color_mode");
    if (color_mode_stored != undefined)
        color_mode = color_mode_stored;
    else
        color_mode = "light";
    draw();
}

function draw () {
    head = document.getElementsByName("head")[0];
    link = document.createElement("link");

    link.rel = "stylesheet";
    link.type = "text/css";

    switch (color_mode){
        case 'dark':
            link.href = "dark_mode.css";
            break;
        case 'light':
            link.href = "light_mode.css";
            break;
    }

    head.appendChild(link);
}

function color_change () {

    if (color_mode == 'light'){
        color_mode = 'dark';
    }
    else {
        color_mode = 'light';
    }
    localStorage.setItem("color_mode", color_mode);

    console.log("yay", color_mode);

    document.location.reload();

}

load();
```


问:
Issue seeding model.ts to mongoose
so i'm connected to my mongodb atlas. i'm trying to seed data into my db.
the errors that i'm getting when i run npm run seed is:

import connectDB from "../config/config"; ^^^^^^ SyntaxError: Cannot use import statement outside a module

and this is my seeder.ts code snippet:

```<code>import connectDB from "../config/config";
import { JobModel } from "../models/model";

const loremIpsum = require("lorem-ipsum").loremIpsum;
const jobTitle = ["Frontend Developer", "Backend Developer"];
const salary = [2000, 3500, 4000, 4500, 5000];
const technologies = [
  "React",
  "Vue.js",
  "Angular",
  "JavaScript",
  "Python",
  "Java",
  "TypeScript",
  "MongoDB",
];
const NUM_OF_JOBS = 10;
const randomizeIndex = (arrLength: any) => {
  return Math.floor(Math.random() * arrLength);
};

connectDB().then(async () => {
  for (let i = 0; i < NUM_OF_JOBS; i++) {
    const newJob = await JobModel.create({
      title: jobTitle[randomizeIndex(jobTitle.length)],
      description: loremIpsum(),
      responsibilities: loremIpsum(),
      requirements: loremIpsum(),
      salary: salary[randomizeIndex(salary.length)],
      technologies: technologies[randomizeIndex(technologies.length)],
    });
    console.log("newJob", newJob);
  }
});
</code>```

i have exported my config file as such:

```<code>import mongoose from "mongoose";
mongoose.set("strictQuery", true);

// Create a new MongoClient
const connectDB: Function = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI as string);
    console.log(`db connected, ${conn.connection.host}`);
  } catch (error) {
    console.log("error in connecting to db");
    console.log(error);
    process.exit(1);
  }
};

export default connectDB;
</code>```

Any help is greatly appreciated!

i tried to switch to const/require, but i read somewhere that TypeScript prefers import/from.

Title: Issue seeding model.ts to mongoose

Body:
so i'm connected to my mongodb atlas. i'm trying to seed data into my db.
the errors that i'm getting when i run npm run seed is:

import connectDB from "../config/config"; ^^^^^^ SyntaxError: Cannot use import statement outside a module

and this is my seeder.ts code snippet:

import connectDB from "../config/config";
import { JobModel } from "../models/model";

const loremIpsum = require("lorem-ipsum").loremIpsum;
const jobTitle = ["Frontend Developer", "Backend Developer"];
const salary = [2000, 3500, 4000, 4500, 5000];
const technologies = [
  "React",
  "Vue.js",
  "Angular",
  "JavaScript",
  "Python",
  "Java",
  "TypeScript",
  "MongoDB",
];
const NUM_OF_JOBS = 10;
const randomizeIndex = (arrLength: any) => {
  return Math.floor(Math.random() * arrLength);
};

connectDB().then(async () => {
  for (let i = 0; i < NUM_OF_JOBS; i++) {
    const newJob = await JobModel.create({
      title: jobTitle[randomizeIndex(jobTitle.length)],
      description: loremIpsum(),
      responsibilities: loremIpsum(),
      requirements: loremIpsum(),
      salary: salary[randomizeIndex(salary.length)],
      technologies: technologies[randomizeIndex(technologies.length)],
    });
    console.log("newJob", newJob);
  }
});

i have exported my config file as such:

import mongoose from "mongoose";
mongoose.set("strictQuery", true);

// Create a new MongoClient
const connectDB: Function = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI as string);
    console.log(`db connected, ${conn.connection.host}`);
  } catch (error) {
    console.log("error in connecting to db");
    console.log(error);
    process.exit(1);
  }
};

export default connectDB;

Any help is greatly appreciated!

i tried to switch to const/require, but i read somewhere that TypeScript prefers import/from.


问:
Copying PST Data Locally from PST to Exchange Online Account Using PowerShell
In order to avoid having to use a 3rd party and expensive solution (i work for an Org any tech would try to do this for if they knew who - ethics wise).

The task is to copy PST's to Exchange online archives. I know there's New-MailboxImportRequest and Azcopy/some third party tools. But, due to this access being obtainable only by a select few and the online end being locked down (for good reason but not in this case) - there must be another way here.

In Outlook I can load thus said Exchange Online Account to Outlook Client for testing as would be all user accounts.

Then, Using File>Open>Import/Export I can manually link a PST and then embed it into the connected accounts Exchange Online archive.

How would i do this from a PowerShell point of view bypassing Exchange Online Cmdlets (I don't see why I'd need them in this case) The PST Data if local, and account loaded, locally, allows this data to be written to the OST file!

How can I do this from PS point of view? Just scrabbling around now - at the very least there must be a VBScript way if PS isn't capable (It's normally always capable).

Thanks in advance.


问:
Kotlin Android - Correct way to get Json objects/Array via the internet in a background thread, and display the result in a recycler view to the UI
This is my problem: Nothing (no item) shows in the UI when the app starts, or even upon swipe to refresh, but I expect the UI to show some items in a recyclerView when the app starts.

The retrieved jsonArray is not empty, and also not null.
I don't get any app crashes, or errors in my logcat when I run the app or use my app.

The funny thing is that: when i tap on the light/dark mode button on my device to switch to either dark/light mode, then my item list correctly shows in the UI of the app. However I notice the following error messages in the logcat when i tap the light/dark mode button on my device.

logcat 1
logcat 2

This is my Fragment:

```<code>class AllScoresFragment : Fragment() {

    companion object {
        var ScoreListASF : ArrayList<Score> = ArrayList()
    }

    //configure private lateinit vars
    private lateinit var binding: FragmentAllScoresBinding
    private lateinit var viewModel: AllScoresViewModel
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter : AdapterForScoreListForAllScoreFragmentForRecyclerView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentAllScoresBinding.inflate(inflater)
        return binding.root)
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        //initiate my viewModel
        viewModel = ViewModelProvider(this)[AllScoresViewModel::class.java]

        //create the observer which updates the UI
        val liveScoreObserver = Observer<ArrayList<Score>>{

            //update the UI
            ScoreListASF = it
        }

        //let the observer observe my livedata through viewModel
        viewModel.liveScores(context).observe(this.viewLifecycleOwner, liveScoreObserver)

        //configure recyclerview for layout in this Fragment
        recyclerView = binding.include.recyclerViewForScoreContent
        recyclerView.setHasFixedSize(true)
        recyclerView.setItemViewCacheSize(100)
        recyclerView.layoutManager = LinearLayoutManager(this.context)
        recyclerView.isVerticalScrollBarEnabled = true
        adapter =
            context?.let { AdapterForScoreListForAllScoreFragmentForRecyclerView(it, ScoreListASF) }!!
        recyclerView.adapter = adapter

        //configure what happens when the layout is swiped to be refreshed
        val swipeToRefresh = binding.swipeToRefresh
        binding.swipeToRefresh.setOnRefreshListener {
            viewModel.liveScores(context).observe(this.viewLifecycleOwner, liveScoreObserver)
            swipeToRefresh.isRefreshing = false
        }
    }
}
</code>```

This is the viewModel:

```<code>class AllScoresViewModel () : ViewModel() {
    private val getOnlineData: GetOnlineData = GetOnlineData()

    fun liveScores(context: Context?): LiveData<ArrayList<Score>> = liveData {
        val data = getOnlineData.retrieveScore(context)
        emit(data)
    }
}

</code>```

This is the GetOnlineData Class:

```<code>sealed class Result<out R> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}

class GetOnlineData {

    suspend fun retrieveScore(context: Context?) : ArrayList<Score> {
        val tempList = ArrayList<Score>()

        //create and show a progress dialog; hide it when the process is done
        val progressDialog = ProgressDialog(context)
        progressDialog.setMessage("Loading...")
        progressDialog.show()

        // Get a RequestQueue
        AllScoresFragment().context?.let { MySingleton.getInstance(it).requestQueue }

        //run newtwork jsonRequest on background thread to avoid ANR
        //retrieve json objects and add each object-set to the ArrayList<Score>()
        return withContext(Dispatchers.IO){

            val url = "https://..."
            val jsonArrayRequest = JsonArrayRequest(
                Request.Method.GET, url, null,
                { response ->

                    var jo : JSONObject

                    try {
                        for (i in 0 until response.length()){
                            jo = response.getJSONObject(i)
                            val id = jo.getInt("id")
                            val name:String = jo.getString("name")
                            val composer:String = jo.getString("composer")
                            val style:String = jo.getString("style")
                            val theme:String = jo.getString("theme")
                            val album:String = jo.getString("album")
                            val lang:String = jo.getString("lang")
                            val thumbnailUrl:String = jo.getString("thumbnail_url")
                            val pdfUrl: String = jo.getString("pdf_url")

                            val score = Score(
                                id = id,
                                name = name,
                                composer = composer,
                                style = style,
                                theme = theme,
                                album = album,
                                lang = lang,
                                thumbnail_url = url + thumbnailUrl,
                                pdf_url = url + pdfUrl
                            )

                            tempList.add(score)

                        }

                        //just to show/know that i get the response: all 'scores' added
                        //this toast shows up every single time, meaning that i get the response
                        Toast.makeText(context,
                            "success getting scores: $tempList",
                            Toast.LENGTH_LONG).show()

                        Result.Success("success getting scores: $tempList")

                        //hide the progress dialog upon getting response
                        progressDialog.hide()

                    } catch (e : JSONException){
                        Toast.makeText(context, e.message, Toast.LENGTH_LONG).show()
                        Result.Error(e)

                        //hide the progress dialog upon getting error
                        progressDialog.hide()
                    }

                },
                { error ->
                    Toast.makeText(context,
                        error.message,
                        Toast.LENGTH_SHORT)
                        .show()
                    Result.Error(error)
                    progressDialog.hide()
                }
            )

            // Access the RequestQueue through my singleton class.
            context?.let { MySingleton.getInstance(it).addToRequestQueue(jsonArrayRequest) }

            return@withContext tempList
        }
    }
}
</code>```

What is happening? What am I doing wrong?

This is what I want to do:

Get jsonArray from an https source in a background thread.

Add all retrieved jsonObjects to an ArrayList.

Show this ArrayList to the UI using RecyclerView when my app starts or when i swipe to refresh.

Please help me out here. What am I doing wrong?
I will be really grateful to get a solution

EDITS SO FAR:

My edited fragment to accommodate for DiffUtil :

```<code>override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        viewModel = ViewModelProvider(this)[AllScoresViewModel::class.java]

        ScoreListASF = ArrayList()

        //create the observer which updates the UI
        val liveScoreObserver = Observer<ArrayList<Score>>{ scoreArrayList ->

            //oldList
            ScoreListASF = ArrayList()

            //get the new list from the observer and call the adapter.insert()
            // for DiffUtil to do its thing
            val newList = scoreArrayList

            adapter.insertItem(newList)

            //tried using notifyDataSetChanged(), did not work
            //adapter.notifyDataSetChanged()

        }

        //observe the livedata
        viewModel.liveScores(context).observe(this.viewLifecycleOwner, liveScoreObserver)

        //configure recyclerview for layout in SongFragment
        recyclerView = binding.include.recyclerViewForScoreContent
        recyclerView.setHasFixedSize(true)
        recyclerView.setItemViewCacheSize(100)
        recyclerView.layoutManager = LinearLayoutManager(this.context)
        recyclerView.isVerticalScrollBarEnabled = true

        adapter =
            context?.let { AdapterForScoreListForAllScoreFragmentForRecyclerView(it, ScoreListASF) }!!
        recyclerView.adapter = adapter

        //what happens when swipe to refresh is initiated
        val swipeToRefresh = binding.swipeToRefresh
        binding.swipeToRefresh.setOnRefreshListener {
            viewModel.liveScores(context).observe(this.viewLifecycleOwner, liveScoreObserver)
            swipeToRefresh.isRefreshing = false
        }
    }
</code>```

This is the Adapter for the recyclerView:

```<code>class AdapterForScoreListForAllScoreFragmentForRecyclerView(
    private val context: Context,
    private val scoreList: ArrayList<Score>
) : RecyclerView.Adapter<AdapterForScoreListForAllScoreFragmentForRecyclerView.ViewHolder>() {
    class ViewHolder(binding: ScoreListForRecycleBinding) : RecyclerView.ViewHolder(binding.root){
        val pdfThumbnailImage = binding.thumbnailForScore
        val songTitle = binding.scoreTitleNameOfAllScoresFragment
        val composerName = binding.nameOfComposerForAllScoresFragment
        val genre = binding.styleForAllScoresFragment

        //val for root
        val root = binding.root

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
    : ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val scoreList = ScoreListForRecycleBinding.inflate(layoutInflater, parent, false)
        return ViewHolder(scoreList)
    }

    override fun getItemCount(): Int {
        return scoreList.size
    }

    //the function to insert the new list to let DiffUtil do its thing
    fun insertItem(newItemList: ArrayList<Score>){

        //should i clear the list before adding newList?
        //scoreList.clear()

        val diffUtil = MyDiffUtil(scoreList, newItemList)
        val diffResult : DiffUtil.DiffResult = DiffUtil.calculateDiff(diffUtil)

        scoreList.addAll(newItemList)
        diffResult.dispatchUpdatesTo(this)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        val scoreName = scoreList[position].name
        val scoreComposer = scoreList[position].composer
        val genre = scoreList[position].style
        val pdfUrl = scoreList[position].pdf_url
        val thumbnailImage = scoreList[position].thumbnail_url

        holder.songTitle.text = scoreName
        holder.composerName.text = scoreComposer
        holder.genre.text = genre
        Glide
            .with(holder.pdfThumbnailImage)
            .load(thumbnailImage)
            .placeholder(R.drawable.scoremus_icon_slash)
            .into(holder.pdfThumbnailImage)

        holder.root.setOnClickListener {
            holder.root.isLongClickable = true
            Toast.makeText(
                context,
                "opening \"${scoreName.uppercase()} composed by $scoreComposer\"...",
                Toast.LENGTH_SHORT)
                .show()

            val intent = Intent(context, PdfActivity::class.java)
            intent.putExtra("index", position)
            intent.putExtra("pdfPath", scoreList[position].pdf_url)
            ContextCompat.startActivity(context, intent, null)
        }
    }

}
</code>```

This is the DiffUtil Class:

```<code>class MyDiffUtil(
    private val oldListYeah : ArrayList<Score>,
    private val newListYeah : ArrayList<Score>
) : DiffUtil.Callback() {
    override fun getOldListSize(): Int {
        return oldListYeah.size
    }

    override fun getNewListSize(): Int {
        return newListYeah.size
    }

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldItemPosition == newItemPosition
    }

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldListYeah[oldItemPosition] == newListYeah[newItemPosition]
    }
}
</code>```

Body:
This is my problem: Nothing (no item) shows in the UI when the app starts, or even upon swipe to refresh, but I expect the UI to show some items in a recyclerView when the app starts.

The retrieved jsonArray is not empty, and also not null.
I don't get any app crashes, or errors in my logcat when I run the app or use my app.

The funny thing is that: when i tap on the light/dark mode button on my device to switch to either dark/light mode, then my item list correctly shows in the UI of the app. However I notice the following error messages in the logcat when i tap the light/dark mode button on my device.

logcat 1
logcat 2

This is my Fragment:

class AllScoresFragment : Fragment() {

    companion object {
        var ScoreListASF : ArrayList<Score> = ArrayList()
    }

    //configure private lateinit vars
    private lateinit var binding: FragmentAllScoresBinding
    private lateinit var viewModel: AllScoresViewModel
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter : AdapterForScoreListForAllScoreFragmentForRecyclerView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentAllScoresBinding.inflate(inflater)
        return binding.root)
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        //initiate my viewModel
        viewModel = ViewModelProvider(this)[AllScoresViewModel::class.java]

        //create the observer which updates the UI
        val liveScoreObserver = Observer<ArrayList<Score>>{

            //update the UI
            ScoreListASF = it
        }

        //let the observer observe my livedata through viewModel
        viewModel.liveScores(context).observe(this.viewLifecycleOwner, liveScoreObserver)

        //configure recyclerview for layout in this Fragment
        recyclerView = binding.include.recyclerViewForScoreContent
        recyclerView.setHasFixedSize(true)
        recyclerView.setItemViewCacheSize(100)
        recyclerView.layoutManager = LinearLayoutManager(this.context)
        recyclerView.isVerticalScrollBarEnabled = true
        adapter =
            context?.let { AdapterForScoreListForAllScoreFragmentForRecyclerView(it, ScoreListASF) }!!
        recyclerView.adapter = adapter

        //configure what happens when the layout is swiped to be refreshed
        val swipeToRefresh = binding.swipeToRefresh
        binding.swipeToRefresh.setOnRefreshListener {
            viewModel.liveScores(context).observe(this.viewLifecycleOwner, liveScoreObserver)
            swipeToRefresh.isRefreshing = false
        }
    }
}

This is the viewModel:

class AllScoresViewModel () : ViewModel() {
    private val getOnlineData: GetOnlineData = GetOnlineData()

    fun liveScores(context: Context?): LiveData<ArrayList<Score>> = liveData {
        val data = getOnlineData.retrieveScore(context)
        emit(data)
    }
}

This is the GetOnlineData Class:

sealed class Result<out R> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}

class GetOnlineData {

    suspend fun retrieveScore(context: Context?) : ArrayList<Score> {
        val tempList = ArrayList<Score>()

        //create and show a progress dialog; hide it when the process is done
        val progressDialog = ProgressDialog(context)
        progressDialog.setMessage("Loading...")
        progressDialog.show()

        // Get a RequestQueue
        AllScoresFragment().context?.let { MySingleton.getInstance(it).requestQueue }

        //run newtwork jsonRequest on background thread to avoid ANR
        //retrieve json objects and add each object-set to the ArrayList<Score>()
        return withContext(Dispatchers.IO){

            val url = "https://..."
            val jsonArrayRequest = JsonArrayRequest(
                Request.Method.GET, url, null,
                { response ->

                    var jo : JSONObject

                    try {
                        for (i in 0 until response.length()){
                            jo = response.getJSONObject(i)
                            val id = jo.getInt("id")
                            val name:String = jo.getString("name")
                            val composer:String = jo.getString("composer")
                            val style:String = jo.getString("style")
                            val theme:String = jo.getString("theme")
                            val album:String = jo.getString("album")
                            val lang:String = jo.getString("lang")
                            val thumbnailUrl:String = jo.getString("thumbnail_url")
                            val pdfUrl: String = jo.getString("pdf_url")

                            val score = Score(
                                id = id,
                                name = name,
                                composer = composer,
                                style = style,
                                theme = theme,
                                album = album,
                                lang = lang,
                                thumbnail_url = url + thumbnailUrl,
                                pdf_url = url + pdfUrl
                            )

                            tempList.add(score)

                        }

                        //just to show/know that i get the response: all 'scores' added
                        //this toast shows up every single time, meaning that i get the response
                        Toast.makeText(context,
                            "success getting scores: $tempList",
                            Toast.LENGTH_LONG).show()

                        Result.Success("success getting scores: $tempList")

                        //hide the progress dialog upon getting response
                        progressDialog.hide()

                    } catch (e : JSONException){
                        Toast.makeText(context, e.message, Toast.LENGTH_LONG).show()
                        Result.Error(e)

                        //hide the progress dialog upon getting error
                        progressDialog.hide()
                    }

                },
                { error ->
                    Toast.makeText(context,
                        error.message,
                        Toast.LENGTH_SHORT)
                        .show()
                    Result.Error(error)
                    progressDialog.hide()
                }
            )

            // Access the RequestQueue through my singleton class.
            context?.let { MySingleton.getInstance(it).addToRequestQueue(jsonArrayRequest) }

            return@withContext tempList
        }
    }
}

What is happening? What am I doing wrong?

This is what I want to do:

Get jsonArray from an https source in a background thread.

Add all retrieved jsonObjects to an ArrayList.

Show this ArrayList to the UI using RecyclerView when my app starts or when i swipe to refresh.

Please help me out here. What am I doing wrong?
I will be really grateful to get a solution

EDITS SO FAR:

My edited fragment to accommodate for DiffUtil :

override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        viewModel = ViewModelProvider(this)[AllScoresViewModel::class.java]

        ScoreListASF = ArrayList()

        //create the observer which updates the UI
        val liveScoreObserver = Observer<ArrayList<Score>>{ scoreArrayList ->

            //oldList
            ScoreListASF = ArrayList()

            //get the new list from the observer and call the adapter.insert()
            // for DiffUtil to do its thing
            val newList = scoreArrayList

            adapter.insertItem(newList)

            //tried using notifyDataSetChanged(), did not work
            //adapter.notifyDataSetChanged()

        }

        //observe the livedata
        viewModel.liveScores(context).observe(this.viewLifecycleOwner, liveScoreObserver)

        //configure recyclerview for layout in SongFragment
        recyclerView = binding.include.recyclerViewForScoreContent
        recyclerView.setHasFixedSize(true)
        recyclerView.setItemViewCacheSize(100)
        recyclerView.layoutManager = LinearLayoutManager(this.context)
        recyclerView.isVerticalScrollBarEnabled = true

        adapter =
            context?.let { AdapterForScoreListForAllScoreFragmentForRecyclerView(it, ScoreListASF) }!!
        recyclerView.adapter = adapter

        //what happens when swipe to refresh is initiated
        val swipeToRefresh = binding.swipeToRefresh
        binding.swipeToRefresh.setOnRefreshListener {
            viewModel.liveScores(context).observe(this.viewLifecycleOwner, liveScoreObserver)
            swipeToRefresh.isRefreshing = false
        }
    }

This is the Adapter for the recyclerView:

class AdapterForScoreListForAllScoreFragmentForRecyclerView(
    private val context: Context,
    private val scoreList: ArrayList<Score>
) : RecyclerView.Adapter<AdapterForScoreListForAllScoreFragmentForRecyclerView.ViewHolder>() {
    class ViewHolder(binding: ScoreListForRecycleBinding) : RecyclerView.ViewHolder(binding.root){
        val pdfThumbnailImage = binding.thumbnailForScore
        val songTitle = binding.scoreTitleNameOfAllScoresFragment
        val composerName = binding.nameOfComposerForAllScoresFragment
        val genre = binding.styleForAllScoresFragment

        //val for root
        val root = binding.root

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
    : ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val scoreList = ScoreListForRecycleBinding.inflate(layoutInflater, parent, false)
        return ViewHolder(scoreList)
    }

    override fun getItemCount(): Int {
        return scoreList.size
    }

    //the function to insert the new list to let DiffUtil do its thing
    fun insertItem(newItemList: ArrayList<Score>){

        //should i clear the list before adding newList?
        //scoreList.clear()

        val diffUtil = MyDiffUtil(scoreList, newItemList)
        val diffResult : DiffUtil.DiffResult = DiffUtil.calculateDiff(diffUtil)

        scoreList.addAll(newItemList)
        diffResult.dispatchUpdatesTo(this)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        val scoreName = scoreList[position].name
        val scoreComposer = scoreList[position].composer
        val genre = scoreList[position].style
        val pdfUrl = scoreList[position].pdf_url
        val thumbnailImage = scoreList[position].thumbnail_url

        holder.songTitle.text = scoreName
        holder.composerName.text = scoreComposer
        holder.genre.text = genre
        Glide
            .with(holder.pdfThumbnailImage)
            .load(thumbnailImage)
            .placeholder(R.drawable.scoremus_icon_slash)
            .into(holder.pdfThumbnailImage)

        holder.root.setOnClickListener {
            holder.root.isLongClickable = true
            Toast.makeText(
                context,
                "opening \"${scoreName.uppercase()} composed by $scoreComposer\"...",
                Toast.LENGTH_SHORT)
                .show()

            val intent = Intent(context, PdfActivity::class.java)
            intent.putExtra("index", position)
            intent.putExtra("pdfPath", scoreList[position].pdf_url)
            ContextCompat.startActivity(context, intent, null)
        }
    }

}

This is the DiffUtil Class:

class MyDiffUtil(
    private val oldListYeah : ArrayList<Score>,
    private val newListYeah : ArrayList<Score>
) : DiffUtil.Callback() {
    override fun getOldListSize(): Int {
        return oldListYeah.size
    }

    override fun getNewListSize(): Int {
        return newListYeah.size
    }

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldItemPosition == newItemPosition
    }

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldListYeah[oldItemPosition] == newListYeah[newItemPosition]
    }
}


问:
didFocus is not executing while navigating between native pages
I have one application in react native, also i have some pages en native code. I am trying to use didFocus to execute one code. it works well when i navigate between in react Native pages, but when i navigate to one native page in android and return the original page, it is not detecting the did focus

Code in react native

```<code>import React, {Component} from 'react';
import {
    Alert,
    Button,
    NativeModules,
    SafeAreaView, StyleSheet,
    Text,
    View,
} from 'react-native';

const {SdkBridge} = NativeModules;

class Login extends Component<{
    navigation: any;
}, any> {
    view: View | null | undefined;
    focusListener: any| null | undefined;
    constructor(props: any) {
        super(props);
        this.state = {
        };
    }

    componentDidMount() {
        const { navigation } = this.props;
        this.focusListener = navigation.addListener("didFocus", () => {
            Alert.alert('Codigo a ser llamado');
        });
    }

    componentWillUnmount() {
        // Remove the event listener
        this.focusListener.remove();
    }

    render() {
        let {
        } = this.state;
        return (
            <SafeAreaView style={styles.container}>
                <View>
                    <Text style={styles.title}>
                        The title and onPress handler are required. It is recommended to set accessibilityLabel to help make your app usable by everyone.
                    </Text>
<Button
                        title="Native code "
                        onPress={() => SdkBridge.redirectToNative('register', 'https://www.google.com')}
                    />
                    </View>
                <View>
                    <Text style={styles.title}>
                        Adjust the color in a way that looks standard on each platform. On  iOS, the color prop controls the color of the text. On Android, the color adjusts the background color of the button.
                    </Text>
                    <Button
                        title="Navigation in react native"
                        color="#f194ff"
                        onPress={() => this.props.navigation.navigate('ScreenWebViewComponent', {
                url: 'https://www.google.com',
            });}
                    />
                </View>
                <View>
                    <Text style={styles.title}>
                        All interaction for the component are disabled.
                    </Text>
                    <Button
                        title="Press me"
                        disabled
                        onPress={() => Alert.alert('Cannot press this one')}
                    />
                </View>
                <View>
                    <Text style={styles.title}>
                        This layout strategy lets the title define the width of the button.
                    </Text>
                    <View style={styles.fixToText}>
                        <Button
                            title="Left button"
                            onPress={() => Alert.alert('Left button pressed')}
                        />
                        <Button
                            title="Right button"
                            onPress={() => Alert.alert('Right button pressed')}
                        />
                    </View>
                </View>
            </SafeAreaView>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        marginHorizontal: 16,
    },
    title: {
        textAlign: 'center',
        marginVertical: 8,
    },
    fixToText: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    separator: {
        marginVertical: 8,
        borderBottomColor: '#737373',
        borderBottomWidth: StyleSheet.hairlineWidth,
    },
});
export default Login;
</code>```

Body:
I have one application in react native, also i have some pages en native code. I am trying to use didFocus to execute one code. it works well when i navigate between in react Native pages, but when i navigate to one native page in android and return the original page, it is not detecting the did focus

Code in react native

import React, {Component} from 'react';
import {
    Alert,
    Button,
    NativeModules,
    SafeAreaView, StyleSheet,
    Text,
    View,
} from 'react-native';

const {SdkBridge} = NativeModules;

class Login extends Component<{
    navigation: any;
}, any> {
    view: View | null | undefined;
    focusListener: any| null | undefined;
    constructor(props: any) {
        super(props);
        this.state = {
        };
    }

    componentDidMount() {
        const { navigation } = this.props;
        this.focusListener = navigation.addListener("didFocus", () => {
            Alert.alert('Codigo a ser llamado');
        });
    }

    componentWillUnmount() {
        // Remove the event listener
        this.focusListener.remove();
    }

    render() {
        let {
        } = this.state;
        return (
            <SafeAreaView style={styles.container}>
                <View>
                    <Text style={styles.title}>
                        The title and onPress handler are required. It is recommended to set accessibilityLabel to help make your app usable by everyone.
                    </Text>
<Button
                        title="Native code "
                        onPress={() => SdkBridge.redirectToNative('register', 'https://www.google.com')}
                    />
                    </View>
                <View>
                    <Text style={styles.title}>
                        Adjust the color in a way that looks standard on each platform. On  iOS, the color prop controls the color of the text. On Android, the color adjusts the background color of the button.
                    </Text>
                    <Button
                        title="Navigation in react native"
                        color="#f194ff"
                        onPress={() => this.props.navigation.navigate('ScreenWebViewComponent', {
                url: 'https://www.google.com',
            });}
                    />
                </View>
                <View>
                    <Text style={styles.title}>
                        All interaction for the component are disabled.
                    </Text>
                    <Button
                        title="Press me"
                        disabled
                        onPress={() => Alert.alert('Cannot press this one')}
                    />
                </View>
                <View>
                    <Text style={styles.title}>
                        This layout strategy lets the title define the width of the button.
                    </Text>
                    <View style={styles.fixToText}>
                        <Button
                            title="Left button"
                            onPress={() => Alert.alert('Left button pressed')}
                        />
                        <Button
                            title="Right button"
                            onPress={() => Alert.alert('Right button pressed')}
                        />
                    </View>
                </View>
            </SafeAreaView>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        marginHorizontal: 16,
    },
    title: {
        textAlign: 'center',
        marginVertical: 8,
    },
    fixToText: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    separator: {
        marginVertical: 8,
        borderBottomColor: '#737373',
        borderBottomWidth: StyleSheet.hairlineWidth,
    },
});
export default Login;


问:
sed for replace works manually but doesn't work from Java code
I'm able to use sed from command line on Windows:

```<code>PS C:\workspace\test_seek\src\main\java\org\example> cat .\test.txt
Testtestoldstringtesttest
PS C:\workspace\test_seek\src\main\java\org\example> sed -i 's/oldstring/newstring/g' test.txt
PS C:\workspace\test_seek\src\main\java\org\example> cat .\test.txt
Testtestnewstringtesttest
PS C:\workspace\test_seek\src\main\java\org\example> sed -i 's/newstring/oldstringagain/g' test.txt
PS C:\workspace\test_seek\src\main\java\org\example> cat .\test.txt
Testtestoldstringagaintesttest
</code>```

I'm trying to do it in Java code:

```<code>public class CmdTest {
    public static void main(String[] args) throws IOException {
        String[] cmdarr = {"cmd", "sed -i 's/oldstring/newstring/g' test.txt"};

        Process runCmd = Runtime.getRuntime().exec(cmdarr);
    }
}
</code>```

Process finish without exception but the file test.txt is not changed/updated.
I tried also:

```<code>    String[] cmdarr = {"cmd", "sed 's/oldstring/newstring/g' test.txt > test2.txt"};
    Process runCmd = Runtime.getRuntime().exec(cmdarr);
</code>```

and also with absoulute paths to file.

What is confusing for me - when I set path:

```<code>    String[] cmdarr = {"cmd", "sed -i 's/oldstring/newstring/g' notexist_badFile.txt"};
</code>```

it doesn't throw exception.
In terminal I get No such file or directory.

It means that my command is not run correctly? But it is run because when I run command:

```<code>    String[] cmdarr = {"cmd", "/c", "sed 's/oldstring/newstring/g' test.txt >
    test2.txt"};
</code>```

empty file test2.txt was created...

Body:
I'm able to use sed from command line on Windows:

PS C:\workspace\test_seek\src\main\java\org\example> cat .\test.txt
Testtestoldstringtesttest
PS C:\workspace\test_seek\src\main\java\org\example> sed -i 's/oldstring/newstring/g' test.txt
PS C:\workspace\test_seek\src\main\java\org\example> cat .\test.txt
Testtestnewstringtesttest
PS C:\workspace\test_seek\src\main\java\org\example> sed -i 's/newstring/oldstringagain/g' test.txt
PS C:\workspace\test_seek\src\main\java\org\example> cat .\test.txt
Testtestoldstringagaintesttest

I'm trying to do it in Java code:

public class CmdTest {
    public static void main(String[] args) throws IOException {
        String[] cmdarr = {"cmd", "sed -i 's/oldstring/newstring/g' test.txt"};

        Process runCmd = Runtime.getRuntime().exec(cmdarr);
    }
}

Process finish without exception but the file test.txt is not changed/updated.
I tried also:

    String[] cmdarr = {"cmd", "sed 's/oldstring/newstring/g' test.txt > test2.txt"};
    Process runCmd = Runtime.getRuntime().exec(cmdarr);

and also with absoulute paths to file.

What is confusing for me - when I set path:

    String[] cmdarr = {"cmd", "sed -i 's/oldstring/newstring/g' notexist_badFile.txt"};

it doesn't throw exception.
In terminal I get No such file or directory.

It means that my command is not run correctly? But it is run because when I run command:

    String[] cmdarr = {"cmd", "/c", "sed 's/oldstring/newstring/g' test.txt >
    test2.txt"};

empty file test2.txt was created...


问:
index 702 is out of bounds for axis 0 with size 5
Ι'm trying to run a TVP VAR for a panel on Statsmodel, but there seems to be two types of problems, after I have updated the state covariance matrices, related to indexing.
I suspect one is a consequence of the other error

To start with, I first get a warning error when I import my data in dta stata file that

```<code>`an unsupported index was provided and will be ignored when e.g. forecasting.
  self._init_dates(dates, freq)``
</code>```

The first part of the code I try to run is

```<code>dtafile = ‘DATA.dta'
df, meta = pyreadstat.read_dta(dtafile)
df.tail()

labels=list(meta.column_labels)
column=list(meta.column_names)

    Get the macro dataset- import stata dta file
import pyreadstat

dtafile = 'TVP.dta'
df, meta = pyreadstat.read_dta(dtafile)
df.tail()

labels=list(meta.column_labels)
column=list(meta.column_names)

#  Panel data settings
year = df.year
df['year'] = year.astype(int)
df = df.set_index([df.index, 'year'])

df.head()

# Subset to the  variables of interest
y = df[[‘LIST OF WHATE VEVER THOSE ARE]].copy()
y.columns = [ LIST ’WHATEVER THOSE ARE’]

</code>```

```<code>!continue
/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/tsa/base/tsa_model.py:471: ValueWarning: An unsupported index was provided and will be ignored when e.g. forecasting.
  self._init_dates(dates, freq)
</code>```

I then run the rest of the code and I reach the point of updating state covariance , manually set to 702 ,as such are the number of k_states

```<code>def update(self, params, **kwargs):
        params = super().update(params, **kwargs)
        self['transition', 2,2] = params[0]
        self['transition', 3,2] = params[1]
        self['state_cov'] = np.diag([params[2]**2, params[702]**2, params[4]**2])  # W
</code>```

I get

```<code>702
Traceback (most recent call last):

  File "/Users/user/Documents/PYTHON/Spider/tvp/tvpstandard3 (1).py", line 219, in <module>
    preliminary = tvppanelvarmodel.fit(maxiter=1000)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/tsa/statespace/mlemodel.py", line 704, in fit
    mlefit = super(MLEModel, self).fit(start_params, method=method,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/base/model.py", line 563, in fit
    xopt, retvals, optim_settings = optimizer._fit(f, score, start_params,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/base/optimizer.py", line 241, in _fit
    xopt, retvals = func(objective, gradient, start_params, fargs, kwargs,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/base/optimizer.py", line 651, in _fit_lbfgs
    retvals = optimize.fmin_l_bfgs_b(func, start_params, maxiter=maxiter,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/lbfgsb.py", line 197, in fmin_l_bfgs_b
    res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/lbfgsb.py", line 306, in _minimize_lbfgsb
    sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/optimize.py", line 261, in _prepare_scalar_function
    sf = ScalarFunction(fun, x0, args, grad, hess,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py", line 140, in __init__
    self._update_fun()

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py", line 233, in _update_fun
    self._update_fun_impl()

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py", line 137, in update_fun
    self.f = fun_wrapped(self.x)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py", line 134, in fun_wrapped
    return fun(np.copy(x), *args)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/base/model.py", line 531, in f
    return -self.loglike(params, *args) / nobs

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/tsa/statespace/mlemodel.py", line 933, in loglike
    self.update(params, transformed=True, includes_fixed=True,

  File "/Users/user/Documents/PYTHON/Spider/project/code1.py", line 203, in update
    self['state_cov'] = np.diag([params[2]**2, params[702]**2, params[4]**2])  # W

IndexError: index 702 is out of bounds for axis 0 with size 5
</code>```

I suspect one is consequence of the error or with numby in the update state covariance line. I have two questions:

How could I correct the index setting for a panel in statsmodel and how could I modify properly my code in order to solve this last error index 702 is out of bounds for axis 0 with size 5?

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

Body:
Ι'm trying to run a TVP VAR for a panel on Statsmodel, but there seems to be two types of problems, after I have updated the state covariance matrices, related to indexing.
I suspect one is a consequence of the other error

To start with, I first get a warning error when I import my data in dta stata file that

`an unsupported index was provided and will be ignored when e.g. forecasting.
  self._init_dates(dates, freq)``

The first part of the code I try to run is

dtafile = ‘DATA.dta'
df, meta = pyreadstat.read_dta(dtafile)
df.tail()

labels=list(meta.column_labels)
column=list(meta.column_names)

    Get the macro dataset- import stata dta file
import pyreadstat

dtafile = 'TVP.dta'
df, meta = pyreadstat.read_dta(dtafile)
df.tail()

labels=list(meta.column_labels)
column=list(meta.column_names)

#  Panel data settings
year = df.year
df['year'] = year.astype(int)
df = df.set_index([df.index, 'year'])

df.head()

# Subset to the  variables of interest
y = df[[‘LIST OF WHATE VEVER THOSE ARE]].copy()
y.columns = [ LIST ’WHATEVER THOSE ARE’]

!continue
/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/tsa/base/tsa_model.py:471: ValueWarning: An unsupported index was provided and will be ignored when e.g. forecasting.
  self._init_dates(dates, freq)

I then run the rest of the code and I reach the point of updating state covariance , manually set to 702 ,as such are the number of k_states

def update(self, params, **kwargs):
        params = super().update(params, **kwargs)
        self['transition', 2,2] = params[0]
        self['transition', 3,2] = params[1]
        self['state_cov'] = np.diag([params[2]**2, params[702]**2, params[4]**2])  # W

I get

702
Traceback (most recent call last):

  File "/Users/user/Documents/PYTHON/Spider/tvp/tvpstandard3 (1).py", line 219, in <module>
    preliminary = tvppanelvarmodel.fit(maxiter=1000)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/tsa/statespace/mlemodel.py", line 704, in fit
    mlefit = super(MLEModel, self).fit(start_params, method=method,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/base/model.py", line 563, in fit
    xopt, retvals, optim_settings = optimizer._fit(f, score, start_params,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/base/optimizer.py", line 241, in _fit
    xopt, retvals = func(objective, gradient, start_params, fargs, kwargs,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/base/optimizer.py", line 651, in _fit_lbfgs
    retvals = optimize.fmin_l_bfgs_b(func, start_params, maxiter=maxiter,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/lbfgsb.py", line 197, in fmin_l_bfgs_b
    res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/lbfgsb.py", line 306, in _minimize_lbfgsb
    sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/optimize.py", line 261, in _prepare_scalar_function
    sf = ScalarFunction(fun, x0, args, grad, hess,

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py", line 140, in __init__
    self._update_fun()

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py", line 233, in _update_fun
    self._update_fun_impl()

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py", line 137, in update_fun
    self.f = fun_wrapped(self.x)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py", line 134, in fun_wrapped
    return fun(np.copy(x), *args)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/base/model.py", line 531, in f
    return -self.loglike(params, *args) / nobs

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/statsmodels/tsa/statespace/mlemodel.py", line 933, in loglike
    self.update(params, transformed=True, includes_fixed=True,

  File "/Users/user/Documents/PYTHON/Spider/project/code1.py", line 203, in update
    self['state_cov'] = np.diag([params[2]**2, params[702]**2, params[4]**2])  # W

IndexError: index 702 is out of bounds for axis 0 with size 5

I suspect one is consequence of the error or with numby in the update state covariance line. I have two questions:

How could I correct the index setting for a panel in statsmodel and how could I modify properly my code in order to solve this last error index 702 is out of bounds for axis 0 with size 5?


问:
Dart Flutter web app runtime variable safety
Halo, i'm a flutter dev recently diving into Flutter web for the first time. I'm digging into security issues, especially for the source code exposed publicly via web browser inspector.

We can easily understand that String variables declared in a class can be access via browser inspect console despite of minification of web build command. That is, if we declare api auth token as a local variable, the token will be used maliciously with ease.

Some devs suggest an idea to use runtime variable for the security issue above. They suggest to retrieve auth token in flutter client from the server. But this solution gave me other two problems:

Such request endpoint to the server for token retrieval will be also exposed to the public js file, so that malicious access can also request the token.

i'm not sure whether such runtime flutter web variables cannot be accessed by client runner or not. Runtime variable would be hidden from the inspector console, but it could be accessed maliciously in some other ways, since the flutter code running on the browser is web app, which is not protected by android or ios platform security.

So, through this question, i hope to get some conceptual advice how to get through the dilemma above. I understand that firebase appcheck for flutter web app associated with google recaptcha would help this problem, but i hope to find some more non-commercial native(or web-native) solution. Hope this question reach gurus in the community. Any conceptual advice will be appreciated. Thanks in advance [:


问:
OAuth2 code flow - redirecting to login due to missing session while testing in browser
While testing the Oauth2 code flow through postman, the resource endpoint response is getting served properly, redirection and flow shown below:

Gateway with port 8989 exposes login endpoint: POST http://qa.example.com/api/v1/login, which internally calls auth service (hosted at post 8383) through webclient. Post successful authentication, gateway use the cookies and passes to as part of response cookies to UI.
(port being mapped at nginx side)

Gets the session from login response cookies and is passed as request header cookies to the resource endpoint (called through gateway): GET http://qa.example.com/api/v1/resource/test
(port being mapped at nginx side)

As part of Oauth2 code flow below redirection happens:

a) GET http://qa.example.com/oauth2/authorization/gateway-client
(port being mapped at nginx side)

b) GET
http://qa.example.com:8383/oauth2/authorize?response_type=code&client_id=gateway-client-id&scope=openid%20resource.read%20resource.write&state=uQfF4ev_xd4h2XmmFpuMpGTxKLCfgs0wcN0FNn0RVtA%3D&redirect_uri=http://qa.example.com:8989/login/oauth2/code/gateway-client&nonce=YXHwtVzCicDnn1jOn899sNBO6EfqgTT9yJIs0Qo937k

c) GET
http://qa.example.com:8989/login/oauth2/code/gateway-client?code=Xn_RQmRf57C87Oi36ZnHCdXvob9yFatbT3sHXAYi-tcOSR1NRBvBUqbKFxIUctLVYSnHQTkpk79YQcT4stpTKO8TnddBxFa-Ud1zmFoREruptiawBCDmFQ2qoFVRp1rD&state=uQfF4ev_xd4h2XmmFpuMpGTxKLCfgs0wcN0FNn0RVtA%3D

And finally the response for the resource endpoint is served.

The same flow when tested through browser is redirecting to login page after /oauth2/authorize i.e.
b) GET http://qa.example.com:8383/oauth2/authorize?response_type=code&client_id=gateway-client-id&scope=openid%20resource.read%20resource.write&state=uQfF4ev_xd4h2XmmFpuMpGTxKLCfgs0wcN0FNn0RVtA%3D&redirect_uri=http://qa.example.com:8989/login/oauth2/code/gateway-client&nonce=YXHwtVzCicDnn1jOn899sNBO6EfqgTT9yJIs0Qo937k
When investigated found cookie is missing in /oauth2/authorize call

The below cookie which is served by login response is found in resource endpoint i.e. 2. (GET http://qa.example.com/api/v1/resource/test) and a) GET http://qa.example.com/oauth2/authorization/gateway-client
Set-Cookie: SESSION=ef5ecd42-f988-4b3f-a72f-d8f4db66e741; Path=/; HttpOnly; SameSite=Lax

But somehow the cookie is lost in the /oauth2/authorize redirection call.

Any solution to fix the above problem?

Thanks.


问:
Custom sessions for TYPO3 API user integration
I am creating custom extension for TYPO3 (10.4) which will allow to log in to the panel via API data. I am keen to create a login session. My question is:

Should I use native sessions that PHP provides $_SESSION or there is any better way to do it. I found \TYPO3\CMS\Core\Session\Backend\SessionBackendInterface but I'm not sure if it's intended to be used that way.

In comparison, laravel provides a custom solution that works without the native php session: session() and session()->put('key', 'value');

My current idea:

```<code>/**
 * The function saves the retrieved user data from the API if the data provided at login matched the API data.
 */
function validUser(array $userData)
{
    $_SESSION['userData'] = $userData; // Is there any other way to do it, the solution provided by TYPO3 for such things
    return true;
}
</code>```

Body:
I am creating custom extension for TYPO3 (10.4) which will allow to log in to the panel via API data. I am keen to create a login session. My question is:

Should I use native sessions that PHP provides $_SESSION or there is any better way to do it. I found \TYPO3\CMS\Core\Session\Backend\SessionBackendInterface but I'm not sure if it's intended to be used that way.

In comparison, laravel provides a custom solution that works without the native php session: session() and session()->put('key', 'value');

My current idea:

/**
 * The function saves the retrieved user data from the API if the data provided at login matched the API data.
 */
function validUser(array $userData)
{
    $_SESSION['userData'] = $userData; // Is there any other way to do it, the solution provided by TYPO3 for such things
    return true;
}


问:
how to run a script only on some targets beginning with a specific pattern?
Considering a first script (language does not matter, it could be replaced by whatever you like, the idea is what it does: replacing, stopping,..)

my_script.py

```<code>for line in sys.stdin:
    for line in file:
        if line:
            if 'plop' in line:
                raise Exception("'plop' found, aborting target")
            line = re.sub(r'not possible yet', r'nice' , line):

</code>```

I want to use this script for some of the targets in this simplified makefile:

```<code>
not_usefull:
    @echo "this is not possible yet and will never be"

something_nice:
    @echo "this is not possible yet"

something_very_nice:
    @echo "this is not possible yet again"

something_bad:
    @echo "this is not possible yet plop"

# The following part is not working
# and I don't like to call make in the recipe
# but you get the idea

ifeq ($(MAKING_IMPOSSIBLE_NICE),yes)
something_%:
    @$(MAKE) $@ | my_script.py
endif
</code>```

use and expected outputs:

```<code>#text replaced
make something_bad MAKING_IMPOSSIBLE_NICE=no
> "this is not possible yet plop"

make something_nice MAKING_IMPOSSIBLE_NICE=no
> "this is not possible yet"

make something_nice MAKING_IMPOSSIBLE_NICE=yes
> "this is nice"

make something_very_nice MAKING_IMPOSSIBLE_NICE=yes
> "this is nice again"

#no effect here because the target does not start by 'something_'
make not_usefull MAKING_IMPOSSIBLE_NICE=no
> "this is not possible yet and will never be"

make not_usefull MAKING_IMPOSSIBLE_NICE=yes
> "this is not possible yet and will never be"

#target aborted because target ouput contains forbidden 'plop'
make something_very_nice MAKING_IMPOSSIBLE_NICE=no
> "this is not possible yet again"

make something_bad MAKING_IMPOSSIBLE_NICE=yes
> "'plop' found, aborting target"

</code>```

I would like to call a parsing/trimming script (my_script.py) after some specific targets, so the output could be formatted (add colors, replace 'helo' by 'Hello'), and action could be triggered (like aborting target if a specific string appears).

Note that I would like the solution to be working on current and new makefile targets.
I have no control on how many target there will be as they are not created by me.
I have no control on the target output and it could change anytime.

How could I do this?

Body:
Considering a first script (language does not matter, it could be replaced by whatever you like, the idea is what it does: replacing, stopping,..)

my_script.py

for line in sys.stdin:
    for line in file:
        if line:
            if 'plop' in line:
                raise Exception("'plop' found, aborting target")
            line = re.sub(r'not possible yet', r'nice' , line):

I want to use this script for some of the targets in this simplified makefile:

not_usefull:
    @echo "this is not possible yet and will never be"

something_nice:
    @echo "this is not possible yet"

something_very_nice:
    @echo "this is not possible yet again"

something_bad:
    @echo "this is not possible yet plop"

# The following part is not working
# and I don't like to call make in the recipe
# but you get the idea

ifeq ($(MAKING_IMPOSSIBLE_NICE),yes)
something_%:
    @$(MAKE) $@ | my_script.py
endif

use and expected outputs:

#text replaced
make something_bad MAKING_IMPOSSIBLE_NICE=no
> "this is not possible yet plop"

make something_nice MAKING_IMPOSSIBLE_NICE=no
> "this is not possible yet"

make something_nice MAKING_IMPOSSIBLE_NICE=yes
> "this is nice"

make something_very_nice MAKING_IMPOSSIBLE_NICE=yes
> "this is nice again"

#no effect here because the target does not start by 'something_'
make not_usefull MAKING_IMPOSSIBLE_NICE=no
> "this is not possible yet and will never be"

make not_usefull MAKING_IMPOSSIBLE_NICE=yes
> "this is not possible yet and will never be"

#target aborted because target ouput contains forbidden 'plop'
make something_very_nice MAKING_IMPOSSIBLE_NICE=no
> "this is not possible yet again"

make something_bad MAKING_IMPOSSIBLE_NICE=yes
> "'plop' found, aborting target"

I would like to call a parsing/trimming script (my_script.py) after some specific targets, so the output could be formatted (add colors, replace 'helo' by 'Hello'), and action could be triggered (like aborting target if a specific string appears).

Note that I would like the solution to be working on current and new makefile targets.
I have no control on how many target there will be as they are not created by me.
I have no control on the target output and it could change anytime.

How could I do this?


问:
Unable to install App on real device or distribute it ad hoc, normal on Simulator
Running on the simulator works fine, but when I try to run on an iPhone using a USB cable, Xcode says:

A valid provisioning profile for this executable was not found.

Both the app and simulator are running iOS 16.

Xcode 14.1

Latest Cocoapod and ruby

The message in the picture says something about the profile but I'm not able/know how to add/upgrade it.

```
    Unable to install "Runner"
    Domain: com.apple.dt.MobileDeviceErrorDomain
    Code: -402620395
    User Info: {
        DVTErrorCreationDateKey = "2022-12-07 17:43:42 +0000";
        IDERunOperationFailingWorker = IDEInstalliPhoneLauncher;
    }
    --
    A valid provisioning profile for this executable was not found.
    Domain: com.apple.dt.MobileDeviceErrorDomain
    Code: -402620395
    User Info: {
        DVTRadarComponentKey = 487925;
        MobileDeviceErrorCode = "(0xE8008015)";
        "com.apple.dtdevicekit.stacktrace" = (
        0   DTDeviceKitBase                     0x000000010d3afc90 DTDKCreateNSErrorFromAMDErrorCode + 235
        1   DTDeviceKitBase                     0x000000010d3ec2ee __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 155
        2   DVTFoundation                       0x0000000102e4ac71 DVTInvokeWithStrongOwnership + 71
        3   DTDeviceKitBase                     0x000000010d3ec016 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1409
        4   IDEiOSSupportCore                   0x000000010d0cd780 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.301 + 3520
        5   DVTFoundation                       0x0000000102f80879 __DVT_CALLING_CLIENT_BLOCK__ + 7
        6   DVTFoundation                       0x0000000102f8138d __DVTDispatchAsync_block_invoke + 196
        7   libdispatch.dylib                   0x00007ff8016577fb _dispatch_call_block_and_release + 12
        8   libdispatch.dylib                   0x00007ff801658a44 _dispatch_client_callout + 8
        9   libdispatch.dylib                   0x00007ff80165eac4 _dispatch_lane_serial_drain + 694
        10  libdispatch.dylib                   0x00007ff80165f5b4 _dispatch_lane_invoke + 366
        11  libdispatch.dylib                   0x00007ff801669ad7 _dispatch_workloop_worker_thread + 762
        12  libsystem_pthread.dylib             0x00007ff8017d4ce3 _pthread_wqthread + 326
        13  libsystem_pthread.dylib             0x00007ff8017d3c67 start_wqthread + 15
    );
    }
    --

    Analytics Event: com.apple.dt.IDERunOperationWorkerFinished : {
        "device_model" = "iPhone8,2";
        "device_osBuild" = "15.7.1 (19H117)";
        "device_platform" = "com.apple.platform.iphoneos";
        "launchSession_schemeCommand" = Run;
        "launchSession_state" = 1;
        "launchSession_targetArch" = arm64;
        "operation_duration_ms" = 14739;
        "operation_errorCode" = "-402620395";
        "operation_errorDomain" = "com.apple.dt.MobileDeviceErrorDomain";
        "operation_errorWorker" = IDEInstalliPhoneLauncher;
        "operation_name" = IDEiPhoneRunOperationWorkerGroup;
        "param_consoleMode" = 0;
        "param_debugger_attachToExtensions" = 0;
        "param_debugger_attachToXPC" = 1;
        "param_debugger_type" = 5;
        "param_destination_isProxy" = 0;
        "param_destination_platform" = "com.apple.platform.iphoneos";
        "param_diag_MainThreadChecker_stopOnIssue" = 0;
        "param_diag_MallocStackLogging_enableDuringAttach" = 0;
        "param_diag_MallocStackLogging_enableForXPC" = 1;
        "param_diag_allowLocationSimulation" = 1;
        "param_diag_checker_tpc_enable" = 1;
        "param_diag_gpu_frameCapture_enable" = 0;
        "param_diag_gpu_shaderValidation_enable" = 0;
        "param_diag_gpu_validation_enable" = 0;
        "param_diag_memoryGraphOnResourceException" = 0;
        "param_diag_queueDebugging_enable" = 1;
        "param_diag_runtimeProfile_generate" = 0;
        "param_diag_sanitizer_asan_enable" = 0;
        "param_diag_sanitizer_tsan_enable" = 0;
        "param_diag_sanitizer_tsan_stopOnIssue" = 0;
        "param_diag_sanitizer_ubsan_stopOnIssue" = 0;
        "param_diag_showNonLocalizedStrings" = 0;
        "param_diag_viewDebugging_enabled" = 1;
        "param_diag_viewDebugging_insertDylibOnLaunch" = 1;
        "param_install_style" = 0;
        "param_launcher_UID" = 2;
        "param_launcher_allowDeviceSensorReplayData" = 0;
        "param_launcher_kind" = 0;
        "param_launcher_style" = 0;
        "param_launcher_substyle" = 0;
        "param_runnable_appExtensionHostRunMode" = 0;
        "param_runnable_productType" = "com.apple.product-type.application";
        "param_runnable_type" = 2;
        "param_testing_launchedForTesting" = 0;
        "param_testing_suppressSimulatorApp" = 0;
        "param_testing_usingCLI" = 0;
        "sdk_canonicalName" = "iphoneos16.1";
        "sdk_osVersion" = "16.1";
        "sdk_variant" = iphoneos;
    }
    --

    System Information

    macOS Version 13.0.1 (Build 22A400)
    Xcode 14.1 (21534.1) (Build 14B47b)
    Timestamp: 2022-12-07T18:43:42+01:00
```

Body:
Running on the simulator works fine, but when I try to run on an iPhone using a USB cable, Xcode says:

A valid provisioning profile for this executable was not found.

Both the app and simulator are running iOS 16.

Xcode 14.1

Latest Cocoapod and ruby

The message in the picture says something about the profile but I'm not able/know how to add/upgrade it.

    Unable to install "Runner"
    Domain: com.apple.dt.MobileDeviceErrorDomain
    Code: -402620395
    User Info: {
        DVTErrorCreationDateKey = "2022-12-07 17:43:42 +0000";
        IDERunOperationFailingWorker = IDEInstalliPhoneLauncher;
    }
    --
    A valid provisioning profile for this executable was not found.
    Domain: com.apple.dt.MobileDeviceErrorDomain
    Code: -402620395
    User Info: {
        DVTRadarComponentKey = 487925;
        MobileDeviceErrorCode = "(0xE8008015)";
        "com.apple.dtdevicekit.stacktrace" = (
        0   DTDeviceKitBase                     0x000000010d3afc90 DTDKCreateNSErrorFromAMDErrorCode + 235
        1   DTDeviceKitBase                     0x000000010d3ec2ee __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 155
        2   DVTFoundation                       0x0000000102e4ac71 DVTInvokeWithStrongOwnership + 71
        3   DTDeviceKitBase                     0x000000010d3ec016 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1409
        4   IDEiOSSupportCore                   0x000000010d0cd780 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.301 + 3520
        5   DVTFoundation                       0x0000000102f80879 __DVT_CALLING_CLIENT_BLOCK__ + 7
        6   DVTFoundation                       0x0000000102f8138d __DVTDispatchAsync_block_invoke + 196
        7   libdispatch.dylib                   0x00007ff8016577fb _dispatch_call_block_and_release + 12
        8   libdispatch.dylib                   0x00007ff801658a44 _dispatch_client_callout + 8
        9   libdispatch.dylib                   0x00007ff80165eac4 _dispatch_lane_serial_drain + 694
        10  libdispatch.dylib                   0x00007ff80165f5b4 _dispatch_lane_invoke + 366
        11  libdispatch.dylib                   0x00007ff801669ad7 _dispatch_workloop_worker_thread + 762
        12  libsystem_pthread.dylib             0x00007ff8017d4ce3 _pthread_wqthread + 326
        13  libsystem_pthread.dylib             0x00007ff8017d3c67 start_wqthread + 15
    );
    }
    --

    Analytics Event: com.apple.dt.IDERunOperationWorkerFinished : {
        "device_model" = "iPhone8,2";
        "device_osBuild" = "15.7.1 (19H117)";
        "device_platform" = "com.apple.platform.iphoneos";
        "launchSession_schemeCommand" = Run;
        "launchSession_state" = 1;
        "launchSession_targetArch" = arm64;
        "operation_duration_ms" = 14739;
        "operation_errorCode" = "-402620395";
        "operation_errorDomain" = "com.apple.dt.MobileDeviceErrorDomain";
        "operation_errorWorker" = IDEInstalliPhoneLauncher;
        "operation_name" = IDEiPhoneRunOperationWorkerGroup;
        "param_consoleMode" = 0;
        "param_debugger_attachToExtensions" = 0;
        "param_debugger_attachToXPC" = 1;
        "param_debugger_type" = 5;
        "param_destination_isProxy" = 0;
        "param_destination_platform" = "com.apple.platform.iphoneos";
        "param_diag_MainThreadChecker_stopOnIssue" = 0;
        "param_diag_MallocStackLogging_enableDuringAttach" = 0;
        "param_diag_MallocStackLogging_enableForXPC" = 1;
        "param_diag_allowLocationSimulation" = 1;
        "param_diag_checker_tpc_enable" = 1;
        "param_diag_gpu_frameCapture_enable" = 0;
        "param_diag_gpu_shaderValidation_enable" = 0;
        "param_diag_gpu_validation_enable" = 0;
        "param_diag_memoryGraphOnResourceException" = 0;
        "param_diag_queueDebugging_enable" = 1;
        "param_diag_runtimeProfile_generate" = 0;
        "param_diag_sanitizer_asan_enable" = 0;
        "param_diag_sanitizer_tsan_enable" = 0;
        "param_diag_sanitizer_tsan_stopOnIssue" = 0;
        "param_diag_sanitizer_ubsan_stopOnIssue" = 0;
        "param_diag_showNonLocalizedStrings" = 0;
        "param_diag_viewDebugging_enabled" = 1;
        "param_diag_viewDebugging_insertDylibOnLaunch" = 1;
        "param_install_style" = 0;
        "param_launcher_UID" = 2;
        "param_launcher_allowDeviceSensorReplayData" = 0;
        "param_launcher_kind" = 0;
        "param_launcher_style" = 0;
        "param_launcher_substyle" = 0;
        "param_runnable_appExtensionHostRunMode" = 0;
        "param_runnable_productType" = "com.apple.product-type.application";
        "param_runnable_type" = 2;
        "param_testing_launchedForTesting" = 0;
        "param_testing_suppressSimulatorApp" = 0;
        "param_testing_usingCLI" = 0;
        "sdk_canonicalName" = "iphoneos16.1";
        "sdk_osVersion" = "16.1";
        "sdk_variant" = iphoneos;
    }
    --

    System Information

    macOS Version 13.0.1 (Build 22A400)
    Xcode 14.1 (21534.1) (Build 14B47b)
    Timestamp: 2022-12-07T18:43:42+01:00


问:
synchronize a server-client program in c
In the code there are simultaneous operations between the clients and the server on the same datas. I used semaphores for synchronization. But it turns out that I had to add unsleep(5000) after each sem_post because the client performing the operation starts the next one directly without letting the others start. In the Code I would like to remove this unsleep.

How can I synchronize my threads without using unsleep at the end?

Client 1

```<code>
while(condition){
 sem_wait(&sem);

 --operations--

 sem_post(&sem)
 unsleep(50000);

}
</code>```

Client 2

```<code>
while(condition){
 sem_wait(&sem);

 --operations--

 sem_post(&sem)
 unsleep(50000);

}
</code>```

Client 3

```<code>
while(condition){
 sem_wait(&sem);

 --operations--

 sem_post(&sem)
 unsleep(50000);

}
</code>```

Body:
In the code there are simultaneous operations between the clients and the server on the same datas. I used semaphores for synchronization. But it turns out that I had to add unsleep(5000) after each sem_post because the client performing the operation starts the next one directly without letting the others start. In the Code I would like to remove this unsleep.

How can I synchronize my threads without using unsleep at the end?

Client 1

while(condition){
 sem_wait(&sem);

 --operations--

 sem_post(&sem)
 unsleep(50000);

}

Client 2

while(condition){
 sem_wait(&sem);

 --operations--

 sem_post(&sem)
 unsleep(50000);

}

Client 3

while(condition){
 sem_wait(&sem);

 --operations--

 sem_post(&sem)
 unsleep(50000);

}