问:
How to upload an image to django from an html input file
I am developing a web service on django with frontend on react. I ran into a problem that I can't upload an image to django. Below is my component code where I'm trying to download it:

```<code>export function ProviderRegistration(){
    const[logoField, setLogoField] = useState()
    const token = useSelector((state) => state.user.token)
    const [cookie, setCookie] = useCookies(['auth'])

    const confirm = () => {
        axios.post(`/providers/?username=${cookie.auth.login}`,
        {
            photo : logoField
        },
        { "headers" : { "Authorization" : "token " + token }})
        .then(res => console.log(res))
        .catch(err => console.log(err))
    }

    return(
        <div className="registration-provider-container">
            <div className="registration-title">Provider registration</div>
            <input type="file" className="registration-logo-add" onChange={(e) => setLogoField(e.target.value)}/>
            <button className="registration-confirm" onClick={() => confirm()}>Confirm</button>
        </div>
)}
</code>```

And the endpoint processing this request

```<code>class Providers(viewsets.ModelViewSet):
    filterset_class = ProvidersFilter
    queryset = Provider.objects.all()
    permission_classes = [IsAuthenticatedOrReadOnly, IsProviderPermission, IsOneToOneProviderPermission]
    def get_serializer_class(self):
        if self.action == 'list':
            return GetProviderSerializer
        else:
            return PutProviderSerializer

    def create(self, request):
        username = request.GET.get('username', '')
        user = User.objects.get(username=username).pk
        request.data.update({'user' : user})
        print(request.data)
        return super().create(request)
</code>```

When I try to upload an image, django returns the following error:

```<code>"The submitted data was not a file. Check the encoding type on the form."
</code>```

And I haven't found a way to correctly upload an image to django using Ajax.
I also output what my browser sends to the server:

```<code>{photo : 'C:\\fakepath\\magnit.jpg'}
</code>```

Body:
I am developing a web service on django with frontend on react. I ran into a problem that I can't upload an image to django. Below is my component code where I'm trying to download it:

export function ProviderRegistration(){
    const[logoField, setLogoField] = useState()
    const token = useSelector((state) => state.user.token)
    const [cookie, setCookie] = useCookies(['auth'])

    const confirm = () => {
        axios.post(`/providers/?username=${cookie.auth.login}`,
        {
            photo : logoField
        },
        { "headers" : { "Authorization" : "token " + token }})
        .then(res => console.log(res))
        .catch(err => console.log(err))
    }

    return(

Provider registration

            <input type="file" className="registration-logo-add" onChange={(e) => setLogoField(e.target.value)}/>
            <button className="registration-confirm" onClick={() => confirm()}>Confirm</button>

)}

And the endpoint processing this request

class Providers(viewsets.ModelViewSet):
    filterset_class = ProvidersFilter
    queryset = Provider.objects.all()
    permission_classes = [IsAuthenticatedOrReadOnly, IsProviderPermission, IsOneToOneProviderPermission]
    def get_serializer_class(self):
        if self.action == 'list':
            return GetProviderSerializer
        else:
            return PutProviderSerializer

    def create(self, request):
        username = request.GET.get('username', '')
        user = User.objects.get(username=username).pk
        request.data.update({'user' : user})
        print(request.data)
        return super().create(request)

When I try to upload an image, django returns the following error:

"The submitted data was not a file. Check the encoding type on the form."

And I haven't found a way to correctly upload an image to django using Ajax.
I also output what my browser sends to the server:

{photo : 'C:\\fakepath\\magnit.jpg'}


来源: stackexchange

问:
Post Keepalived configuration, Server with VIP unable to communicate to other servers
I have configured keepalived on two servers, 10.90.11.194 (Server1) and 10.90.11.196(Server2). Server1 is configured as the MASTER while Server2 is the BACKUP. The VIP 10.90.11.219 successfully switches from Server1 to Server2 when keepalived is stopped on Server1.
Both the servers have syslog-ng configured in them to receive syslogs from firewalls, proxy etc. These servers also have Splunk Heavy Forwarder application installed on them to forward these incoming syslogs to Splunk indexers 10.90.11.226 (IDX1), 10.90.11.227(IDX2) and 10.90.11.228(IDX3).
Server1, Server2, IDX1, IDX2 and IDX 3 are all in the same security group and any-any connection is allowed between them. VIP is also allowed inbound and outbound for this security group.

Problem: No matter which device has VIP assigned, it will not be able to connect to the indexers (IDX1, IDX2 and IDX3) at port 9997. However, this connectivity works absolutely fine from the other device without VIP.

Keepalived Config on Master.

```<code>vrrp_instance VI_1 {
            state MASTER
            interface ens3
            virtual_router_id 51
            priority 100
            advert_int 1
            unicast_src_ip 10.90.11.194
            unicast_peer {
                    10.90.11.196
            }
            authentication {
                  auth_type PASS
                  auth_pass 12345
            }
            virtual_ipaddress {
                 10.90.11.219/24
            }
    }

</code>```

On BACKUP unicast IPs are reversed, priority is 50 and state is BACKUP.

Pinging IDX devices from the server without VIP works fine. Problem is only with the device with VIP where I get "Destination Host Unreachable" response from VIP

```<code>[root@SERVER1 ~]# ping 10.90.11.226
PING 10.90.11.226 (10.90.11.226) 56(84) bytes of data.
From 10.90.11.219 icmp_seq=1 Destination Host Unreachable
From 10.90.11.219 icmp_seq=2 Destination Host Unreachable
From 10.90.11.219 icmp_seq=3 Destination Host Unreachable

[root@SERVER1 ~]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.90.11.193    0.0.0.0         UG    100    0        0 ens3
10.90.11.0      0.0.0.0         255.255.255.0   U     0      0        0 ens3
10.90.11.192    0.0.0.0         255.255.255.224 U     100    0        0 ens3
169.254.169.254 10.90.11.222    255.255.255.255 UGH   100    0        0 ens3
</code>```

Could any of you please help fix the issue here?

ContentLicense: CC BY-SA 4.0

Body:
I have configured keepalived on two servers, 10.90.11.194 (Server1) and 10.90.11.196(Server2). Server1 is configured as the MASTER while Server2 is the BACKUP. The VIP 10.90.11.219 successfully switches from Server1 to Server2 when keepalived is stopped on Server1.
Both the servers have syslog-ng configured in them to receive syslogs from firewalls, proxy etc. These servers also have Splunk Heavy Forwarder application installed on them to forward these incoming syslogs to Splunk indexers 10.90.11.226 (IDX1), 10.90.11.227(IDX2) and 10.90.11.228(IDX3).
Server1, Server2, IDX1, IDX2 and IDX 3 are all in the same security group and any-any connection is allowed between them. VIP is also allowed inbound and outbound for this security group.

Problem: No matter which device has VIP assigned, it will not be able to connect to the indexers (IDX1, IDX2 and IDX3) at port 9997. However, this connectivity works absolutely fine from the other device without VIP.

Keepalived Config on Master.

vrrp_instance VI_1 {
            state MASTER
            interface ens3
            virtual_router_id 51
            priority 100
            advert_int 1
            unicast_src_ip 10.90.11.194
            unicast_peer {
                    10.90.11.196
            }
            authentication {
                  auth_type PASS
                  auth_pass 12345
            }
            virtual_ipaddress {
                 10.90.11.219/24
            }
    }

On BACKUP unicast IPs are reversed, priority is 50 and state is BACKUP.

Pinging IDX devices from the server without VIP works fine. Problem is only with the device with VIP where I get "Destination Host Unreachable" response from VIP

[root@SERVER1 ~]# ping 10.90.11.226
PING 10.90.11.226 (10.90.11.226) 56(84) bytes of data.
From 10.90.11.219 icmp_seq=1 Destination Host Unreachable
From 10.90.11.219 icmp_seq=2 Destination Host Unreachable
From 10.90.11.219 icmp_seq=3 Destination Host Unreachable

[root@SERVER1 ~]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.90.11.193    0.0.0.0         UG    100    0        0 ens3
10.90.11.0      0.0.0.0         255.255.255.0   U     0      0        0 ens3
10.90.11.192    0.0.0.0         255.255.255.224 U     100    0        0 ens3
169.254.169.254 10.90.11.222    255.255.255.255 UGH   100    0        0 ens3

Could any of you please help fix the issue here?


问:
Webrtc being included as webrtc.lib within conanbuildinfo.props instead of libwebrtc.a
I am trying to consume a Linux based binary of Webrtc (https://webrtc.org/) in a Conan package with another project and finding when the Visual Studio generator runs it tries to include Webrtc as webrtc.lib instead of libwebrtc.a.

Here's the conanfile.py recipe I am using to create the local Webrtc package...

```<code>class WebrtcConan(ConanFile):
    name = "webrtc"
    version = "0.1"
    license = "<Put the package license here>"
    author = "<Put your name here> <And your email here>"
    url = "<Package recipe repository url here, for issues about the package>"
    description = "<Description of Webrtc here>"
    topics = ("<Put some tag here>", "<here>", "<and here>")
    settings = {"os", "compiler", "build_type", "arch"}
    options = {"shared": [True, False], "fPIC": [True, False]}
    default_options = {"shared": False, "fPIC": True}

    def package(self):
        self.copy("*")

    def package_info(self):
        self.cpp_info.libs = self.collect_libs()
</code>```

I'm exporting the package to the local cache like this...

```<code>conan export-pkg -f . webrtc/local
</code>```

Then running the Visual Studio generator like this in the consuming project...

```<code>conan install . -g visual_studio
</code>```

Reviewing the generated conanbuildinfo.props shows Webrtc included as webrtc.lib instead of libwebrtc.a.

I CAN get the correct library inclusion with the following changes to package and package_info...

```<code>class WebrtcConan(ConanFile):
    name = "webrtc"
    version = "0.1"
    license = "<Put the package license here>"
    author = "<Put your name here> <And your email here>"
    url = "<Package recipe repository url here, for issues about the package>"
    description = "<Description of Webrtc here>"
    topics = ("<Put some tag here>", "<here>", "<and here>")
    settings = {"os", "compiler", "build_type", "arch"}
    options = {"shared": [True, False], "fPIC": [True, False]}
    default_options = {"shared": False, "fPIC": True}
    generators = "visual_studio"

    def package(self):
        self.copy("*.a", dst="lib", keep_path=False) <<< specific destination

    def package_info(self):
        self.cpp_info.libs = ["libwebrtc.a"] <<< specific library inclusion
</code>```

Ideally I can use this default recipe (the first conanfile.py example) as I'm not the one responsible for creating the Webrtc Conan package ultimately.  I am working with another team/developer responsible for this and I need to support several different platforms past Linux.  Is there a setting I'm missing somewhere to control the library inclusion?  Why does the Conan generator assume the library name is webrtc.lib for consumer inclusion when it is included within the package as libwebrtc.a?

Body:
I am trying to consume a Linux based binary of Webrtc (https://webrtc.org/) in a Conan package with another project and finding when the Visual Studio generator runs it tries to include Webrtc as webrtc.lib instead of libwebrtc.a.

Here's the conanfile.py recipe I am using to create the local Webrtc package...

class WebrtcConan(ConanFile):
    name = "webrtc"
    version = "0.1"
    license = "<Put the package license here>"
    author = "<Put your name here> <And your email here>"
    url = "<Package recipe repository url here, for issues about the package>"
    description = "<Description of Webrtc here>"
    topics = ("<Put some tag here>", "<here>", "<and here>")
    settings = {"os", "compiler", "build_type", "arch"}
    options = {"shared": [True, False], "fPIC": [True, False]}
    default_options = {"shared": False, "fPIC": True}

    def package(self):
        self.copy("*")

    def package_info(self):
        self.cpp_info.libs = self.collect_libs()

I'm exporting the package to the local cache like this...

conan export-pkg -f . webrtc/local

Then running the Visual Studio generator like this in the consuming project...

conan install . -g visual_studio

Reviewing the generated conanbuildinfo.props shows Webrtc included as webrtc.lib instead of libwebrtc.a.

I CAN get the correct library inclusion with the following changes to package and package_info...

class WebrtcConan(ConanFile):
    name = "webrtc"
    version = "0.1"
    license = "<Put the package license here>"
    author = "<Put your name here> <And your email here>"
    url = "<Package recipe repository url here, for issues about the package>"
    description = "<Description of Webrtc here>"
    topics = ("<Put some tag here>", "<here>", "<and here>")
    settings = {"os", "compiler", "build_type", "arch"}
    options = {"shared": [True, False], "fPIC": [True, False]}
    default_options = {"shared": False, "fPIC": True}
    generators = "visual_studio"

    def package(self):
        self.copy("*.a", dst="lib", keep_path=False) <<< specific destination

    def package_info(self):
        self.cpp_info.libs = ["libwebrtc.a"] <<< specific library inclusion

Ideally I can use this default recipe (the first conanfile.py example) as I'm not the one responsible for creating the Webrtc Conan package ultimately.  I am working with another team/developer responsible for this and I need to support several different platforms past Linux.  Is there a setting I'm missing somewhere to control the library inclusion?  Why does the Conan generator assume the library name is webrtc.lib for consumer inclusion when it is included within the package as libwebrtc.a?


问:
Build a jpa specification query without retriving child entity data
I'm trying to build a search query to find all Test entity data.
Here are my classes...

TestParent.java

```<code>@Entity
public class TestParant{
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String createdBy;

  @OneToMany(
            targetEntity = Channel.class,
            cascade = {CascadeType.ALL},
            fetch = FetchType.LAZY)
    @JoinColumn(name = "test_id")
    private List<Channel> channels;
 }
</code>```

Channel.java

```<code>@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Channel{

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Enumerated(EnumType.STRING)
    private Channel channelName;

    @ManyToOne
    @JoinColumn(name = "id", referencedColumnName = "id")
    @JsonBackReference
    private Test test;

    @OneToMany(
            targetEntity = TvSet.class,
            cascade = {CascadeType.ALL},
            fetch = FetchType.LAZY)
    @JoinColumn(name = "channel_id")
    private List<TvSet> tvSets;

}
</code>```

My specification query...

```<code>   public Specification<TEST> generateFilterTestQuery(FilterRequest filterRequest) {
        log.info("start to build query  from" + filterRequest);
        return (root, cq, cb) -> {
            Predicate p = cb.conjunction();
            Join<Channel, Campaign> channel = root.join("channels", JoinType.INNER);
            if (!filterRequest.getStartCreatedDate().isEmpty() && !filterRequest.getEndCreatedDate().isEmpty())
                p = cb.and(p,
                        cb.between(root.get(CREATED_DATE),
                                filterRequest.getStartCreatedDate(), filterRequest.getEndCreatedDate()));
            else if (!(filterRequest.getStartCreatedDate().isEmpty()))
                p = cb.and(p,
                        cb.greaterThanOrEqualTo(root.get(CREATED_DATE),
                                filterRequest.getStartCreatedDate()));
            else if (!(filterRequest.getEndCreatedDate().isEmpty()))
                p = cb.and(p,
                        cb.lessThanOrEqualTo(root.get(CREATED_DATE),

                                filterRequest.getEndCreatedDate()));
            if (!filterRequest.getCreatedBy().isEmpty()) {
                p = cb.and(p,
                        cb.equal(root.get("createdBy"), filterRequest.getCreatedBy()));
            }

            if (!filterRequest.getBrandId().isEmpty()) {
                p = cb.and(p,
                        cb.equal(root.get("brandId"), filterRequest.getBrandId()));
            }
            if (!filterRequest.getChannel().isEmpty()) {

                p = cb.and(p,
                        cb.equal(channel.get("channelName"), Channel.valueOf(filterRequest.getChannel())));
            }
            if (filterRequest.getSort().equals(SortEnum.ASC)) {
                cq.orderBy(cb.asc(root.get(CREATED_DATE)));
            } else {
                cq.orderBy(cb.desc(root.get(CREATED_DATE)));
            }
            return p;
        };
    }
</code>```

And my service method...

```<code>public Page<TEST> filter(FilterRequest filterRequest) throws BaseException {
        try {
            log.info("Getting campaign for filterRequest : {} ", filterRequest);
            // Find Sorted Creatives By filterRequest
            Pageable pageable =
                    PageRequest.of(filterRequest.getPageNumber(), filterRequest.getPageSize());
            return repository.findAll(generateFilterTestQuery(filterRequest),pageable);
        } catch (IllegalArgumentException e) {
            log.error(e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }
</code>```

The result I'm getting...

```<code>   "content": [
    {
      "id": 516,
      "name": "Tes",
      "createdBy": "test",
      "brandId": "1",
      "createdDate": 1671529546,
      "channels": [
        {
          "id": 312,
          "channelName": "TV1",
          "channelStatus": "DONE",
          "tvSet": [
            {
              "id": 312,
                "locations": [
                  {
                    "id": 302,
                    "isGeoLocation": true,
                    "cities": [
                      {
                        "id": 282,
                        "distanceUnit": "kilometer",
                      },
                      {
                        "id": 283,
                        "distanceUnit": "kilometer",
                      }
                    ],

    }
</code>```

But I want to get results(channels ) that without getting tvSet array like in below

```<code>   "content": [
    {
      "id": 516,
      "name": "Tes",
      "createdBy": "test",
      "brandId": "1",
      "createdDate": 1671529546,
      "channels": [
        {
          "id": 312,
          "channelName": "TV1",
          "channelStatus": "DONE",
          "tvSet": [],

    }
</code>```

Can someone please help me to resolve this issue?? Thank you!!

Body:
I'm trying to build a search query to find all Test entity data.
Here are my classes...

TestParent.java

@Entity
public class TestParant{
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String createdBy;

  @OneToMany(
            targetEntity = Channel.class,
            cascade = {CascadeType.ALL},
            fetch = FetchType.LAZY)
    @JoinColumn(name = "test_id")
    private List<Channel> channels;
 }

Channel.java

@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Channel{

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Enumerated(EnumType.STRING)
    private Channel channelName;

    @ManyToOne
    @JoinColumn(name = "id", referencedColumnName = "id")
    @JsonBackReference
    private Test test;

    @OneToMany(
            targetEntity = TvSet.class,
            cascade = {CascadeType.ALL},
            fetch = FetchType.LAZY)
    @JoinColumn(name = "channel_id")
    private List<TvSet> tvSets;

}

My specification query...

   public Specification<TEST> generateFilterTestQuery(FilterRequest filterRequest) {
        log.info("start to build query  from" + filterRequest);
        return (root, cq, cb) -> {
            Predicate p = cb.conjunction();
            Join<Channel, Campaign> channel = root.join("channels", JoinType.INNER);
            if (!filterRequest.getStartCreatedDate().isEmpty() && !filterRequest.getEndCreatedDate().isEmpty())
                p = cb.and(p,
                        cb.between(root.get(CREATED_DATE),
                                filterRequest.getStartCreatedDate(), filterRequest.getEndCreatedDate()));
            else if (!(filterRequest.getStartCreatedDate().isEmpty()))
                p = cb.and(p,
                        cb.greaterThanOrEqualTo(root.get(CREATED_DATE),
                                filterRequest.getStartCreatedDate()));
            else if (!(filterRequest.getEndCreatedDate().isEmpty()))
                p = cb.and(p,
                        cb.lessThanOrEqualTo(root.get(CREATED_DATE),

                                filterRequest.getEndCreatedDate()));
            if (!filterRequest.getCreatedBy().isEmpty()) {
                p = cb.and(p,
                        cb.equal(root.get("createdBy"), filterRequest.getCreatedBy()));
            }

            if (!filterRequest.getBrandId().isEmpty()) {
                p = cb.and(p,
                        cb.equal(root.get("brandId"), filterRequest.getBrandId()));
            }
            if (!filterRequest.getChannel().isEmpty()) {

                p = cb.and(p,
                        cb.equal(channel.get("channelName"), Channel.valueOf(filterRequest.getChannel())));
            }
            if (filterRequest.getSort().equals(SortEnum.ASC)) {
                cq.orderBy(cb.asc(root.get(CREATED_DATE)));
            } else {
                cq.orderBy(cb.desc(root.get(CREATED_DATE)));
            }
            return p;
        };
    }

And my service method...

public Page<TEST> filter(FilterRequest filterRequest) throws BaseException {
        try {
            log.info("Getting campaign for filterRequest : {} ", filterRequest);
            // Find Sorted Creatives By filterRequest
            Pageable pageable =
                    PageRequest.of(filterRequest.getPageNumber(), filterRequest.getPageSize());
            return repository.findAll(generateFilterTestQuery(filterRequest),pageable);
        } catch (IllegalArgumentException e) {
            log.error(e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }

The result I'm getting...

   "content": [
    {
      "id": 516,
      "name": "Tes",
      "createdBy": "test",
      "brandId": "1",
      "createdDate": 1671529546,
      "channels": [
        {
          "id": 312,
          "channelName": "TV1",
          "channelStatus": "DONE",
          "tvSet": [
            {
              "id": 312,
                "locations": [
                  {
                    "id": 302,
                    "isGeoLocation": true,
                    "cities": [
                      {
                        "id": 282,
                        "distanceUnit": "kilometer",
                      },
                      {
                        "id": 283,
                        "distanceUnit": "kilometer",
                      }
                    ],

    }

But I want to get results(channels ) that without getting tvSet array like in below

   "content": [
    {
      "id": 516,
      "name": "Tes",
      "createdBy": "test",
      "brandId": "1",
      "createdDate": 1671529546,
      "channels": [
        {
          "id": 312,
          "channelName": "TV1",
          "channelStatus": "DONE",
          "tvSet": [],

    }

Can someone please help me to resolve this issue?? Thank you!!


问:
how to write Foreach with out key in react js
i want to loop in this array, and i don't have key in array

my array

```<code>const array = ['name1','name2','name3']
</code>```

after that the proplem on console is

Warning: Each child in a list should have a unique "key" prop

my component

```<code>{
    items.map((item) => {
        return (
          <div className="flex-shrink-0 py-1">
            <button
              key={}
              onClick={() => onFillter(item)}
              type="button"
              className="... tailwind css"
            >
              {item}
            </button>
          </div>
       );
    })
}
</code>```

i try to added math.random() in key -> bad result
added number to array -> bad result

Body:
i want to loop in this array, and i don't have key in array

my array

const array = ['name1','name2','name3']

after that the proplem on console is

Warning: Each child in a list should have a unique "key" prop

my component

{
    items.map((item) => {
        return (

            <button
              key={}
              onClick={() => onFillter(item)}
              type="button"
              className="... tailwind css"
            >
              {item}
            </button>

       );
    })
}

i try to added math.random() in key -> bad result
added number to array -> bad result


问:
Is it possible to load build result in VS Output window?
I was been trying to switch IDEs.

What if I will want to load MISRA check result file to Visual Studio.

Is there any direct or simpler way?

Made indirect workaround:

```<code>var fso = new ActiveXObject("Scripting.FileSystemObject");
var rootPath = fso.GetFolder(".");
var cStat = rootPath.files;
for(var objEnum = new Enumerator(cStat); !objEnum.atEnd(); objEnum.moveNext()) {
    var strFileName = objEnum.item();
    if (strFileName.ShortName.length - strFileName.ShortName.toUpperCase().indexOf(".TXT") != 4) continue;
    //WScript.Echo(strFileName);
    break;
}
var ts = strFileName.OpenAsTextStream(1);
while(!ts.AtEndOfStream) {
    var textLine = ts.ReadLine();
    textLine = textLine.split('\t'); // IAR MISRA line: Description Rule Severity File:Line
    if (textLine[3])
    {
        var res = textLine[3].replace(/(.+):(\d+)/g, "$1($2)");
        if (textLine[2] == "Low")
        {
            res += ": warning " + textLine[1] + ": " + textLine[0];
        }
        else
        {
            res += ": error " + textLine[1] + ": " + textLine[0] + ' ' + textLine[2];
        }
        WScript.Echo(res);
    }
}
ts.Close();
</code>```

Using fake NMAKE project with build command like cscript /NoLogo PrintLog.js.

Now I can open files reported by MISRA in VS by copying export txt file to this project and running build.

Similar older IAR warning(s) filter used as pipe by command:

...\iarbuild "project.ewp" ReleaseCfg | cscript /NoLogo IARfilterPipe.js.

```<code>var fso = new ActiveXObject("Scripting.FileSystemObject");
var rootPath = fso.GetFolder(".") + '\\';
var x = oldBad(), skip = {};
for (i in x) skip[x[i]] = 1;
var stat = [0, 0], all = [], newWarnings = [];
do {
    var line = WScript.StdIn.ReadLine();
    if (line.indexOf('[') > 0) // possible warning line
    {
        all.push(line);
        line = line.replace(rootPath, "");
        var fit = 0;
        if (line.indexOf("Remark[") > -1)
        {
            fit++;
            stat[0]++;
            line = line
                .replace(/\d+>\s+/g, "")
                .replace(/Remark\[(\S+)\]:/g, "Warning $1:");
        }
        else if (line.indexOf("Error[") > -1)
        {
            fit++;
            stat[1]++;
            line = line
                .replace(/\d+>\s+/g, "")
                .replace(/Error\[(\S+)\]:/g, "Error $1:");
        }
        if (skip[line] != 1 && fit)
        {
            newWarnings.push(line);
            WScript.Echo('!' + line);
            var m = line.match(/\s*[^\s.]+\.(s|cpp|c)/g)
        } else {
            WScript.Echo('_' + line);
        }
    }
    else {
        var m = line.match(/\s*[^\s.]+\.(s|cpp|c)/g)
        if (m == null) // no name.ext
        {
            WScript.Echo(line);
        }
        else if (m.length == 1) // single filename
        {
            all.push(line);
        }
    }
} while (!WScript.StdIn.AtEndOfStream);
if (all.length)
{
    all = all.sort();
    writeFile("buildFiles.txt", all.join('\n'));
}
if (newWarnings.length)
{
    writeFile("newWarnings.txt", newWarnings.join('\n'));
    WScript.Echo("========== New warnings: ==========");
}
for(var l in newWarnings)
{
    WScript.Echo(newWarnings[l]);
}
if (stat[0] + stat[1])
{
    WScript.Echo("========== Build Result - Warnings " + stat[0] + " Errors " + stat[1] + " ==========");
}
WScript.Quit(0); // (do not work from file after Echo => -1)

function writeFile(filename, content)
{
    var TextStream = fso.CreateTextFile(filename);
    TextStream.Write(content);
    TextStream.Close()
}

function oldBad()
{
    return [
        'somefile.cpp(42) : Warning Pe340: value copied to temporary, reference to temporary used', ...
    ];
}
</code>```

Body:
I was been trying to switch IDEs.

What if I will want to load MISRA check result file to Visual Studio.

Is there any direct or simpler way?

Made indirect workaround:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var rootPath = fso.GetFolder(".");
var cStat = rootPath.files;
for(var objEnum = new Enumerator(cStat); !objEnum.atEnd(); objEnum.moveNext()) {
    var strFileName = objEnum.item();
    if (strFileName.ShortName.length - strFileName.ShortName.toUpperCase().indexOf(".TXT") != 4) continue;
    //WScript.Echo(strFileName);
    break;
}
var ts = strFileName.OpenAsTextStream(1);
while(!ts.AtEndOfStream) {
    var textLine = ts.ReadLine();
    textLine = textLine.split('\t'); // IAR MISRA line: Description Rule Severity File:Line
    if (textLine[3])
    {
        var res = textLine[3].replace(/(.+):(\d+)/g, "$1($2)");
        if (textLine[2] == "Low")
        {
            res += ": warning " + textLine[1] + ": " + textLine[0];
        }
        else
        {
            res += ": error " + textLine[1] + ": " + textLine[0] + ' ' + textLine[2];
        }
        WScript.Echo(res);
    }
}
ts.Close();

Using fake NMAKE project with build command like cscript /NoLogo PrintLog.js.

Now I can open files reported by MISRA in VS by copying export txt file to this project and running build.

Similar older IAR warning(s) filter used as pipe by command:

...\iarbuild "project.ewp" ReleaseCfg | cscript /NoLogo IARfilterPipe.js.

var fso = new ActiveXObject("Scripting.FileSystemObject");
var rootPath = fso.GetFolder(".") + '\\';
var x = oldBad(), skip = {};
for (i in x) skip[x[i]] = 1;
var stat = [0, 0], all = [], newWarnings = [];
do {
    var line = WScript.StdIn.ReadLine();
    if (line.indexOf('[') > 0) // possible warning line
    {
        all.push(line);
        line = line.replace(rootPath, "");
        var fit = 0;
        if (line.indexOf("Remark[") > -1)
        {
            fit++;
            stat[0]++;
            line = line
                .replace(/\d+>\s+/g, "")
                .replace(/Remark\[(\S+)\]:/g, "Warning $1:");
        }
        else if (line.indexOf("Error[") > -1)
        {
            fit++;
            stat[1]++;
            line = line
                .replace(/\d+>\s+/g, "")
                .replace(/Error\[(\S+)\]:/g, "Error $1:");
        }
        if (skip[line] != 1 && fit)
        {
            newWarnings.push(line);
            WScript.Echo('!' + line);
            var m = line.match(/\s*[^\s.]+\.(s|cpp|c)/g)
        } else {
            WScript.Echo('_' + line);
        }
    }
    else {
        var m = line.match(/\s*[^\s.]+\.(s|cpp|c)/g)
        if (m == null) // no name.ext
        {
            WScript.Echo(line);
        }
        else if (m.length == 1) // single filename
        {
            all.push(line);
        }
    }
} while (!WScript.StdIn.AtEndOfStream);
if (all.length)
{
    all = all.sort();
    writeFile("buildFiles.txt", all.join('\n'));
}
if (newWarnings.length)
{
    writeFile("newWarnings.txt", newWarnings.join('\n'));
    WScript.Echo("========== New warnings: ==========");
}
for(var l in newWarnings)
{
    WScript.Echo(newWarnings[l]);
}
if (stat[0] + stat[1])
{
    WScript.Echo("========== Build Result - Warnings " + stat[0] + " Errors " + stat[1] + " ==========");
}
WScript.Quit(0); // (do not work from file after Echo => -1)

function writeFile(filename, content)
{
    var TextStream = fso.CreateTextFile(filename);
    TextStream.Write(content);
    TextStream.Close()
}

function oldBad()
{
    return [
        'somefile.cpp(42) : Warning Pe340: value copied to temporary, reference to temporary used', ...
    ];
}


问:
R: Too big legends in a bar plot
I have this plot that looks awful because the legends on the left and right and bottom are too big. I tried to make them smaller with legend.title = element_text(size=7), but I managed to do it only to the right side's "Answer" legend. I want all the text in the figure as the same size (7) "Answer" is.

Apparently I put that code to wrong places. I get the error of unused argument: Error in scale_y_continuous(name = "Percentage", breaks = seq(from = 0,  :  unused argument (legend.title = element_text(size = 7)). So where to insert that code, or do I need another code?

```<code>mydata %>%

  mutate(
    variable = recode(
      variable,
      'item3' = '
      Very long item name here')) %>%

  drop_na() %>%
  ggplot(mapping = aes(x = variable)) +
  geom_bar(aes(fill = value),
           position = 'fill',
           width = 0.30)+
  scale_y_continuous(name = 'Percentage',
                     breaks = seq(from = 0, to = 1, by = 0.2),
                     minor_breaks = seq(from = 0, to = 1, by = 0.1),
                     labels = seq(from = 0, to = 100, by = 20),
                     expand = c(0,0)) +
  xlab( element_blank() ) +
  scale_fill_manual(
    values = c(fioh_colors$fioh_blue_40,
               fioh_colors$fioh_blue_60,
               fioh_colors$fioh_blue_80,
               fioh_colors$fioh_blue_100,
               fioh_colors$fioh_turq_20
    ),
    labels = c(
      'yes',
      'no',
      'maybe'
    ),
    drop = FALSE
  ) +

  guides(
    fill = guide_legend(title = 'Answer')
  ) + theme(panel.background = element_blank(),
            legend.title = element_text(size=7),
            plot.margin = margin(t = 30, r =  30, b = 20, l = 0),
            axis.ticks.y = element_blank(),
            panel.grid.major = element_line(colour = 'grey'),
            axis.ticks.x = element_line(colour = 'grey'),
            panel.grid.minor = element_line(colour = 'lightgrey'),
            axis.text.y = element_text(
              size = 11,
              face = 'bold',
              hjust = 0
            )) +
  coord_flip()
</code>```

Data

```<code>structure(list(variable = c("item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3"), value = structure(c(1L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 3L, 2L, 2L, 1L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L,
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L), .Label = c("1",
"2", "3"), class = c("ordered", "factor"))), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -147L))```
```

Title: R: Too big legends in a bar plot

Body:
I have this plot that looks awful because the legends on the left and right and bottom are too big. I tried to make them smaller with legend.title = element_text(size=7), but I managed to do it only to the right side's "Answer" legend. I want all the text in the figure as the same size (7) "Answer" is.

Apparently I put that code to wrong places. I get the error of unused argument: Error in scale_y_continuous(name = "Percentage", breaks = seq(from = 0,  :  unused argument (legend.title = element_text(size = 7)). So where to insert that code, or do I need another code?

mydata %>%

  mutate(
    variable = recode(
      variable,
      'item3' = '
      Very long item name here')) %>%

  drop_na() %>%
  ggplot(mapping = aes(x = variable)) +
  geom_bar(aes(fill = value),
           position = 'fill',
           width = 0.30)+
  scale_y_continuous(name = 'Percentage',
                     breaks = seq(from = 0, to = 1, by = 0.2),
                     minor_breaks = seq(from = 0, to = 1, by = 0.1),
                     labels = seq(from = 0, to = 100, by = 20),
                     expand = c(0,0)) +
  xlab( element_blank() ) +
  scale_fill_manual(
    values = c(fioh_colors$fioh_blue_40,
               fioh_colors$fioh_blue_60,
               fioh_colors$fioh_blue_80,
               fioh_colors$fioh_blue_100,
               fioh_colors$fioh_turq_20
    ),
    labels = c(
      'yes',
      'no',
      'maybe'
    ),
    drop = FALSE
  ) +

  guides(
    fill = guide_legend(title = 'Answer')
  ) + theme(panel.background = element_blank(),
            legend.title = element_text(size=7),
            plot.margin = margin(t = 30, r =  30, b = 20, l = 0),
            axis.ticks.y = element_blank(),
            panel.grid.major = element_line(colour = 'grey'),
            axis.ticks.x = element_line(colour = 'grey'),
            panel.grid.minor = element_line(colour = 'lightgrey'),
            axis.text.y = element_text(
              size = 11,
              face = 'bold',
              hjust = 0
            )) +
  coord_flip()

Data

structure(list(variable = c("item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3", "item3", "item3", "item3", "item3",
"item3", "item3", "item3"), value = structure(c(1L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 3L, 2L, 2L, 1L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L,
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L), .Label = c("1",
"2", "3"), class = c("ordered", "factor"))), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -147L))```


问:
Set use_deprecated_int96_timestamps and engine to a spark dataframe on databricks
I am using databricks to write my delta tables in this way:

```<code> df.write \
  .format("delta") \
  .mode("overwrite") \
  .partitionBy("DT_INSERT_PART","FILE_NAME_PART") \
  .save(f"{my_path}")
</code>```

When on DataFactory I use the copydata command with polybase I get the following error.

```<code>ErrorCode=UserErrorSqlDWCopyCommandError,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=SQL DW Copy Command operation failed with error 'HdfsBridge::recordReaderFillBuffer - Unexpected error encountered filling record reader buffer: ClassCastException: class java.lang.Integer cannot be cast to class parquet.io.api.Binary (java.lang.Integer is in module java.base of loader 'bootstrap'; parquet.io.api.Binary is in unnamed module of loader 'app')',Source=Microsoft.DataTransfer.ClientLibrary,''Type=System.Data.SqlClient.SqlException,Message=HdfsBridge::recordReaderFillBuffer - Unexpected error encountered filling record reader buffer: ClassCastException: class java.lang.Integer cannot be cast to class parquet.io.api.Binary (java.lang.Integer is in module java.base of loader 'bootstrap'; parquet.io.api.Binary is in unnamed module of loader 'app'),Source=.Net SqlClient Data Provider,SqlErrorNumber=106000,Class=16,ErrorCode=-2146232060,State=1,Errors=[{Class=16,Number=106000,State=1,Message=HdfsBridge::recordReaderFillBuffer - Unexpected error encountered filling record reader buffer: ClassCastException: class java.lang.Integer cannot be cast to class parquet.io.api.Binary (java.lang.Integer is in module java.base of loader 'bootstrap'; parquet.io.api.Binary is in unnamed module of loader 'app'),},],'
</code>```

I tried using the '.to_parquet' function found on pandas to try to solve the problem. I think I need to use use_deprecated_int96_timestamps=True and engine='pyarrow'. I have a spark format dataframe so I don't think it is convenient to convert the format, also I would not be able to replicate the settings mentioned above (such as."partitionBy("DT_INSERT_PART", "FILE_NAME_PART") ")

```<code>df = df.to_parquet('samplefile.parquet',engine='pyarrow',use_deprecated_int96_timestamps=True)
</code>```

How could I enter these settings without having to convert my dataframe then continuing to use spark dataframe?

Body:
I am using databricks to write my delta tables in this way:

 df.write \
  .format("delta") \
  .mode("overwrite") \
  .partitionBy("DT_INSERT_PART","FILE_NAME_PART") \
  .save(f"{my_path}")

When on DataFactory I use the copydata command with polybase I get the following error.

ErrorCode=UserErrorSqlDWCopyCommandError,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=SQL DW Copy Command operation failed with error 'HdfsBridge::recordReaderFillBuffer - Unexpected error encountered filling record reader buffer: ClassCastException: class java.lang.Integer cannot be cast to class parquet.io.api.Binary (java.lang.Integer is in module java.base of loader 'bootstrap'; parquet.io.api.Binary is in unnamed module of loader 'app')',Source=Microsoft.DataTransfer.ClientLibrary,''Type=System.Data.SqlClient.SqlException,Message=HdfsBridge::recordReaderFillBuffer - Unexpected error encountered filling record reader buffer: ClassCastException: class java.lang.Integer cannot be cast to class parquet.io.api.Binary (java.lang.Integer is in module java.base of loader 'bootstrap'; parquet.io.api.Binary is in unnamed module of loader 'app'),Source=.Net SqlClient Data Provider,SqlErrorNumber=106000,Class=16,ErrorCode=-2146232060,State=1,Errors=[{Class=16,Number=106000,State=1,Message=HdfsBridge::recordReaderFillBuffer - Unexpected error encountered filling record reader buffer: ClassCastException: class java.lang.Integer cannot be cast to class parquet.io.api.Binary (java.lang.Integer is in module java.base of loader 'bootstrap'; parquet.io.api.Binary is in unnamed module of loader 'app'),},],'

I tried using the '.to_parquet' function found on pandas to try to solve the problem. I think I need to use use_deprecated_int96_timestamps=True and engine='pyarrow'. I have a spark format dataframe so I don't think it is convenient to convert the format, also I would not be able to replicate the settings mentioned above (such as."partitionBy("DT_INSERT_PART", "FILE_NAME_PART") ")

df = df.to_parquet('samplefile.parquet',engine='pyarrow',use_deprecated_int96_timestamps=True)

How could I enter these settings without having to convert my dataframe then continuing to use spark dataframe?


问:
How can I fix android gradle build making strange error
I made a file manager app and now I am trying to build it to an APK. The problem is that every time I try to build it returns this error:

error: failed processing manifest.

here's my manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:requestLegacyExternalStorage="true"
        android:label="FileManager"
        android:supportsRtl="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:theme="@style/Theme.FileManager"
        tools:targetApi="31">
        <activity
            android:name=".FileListActivity"
            android:exported="false">
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>
```

I tried everything, I found similar questions in the internet but none of them works for me, can someone please help.

Body:
I made a file manager app and now I am trying to build it to an APK. The problem is that every time I try to build it returns this error:

error: failed processing manifest.

here's my manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:requestLegacyExternalStorage="true"
        android:label="FileManager"
        android:supportsRtl="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:theme="@style/Theme.FileManager"
        tools:targetApi="31">
        <activity
            android:name=".FileListActivity"
            android:exported="false">
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

I tried everything, I found similar questions in the internet but none of them works for me, can someone please help.


问:
How to automatize image search with 2 different types of queries?
I need to do some data scraping and it would be very useful for me if there was a way to implement an algorithm that downloads a subset of images matching a certain query, but only within a specific 'root' website (for example all images in www.example.com including all subdirectories such as www.example.com/sub1).

I already know that it might be impossible to find all subdirectories in a root website unless they're listed somewhere. Since I do not know all the subdirectories I think i should avoid looping over subdirectories and extracting all images (with an online image extractor for instance).

So in my opinion the easiest thing to do is to let google do most of the work so that it outputs all (or maybe most) of the images that are contained in any subdirectory of the 'root' and then do a query.

The problem is thus divided in 2 parts:

Get all the images from google image search that come from a specific website

Only get the subset of images matching the query. This I guess would possible with some AI recognition (all images that are labeled as animals, or buildings and so on)

I know that this is a very broad question so i do not expect any answers with code.

What I would like to know is:

Do you think it is even possible to do that?

What programs would you suggest using for this purpose (both for the search and the image recognition)

If you think this question belongs more to another stack site let me know, I'm trying my best to be compliant with the rules. Thanks.


问:
How to decode socket response?
I am try to decode socket response from web source, but I can to decode only 50% of message.
It looks strange, because it should be a full message decompress, if it can decompress some socket response, but maybe I wrong. Any help will be greatly appreciated!

```<code>require "faye/websocket"
require "eventmachine"
require "permessage_deflate"
require 'zlib'
require 'stringio'

EM.run do
  ws = Faye::WebSocket::Client.new("wss://wss.winline.ru/data_ng?", [], :extensions => [PermessageDeflate])

  ws.on :open do |event|
    p [:open]
    ws.send "lang"
    ws.send "AQ=="
    ws.send "data"
    ws.send "WINLINE"
    ws.send "getdate"
    ws.send "no_fordata"

  end

  ws.on :message do |event|
    gz = Zlib::GzipReader.new(StringIO.new(event.data.pack('C*')))
    puts gz.read
  end

  ws.on :close do |event|
    p [:close, event.code, event.reason]
    ws = nil
  end
end
</code>```

I have receive the following data:

```<code>�$��$^���60.5
�$��$^��62.5'!�$i#�$^����31.5�I�$�6�$^���9.5�3�$^���11.5�   �$^��10�3�$$W�$^����80:3ূ$�m���&ާ�$�m�id�rݧ�$�m�t

�$''�=�v�p��a��0ȣc�Cincinnati BearcatsDetroit Mercy Titans��}$1'':%���}$1''�G���}$1'n|
</code>```

As u can see, some parts of the message are decodable and other is still not.

Without decompress, I have this msg from sock:

```<code>[242, 204, 179, 144, 33, 112, 239, 219, 8, 118, 124, 89, 134, 218, 170, 173, 183, 173, 126, 59, 167, 131, 63, 254, 48, 115, 255, 123, 7, 161, 157, 64, 184, 79, 95, 202, 7, 203, 254, 172, 245, 49, 72, 63, 3, 5, 128, 62, 243, 77, 202, 4, 219, 80, 245, 92, 169, 237, 174, 85, 242, 165, 252, 180, 73, 54, 149, 19, 245, 163, 88, 212, 49, 186, 65, 111, 156, 215, 136, 53, 70, 54, 205, 33, 147, 72, 255, 36, 246, 167, 135, 253, 65, 163, 224, 36, 28, 78, 38, 227, 165, 7, 191, 246, 98, 255, 235, 195, 126, 55, 101, 38, 246, 68, 188, 252, 63, 92, 112, 93, 239, 36, 118, 2, 0]
</code>```

I think, this source are using pako to compress their data socket.

Title: How to decode socket response?

Body:
I am try to decode socket response from web source, but I can to decode only 50% of message.
It looks strange, because it should be a full message decompress, if it can decompress some socket response, but maybe I wrong. Any help will be greatly appreciated!

require "faye/websocket"
require "eventmachine"
require "permessage_deflate"
require 'zlib'
require 'stringio'

EM.run do
  ws = Faye::WebSocket::Client.new("wss://wss.winline.ru/data_ng?", [], :extensions => [PermessageDeflate])

  ws.on :open do |event|
    p [:open]
    ws.send "lang"
    ws.send "AQ=="
    ws.send "data"
    ws.send "WINLINE"
    ws.send "getdate"
    ws.send "no_fordata"

  end

  ws.on :message do |event|
    gz = Zlib::GzipReader.new(StringIO.new(event.data.pack('C*')))
    puts gz.read
  end

  ws.on :close do |event|
    p [:close, event.code, event.reason]
    ws = nil
  end
end

I have receive the following data:

�$��$^���60.5
�$��$^��62.5'!�$i#�$^����31.5�I�$�6�$^���9.5�3�$^���11.5�   �$^��10�3�$$W�$^����80:3ূ$�m���&ާ�$�m�id�rݧ�$�m�t

�$''�=�v�p��a��0ȣc�Cincinnati BearcatsDetroit Mercy Titans��}$1'':%���}$1''�G���}$1'n|

As u can see, some parts of the message are decodable and other is still not.

Without decompress, I have this msg from sock:

[242, 204, 179, 144, 33, 112, 239, 219, 8, 118, 124, 89, 134, 218, 170, 173, 183, 173, 126, 59, 167, 131, 63, 254, 48, 115, 255, 123, 7, 161, 157, 64, 184, 79, 95, 202, 7, 203, 254, 172, 245, 49, 72, 63, 3, 5, 128, 62, 243, 77, 202, 4, 219, 80, 245, 92, 169, 237, 174, 85, 242, 165, 252, 180, 73, 54, 149, 19, 245, 163, 88, 212, 49, 186, 65, 111, 156, 215, 136, 53, 70, 54, 205, 33, 147, 72, 255, 36, 246, 167, 135, 253, 65, 163, 224, 36, 28, 78, 38, 227, 165, 7, 191, 246, 98, 255, 235, 195, 126, 55, 101, 38, 246, 68, 188, 252, 63, 92, 112, 93, 239, 36, 118, 2, 0]

I think, this source are using pako to compress their data socket.


问:
Can we unstitch a panorama into component images?
Panorama images can be made by stitching multiple images together.

Can this be undone?

Can a panorama be transformed into multiple not warped images?


问:
ERROR: Unable to start debugging. Unexpected LLDB output from command "-exec-run". When trying to debug C++ code in VSCode
I started working on a beginners C++ course for game dev and last week the debug ran fine to run my code. Now, all of a sudden, I get this error when running debug

```<code>Warning: Debuggee TargetArchitecture not detected, assuming x86_64.
ERROR: Unable to start debugging. Unexpected LLDB output from command "-exec-run". process exited with status -1 (attach failed (Not allowed to attach to process.  Look in the console messages (Console.app), near the debugserver entries, when the attach failed.  The subsystem that denied the attach permission will likely have logged an informative message about why it was denied.))
The program '/Users/bcarson/Documents/GameDev/dapper-dasher/main' has exited with code 42 (0x0000002a).
</code>```

I haven't changed anything only created a new project, and now my previous project won't run either. So confused, much frustrated, many annoyed.

I searched through the interwebs and found some related articles - most dealing with Macs running the M1 chip (I have an Intel chip) but tried their solution anyways, which was installing CodeLLDB extension on my VSCode. I added a config to my launch.json file for a CodeLLDB: Launch option and updated the program to "${workspaceFolder}/main.cpp"

launch.json file:

```<code>{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
      "version": "0.2.0",
      "configurations": [
        {
          "type": "lldb",
          "request": "launch",
          "name": "Launch",
          "program": "${workspaceFolder}/main.cpp",
          "args": [],
          "cwd": "${workspaceFolder}"
        },
        {
          "name": "Debug",
          "type": "cppdbg",
          "request": "launch",
          "program": "${workspaceFolder}/${fileBasenameNoExtension}",
          "args": [],
          "stopAtEntry": false,
          "cwd": "${workspaceFolder}",
          "environment": [],
          "externalConsole": false,
          "MIMode": "gdb",
          "setupCommands": [
            {
              "description": "Enable pretty-printing for gdb",
              "text": "-enable-pretty-printing",
              "ignoreFailures": false
            }
          ],
          "windows": {
            "miDebuggerPath": "C:/raylib/w64devkit/bin/gdb.exe",
          },
          "osx": {
            "MIMode": "lldb"
          },
          "linux": {
            "miDebuggerPath": "/usr/bin/gdb",
          },
          "preLaunchTask": "build debug"
        },
        {
          "name": "Run",
          "type": "cppdbg",
          "request": "launch",
          "args": [],
          "stopAtEntry": false,
          "cwd": "${workspaceFolder}",
          "environment": [],
          "externalConsole": false,
          "program": "${workspaceFolder}/${fileBasenameNoExtension}",
          "MIMode": "gdb",
          "windows": {
            "program": "${workspaceFolder}/${fileBasenameNoExtension}.exe",
            "miDebuggerPath": "C:/raylib/w64devkit/bin/gdb.exe"
          },
          "osx": {
            "MIMode": "lldb"
          },
          "linux": {
            "miDebuggerPath": "/usr/bin/gdb"
          },
          "preLaunchTask": "build release",
        }
      ]
    }
</code>```

But I am still getting the same error. I tried removing all other launch.json configs but VSCode REALLY didn't like that.

Here are my mac specs:

```<code>macOS Monterey
Version 12.6.1

MacBook Pro (13-inch, 2019)
Processor 1.4 GHz Quad-Core Intel Core i5
</code>```

Here are my VSCode specs:

```<code>Version: 1.74.1
Commit: 1ad8d514439d5077d2b0b7ee64d2ce82a9308e5a
Date: 2022-12-14T10:33:40.793Z
Electron: 19.1.8
Chromium: 102.0.5005.167
Node.js: 16.14.2
V8: 10.2.154.15-electron.0
OS: Darwin x64 21.6.0
Sandboxed: Yes
</code>```

Here is my main.cpp file:

```<code>#include "raylib.h"

int main()
{
   //window dimensions
   const int windowWidth = 1300;
   const int windowHeight = 1300;
   //initialize the window
   InitWindow(windowWidth, windowHeight, "That Dasher Sure is Dapper!");

   SetTargetFPS(60);
   while (!WindowShouldClose())
   {
      //start drawing
      BeginDrawing();
      ClearBackground(WHITE);

      //stop drawing
      EndDrawing();
   }
   CloseWindow();
}
</code>```

Body:
I started working on a beginners C++ course for game dev and last week the debug ran fine to run my code. Now, all of a sudden, I get this error when running debug

Warning: Debuggee TargetArchitecture not detected, assuming x86_64.
ERROR: Unable to start debugging. Unexpected LLDB output from command "-exec-run". process exited with status -1 (attach failed (Not allowed to attach to process.  Look in the console messages (Console.app), near the debugserver entries, when the attach failed.  The subsystem that denied the attach permission will likely have logged an informative message about why it was denied.))
The program '/Users/bcarson/Documents/GameDev/dapper-dasher/main' has exited with code 42 (0x0000002a).

I haven't changed anything only created a new project, and now my previous project won't run either. So confused, much frustrated, many annoyed.

I searched through the interwebs and found some related articles - most dealing with Macs running the M1 chip (I have an Intel chip) but tried their solution anyways, which was installing CodeLLDB extension on my VSCode. I added a config to my launch.json file for a CodeLLDB: Launch option and updated the program to "${workspaceFolder}/main.cpp"

launch.json file:

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
      "version": "0.2.0",
      "configurations": [
        {
          "type": "lldb",
          "request": "launch",
          "name": "Launch",
          "program": "${workspaceFolder}/main.cpp",
          "args": [],
          "cwd": "${workspaceFolder}"
        },
        {
          "name": "Debug",
          "type": "cppdbg",
          "request": "launch",
          "program": "${workspaceFolder}/${fileBasenameNoExtension}",
          "args": [],
          "stopAtEntry": false,
          "cwd": "${workspaceFolder}",
          "environment": [],
          "externalConsole": false,
          "MIMode": "gdb",
          "setupCommands": [
            {
              "description": "Enable pretty-printing for gdb",
              "text": "-enable-pretty-printing",
              "ignoreFailures": false
            }
          ],
          "windows": {
            "miDebuggerPath": "C:/raylib/w64devkit/bin/gdb.exe",
          },
          "osx": {
            "MIMode": "lldb"
          },
          "linux": {
            "miDebuggerPath": "/usr/bin/gdb",
          },
          "preLaunchTask": "build debug"
        },
        {
          "name": "Run",
          "type": "cppdbg",
          "request": "launch",
          "args": [],
          "stopAtEntry": false,
          "cwd": "${workspaceFolder}",
          "environment": [],
          "externalConsole": false,
          "program": "${workspaceFolder}/${fileBasenameNoExtension}",
          "MIMode": "gdb",
          "windows": {
            "program": "${workspaceFolder}/${fileBasenameNoExtension}.exe",
            "miDebuggerPath": "C:/raylib/w64devkit/bin/gdb.exe"
          },
          "osx": {
            "MIMode": "lldb"
          },
          "linux": {
            "miDebuggerPath": "/usr/bin/gdb"
          },
          "preLaunchTask": "build release",
        }
      ]
    }

But I am still getting the same error. I tried removing all other launch.json configs but VSCode REALLY didn't like that.

Here are my mac specs:

macOS Monterey
Version 12.6.1

MacBook Pro (13-inch, 2019)
Processor 1.4 GHz Quad-Core Intel Core i5

Here are my VSCode specs:

Version: 1.74.1
Commit: 1ad8d514439d5077d2b0b7ee64d2ce82a9308e5a
Date: 2022-12-14T10:33:40.793Z
Electron: 19.1.8
Chromium: 102.0.5005.167
Node.js: 16.14.2
V8: 10.2.154.15-electron.0
OS: Darwin x64 21.6.0
Sandboxed: Yes

Here is my main.cpp file:

#include "raylib.h"

int main()
{
   //window dimensions
   const int windowWidth = 1300;
   const int windowHeight = 1300;
   //initialize the window
   InitWindow(windowWidth, windowHeight, "That Dasher Sure is Dapper!");

   SetTargetFPS(60);
   while (!WindowShouldClose())
   {
      //start drawing
      BeginDrawing();
      ClearBackground(WHITE);

      //stop drawing
      EndDrawing();
   }
   CloseWindow();
}


问:
Datatype for Object with empty array at the end in typescript
'interface HeaderSearchProps'</p>
```<code>  links: {
    link: string;
    label: string;
    links: { link: string; label: string }[];
  }[];
}```

**how to define data for this type,I am using matine ui and this type gives me an error when i declare an object as this type**

"example data specified"
</code>```
<p>{link: "./about", label: "About", links:{link: "./about" , label: "About"}}</p>
```<code>"Is this a valid data for the type specified above"
</code>```

Body:
'interface HeaderSearchProps'

  links: {
    link: string;
    label: string;
    links: { link: string; label: string }[];
  }[];
}```

**how to define data for this type,I am using matine ui and this type gives me an error when i declare an object as this type**

"example data specified"

{link: "./about", label: "About", links:{link: "./about" , label: "About"}}

"Is this a valid data for the type specified above"


问:
MQL5 CopyBuffer - How to get Values
a long time ago I found a perfect Indicator called Supertrend, for my needs in the web.
It has some additional features as the standard one.

Here is no Fileupload for me, so i will give you the important lines of Code out of this. Importand only in my eyes now ... Please ask for the full code if needed.

As you can see, there are 4 Buffer´s for individual values.

double UpBuffer[]; double DnBuffer[]; double BuyBuffer[]; double
SellBuffer[];

int OnInit(){ SetIndexBuffer(0,UpBuffer,INDICATOR_DATA);
SetIndexBuffer(1,DnBuffer,INDICATOR_DATA);
SetIndexBuffer(2,BuyBuffer,INDICATOR_DATA);
SetIndexBuffer(3,SellBuffer,INDICATOR_DATA);

In the past i worked with standards like iMA and this was easy to understand.
Just write one line of Code in your special function like:

void CheckSomething(){ // deklare Variables and use:
ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0); }

I followed the last 3 days reading the Documentation and searching google for understanding "iCustom" and "CopyBuffer".

It seems so, that there is no way for just a one-liner in a function ...

Ok, so i followed the Documentation.

First i created the iCustom and this works withoud errors!
I think this will work as is should.

input ENUM_TIMEFRAMES indi_ST_Timeframe = PERIOD_M1;  // Timeframe for
Supertrend enum ENUM_ST_Mode { SuperTrend=0,// SuperTrend NewWay,

// NewWay Visual,      // Visual ExpertSignal // ExpertSignal };

input ENUM_ST_Mode   indi_ST_Mode = SuperTrend;   // SuperTrend input
int            indi_ST_Period       =  10; // ATR Period input double
indi_ST_Multiplier   = 3.0; // ATR Multiplier input int

indi_ST_Shift        =   0; // Shift // Internal Variables: string

indi_ST_ShortName    = "SuperTrend"; int OnInit(){ indi_ST_HANDLE =
iCustom(_Symbol,indi_ST_Timeframe,indi_ST_ShortName,indi_ST_Mode,indi_ST_Period,indi_ST_Multiplier,indi_ST_Shift);

return(INIT_SUCCEEDED); }

Next i am struggling huge ...
I did not really understand "CopyBuffer"!

int indi_ST_HANDLE; void ST_Print(){ double   indi_ST_Up     = NULL;
double   indi_ST_Down   = NULL; double   indi_ST_Buy    = NULL; double
indi_ST_Sell   = NULL;

/* // first try to get all 4 Buffer directly into a variable
indi_ST_Up   = CopyBuffer(indi_ST_HANDLE,0,0,0,indi_ST_Buffer);
indi_ST_Down = CopyBuffer(indi_ST_HANDLE,1,0,1,indi_ST_Buffer);
indi_ST_Buy  = CopyBuffer(indi_ST_HANDLE,2,0,2,indi_ST_Buffer);
indi_ST_Sell = CopyBuffer(indi_ST_HANDLE,3,0,3,indi_ST_Buffer);

Print ("ST-Up   = ", indi_ST_Up); Print ("ST-Down = ", indi_ST_Down);
Print ("ST-Buy  = ", indi_ST_Buy); Print ("ST-Sell = ", indi_ST_Sell);
*/

// copy complete Buffers to an Array named "indi_ST_Buffer"
CopyBuffer(indi_ST_HANDLE,3,0,3,indi_ST_Buffer);  //--- set indexing
of elements as series ArraySetAsSeries(indi_ST_Buffer,true); //
true/false ??? I did tested both with no change.

indi_ST_Up   = indi_ST_Buffer[0]; indi_ST_Down = indi_ST_Buffer[1];
//indi_ST_Buy  = indi_ST_Buffer[2]; //indi_ST_Sell =
indi_ST_Buffer[3];

Print ("ST-Up   = ", indi_ST_Up); Print ("ST-Down = ", indi_ST_Down);
Print ("ST-Buy  = ", indi_ST_Buy); Print ("ST-Sell = ", indi_ST_Sell);

Print ("- - - - - - - - - - - - - - - - - - - - - - -"); }

In the past i have added code as JavaScript/HTML/CSS that was not ok for moderators.
Now i tried the only other was as blockcode.
This will look not comfortable for me, but if the moderator need code on a different way ... This must be ok.

You realize that my last code is just "Try & Error" as i did not understand the function.
What ever i tried to print my variables, i got just crap.

Can you help me to understand what CopyBuffer will really need?
Or can you explain me, where i am struggling?

Thank you a lot.

Title: MQL5 CopyBuffer - How to get Values


问:
"Undefined method 'createToken'" in UserAuthController in laravel 9
I'm trying to use passport in laravel and I'm following this tutorial: https://blog.logrocket.com/laravel-passport-a-tutorial-and-example-build/. But in step 4 I come across an error creating the UserAuthCotroller.

Here is my UserAuthController:

```<code><?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;

class UserAuthController extends Controller
{
    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed'
        ]);

        $data['password'] = bcrypt($request->password);

        $user = User::create($data);

        $token = $user->createToken('API Token')->accessToken;

        return response([ 'user' => $user, 'token' => $token]);
    }

    public function login(Request $request)
    {
        $data = $request->validate([
            'email' => 'email|required',
            'password' => 'required'
        ]);

        if (!auth()->attempt($data)) {
            return response(['error_message' => 'Incorrect Details.
            Please try again']);
        }

        $token = auth()->user()->createToken('API Token')->accessToken;

        return response(['user' => auth()->user(), 'token' => $token]);

    }
}
</code>```

I have searched and some people say that I just have to add this lines to my user.php file:

```<code>use HasApiTokens, HasFactory, Notifiable;

use Laravel\Passport\HasApiTokens;
</code>```

Here is my user.php file

```<code><?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}
</code>```

Here is the error

```<code>[{
    "resource": "/c:/xampp/htdocs/application-example/app/Http/Controllers/Auth/UserAuthController.php",
    "owner": "_generated_diagnostic_collection_name_#1",
    "code": "1013",
    "severity": 8,
    "message": "Undefined method 'createToken'.",
    "source": "intelephense",
    "startLineNumber": 40,
    "startColumn": 34,
    "endLineNumber": 40,
    "endColumn": 45
}]
</code>```

Here is my config/auth.php

```<code><?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that each reset token will be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

</code>```

I have done that but still doesn`t work. Any idea?

Body:
I'm trying to use passport in laravel and I'm following this tutorial: https://blog.logrocket.com/laravel-passport-a-tutorial-and-example-build/. But in step 4 I come across an error creating the UserAuthCotroller.

Here is my UserAuthController:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;

class UserAuthController extends Controller
{
    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed'
        ]);

        $data['password'] = bcrypt($request->password);

        $user = User::create($data);

        $token = $user->createToken('API Token')->accessToken;

        return response([ 'user' => $user, 'token' => $token]);
    }

    public function login(Request $request)
    {
        $data = $request->validate([
            'email' => 'email|required',
            'password' => 'required'
        ]);

        if (!auth()->attempt($data)) {
            return response(['error_message' => 'Incorrect Details.
            Please try again']);
        }

        $token = auth()->user()->createToken('API Token')->accessToken;

        return response(['user' => auth()->user(), 'token' => $token]);

    }
}

I have searched and some people say that I just have to add this lines to my user.php file:

use HasApiTokens, HasFactory, Notifiable;

use Laravel\Passport\HasApiTokens;

Here is my user.php file

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Here is the error

[{
    "resource": "/c:/xampp/htdocs/application-example/app/Http/Controllers/Auth/UserAuthController.php",
    "owner": "_generated_diagnostic_collection_name_#1",
    "code": "1013",
    "severity": 8,
    "message": "Undefined method 'createToken'.",
    "source": "intelephense",
    "startLineNumber": 40,
    "startColumn": 34,
    "endLineNumber": 40,
    "endColumn": 45
}]

Here is my config/auth.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that each reset token will be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

I have done that but still doesn`t work. Any idea?


问:
How to trigger karate gatling distributed test?
We want to run karate gatling distributed mode to test API performance.

Here is the performance test class for master node

```<code>public class TestPerformanceDocker {
    @Test
    void test(){
        //master node server ip
        String serverUrl= "127.0.0.1";
        String threads = System.getProperty("THREADS");
        String rampDuration = System.getProperty("RAMP_DURATION");
        String constantDuration =System.getProperty("CONST_DURATION");
        //slave node amounts
        Integer executorCount=Integer.parseInt(System.getProperty("NODES_COUNT"));
        String cmd ="mvn gatling:test -DTHREADS="+threads+" -DRAMP_DURATION="+rampDuration+" -DCONST_DURATION="+constantDuration+"";
        GatlingMavenJobConfig config = new GatlingMavenJobConfig(executorCount, serverUrl, 9090) {};
        config.setMainCommand(cmd);
        JobManager<Integer> manager = new JobManager(config);
        manager.start();
        manager.waitForCompletion();
    }
}
</code>```

Start the master node with cmd :
docker container run -d -t --network=karate_network --name karate_boss --privileged karate mvn clean test -Dtest=TestPerformanceDocker -DTHREADS=3 -DRAMP_DURATION=600 -DCONST_DURATION=600

Face with error log below:

2022-12-20 21:55:35 13:55:35.259 [main] DEBUG com.intuit.karate.http.HttpServer - server started: f224cb587867:9090
2022-12-20 21:55:35 13:55:35.261 [main] DEBUG com.intuit.karate.job.JobManager - added to queue: 1
2022-12-20 21:55:35 13:55:35.262 [main] DEBUG com.intuit.karate.job.JobManager - added to queue: 2
2022-12-20 21:55:35 13:55:35.265 [main] DEBUG com.intuit.karate.job.JobManager - added to queue: 3
2022-12-20 21:55:35 13:55:35.283 [1671544535281] DEBUG com.intuit.karate - command: [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome], working dir: null
2022-12-20 21:55:35 13:55:35.285 [1671544535281] DEBUG com.intuit.karate - command: [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome], working dir: null
2022-12-20 21:55:35 13:55:35.285 [1671544535281] DEBUG com.intuit.karate - command: [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome], working dir: null
2022-12-20 21:55:35 13:55:35.348 [1671544535281-out] DEBUG com.intuit.karate - docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
2022-12-20 21:55:35 13:55:35.349 [1671544535281-out] DEBUG com.intuit.karate - See 'docker run --help'.
2022-12-20 21:55:35 13:55:35.357 [1671544535281] WARN  com.intuit.karate.shell.Command - exit code was non-zero: 125 - [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome] working dir: null
2022-12-20 21:55:35 13:55:35.363 [1671544535281-out] DEBUG com.intuit.karate - docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
2022-12-20 21:55:35 13:55:35.364 [1671544535281-out] DEBUG com.intuit.karate - See 'docker run --help'.
2022-12-20 21:55:35 13:55:35.365 [1671544535281-out] DEBUG com.intuit.karate - docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
2022-12-20 21:55:35 13:55:35.366 [1671544535281-out] DEBUG com.intuit.karate - See 'docker run --help'.
2022-12-20 21:55:35 13:55:35.369 [1671544535281] WARN  com.intuit.karate.shell.Command - exit code was non-zero: 125 - [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome] working dir: null
2022-12-20 21:55:35 13:55:35.371 [1671544535281] WARN  com.intuit.karate.shell.Command - exit code was non-zero: 125 - [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome] working dir: null

With the reference article in official github, we want to run the karate-gatling with distributed mode for API testing.

Reference assets:

https://github.com/karatelabs/karate/wiki/Distributed-Testing#jenkins-config

Body:
We want to run karate gatling distributed mode to test API performance.

Here is the performance test class for master node

public class TestPerformanceDocker {
    @Test
    void test(){
        //master node server ip
        String serverUrl= "127.0.0.1";
        String threads = System.getProperty("THREADS");
        String rampDuration = System.getProperty("RAMP_DURATION");
        String constantDuration =System.getProperty("CONST_DURATION");
        //slave node amounts
        Integer executorCount=Integer.parseInt(System.getProperty("NODES_COUNT"));
        String cmd ="mvn gatling:test -DTHREADS="+threads+" -DRAMP_DURATION="+rampDuration+" -DCONST_DURATION="+constantDuration+"";
        GatlingMavenJobConfig config = new GatlingMavenJobConfig(executorCount, serverUrl, 9090) {};
        config.setMainCommand(cmd);
        JobManager<Integer> manager = new JobManager(config);
        manager.start();
        manager.waitForCompletion();
    }
}

Start the master node with cmd :
docker container run -d -t --network=karate_network --name karate_boss --privileged karate mvn clean test -Dtest=TestPerformanceDocker -DTHREADS=3 -DRAMP_DURATION=600 -DCONST_DURATION=600

Face with error log below:

2022-12-20 21:55:35 13:55:35.259 [main] DEBUG com.intuit.karate.http.HttpServer - server started: f224cb587867:9090
2022-12-20 21:55:35 13:55:35.261 [main] DEBUG com.intuit.karate.job.JobManager - added to queue: 1
2022-12-20 21:55:35 13:55:35.262 [main] DEBUG com.intuit.karate.job.JobManager - added to queue: 2
2022-12-20 21:55:35 13:55:35.265 [main] DEBUG com.intuit.karate.job.JobManager - added to queue: 3
2022-12-20 21:55:35 13:55:35.283 [1671544535281] DEBUG com.intuit.karate - command: [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome], working dir: null
2022-12-20 21:55:35 13:55:35.285 [1671544535281] DEBUG com.intuit.karate - command: [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome], working dir: null
2022-12-20 21:55:35 13:55:35.285 [1671544535281] DEBUG com.intuit.karate - command: [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome], working dir: null
2022-12-20 21:55:35 13:55:35.348 [1671544535281-out] DEBUG com.intuit.karate - docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
2022-12-20 21:55:35 13:55:35.349 [1671544535281-out] DEBUG com.intuit.karate - See 'docker run --help'.
2022-12-20 21:55:35 13:55:35.357 [1671544535281] WARN  com.intuit.karate.shell.Command - exit code was non-zero: 125 - [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome] working dir: null
2022-12-20 21:55:35 13:55:35.363 [1671544535281-out] DEBUG com.intuit.karate - docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
2022-12-20 21:55:35 13:55:35.364 [1671544535281-out] DEBUG com.intuit.karate - See 'docker run --help'.
2022-12-20 21:55:35 13:55:35.365 [1671544535281-out] DEBUG com.intuit.karate - docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
2022-12-20 21:55:35 13:55:35.366 [1671544535281-out] DEBUG com.intuit.karate - See 'docker run --help'.
2022-12-20 21:55:35 13:55:35.369 [1671544535281] WARN  com.intuit.karate.shell.Command - exit code was non-zero: 125 - [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome] working dir: null
2022-12-20 21:55:35 13:55:35.371 [1671544535281] WARN  com.intuit.karate.shell.Command - exit code was non-zero: 125 - [docker, run, --rm, --cap-add=SYS_ADMIN, -e, KARATE_JOBURL=http://127.0.0.1:9090, ptrthomas/karate-chrome] working dir: null

With the reference article in official github, we want to run the karate-gatling with distributed mode for API testing.

Reference assets:

https://github.com/karatelabs/karate/wiki/Distributed-Testing#jenkins-config


问:
Sharing a local variable inside a function to another c file
I want to share accountrefence variable to another c file where
the other c file has accountrefence = NULL;
and is having another called function which is using accountrefence variable.

The second function always sees the variable as NULL.
how can I share the variable between the 2 called function so that whenever the variable changes the 2nd called function sees it and do operations upon it?
the functions are in the first c file
the main is in the second c file

```<code>
    EN_serverError_t isValidAccount(ST_cardData_t* cardData, ST_accountsDB_t* accountRefrence)

        for (int i = 0 ; i < 3; i++)
        {
            //printf("\n%s\n", accountRefrence[i].primaryAccountNumber);

            if (!(strcmp(cardData->primaryAccountNumber, accountsDB[i].primaryAccountNumber)))

            {
                accountRefrence = &accountsDB[i];
                return SERVER_OK;
            }
        }
        return ACCOUNT_NOT_FOUND;
    }
    ```
    EN_serverError_t isBlockedAccount(ST_accountsDB_t* accountRefrence)
    {
        printf("%p", accountRefrence);

        if (accountRefrence->state == RUNNING)
        {
            return SERVER_OK;
        }
        else
        {
            return BLOCKED_ACCOUNT;
        }
    }
    ST_transaction_t* accountRefrence = NULL;
    int main(void)
{
    CheckAccountDB = isValidAccount(cardData, accountRefrence);

        if (CheckAccountDB == ACCOUNT_NOT_FOUND)
        {
            printf("\nAccount Doesn't Exist");
        }
        else
        {
            printf("\nAccount Exist");
        }

    CheckAccountState = isBlockedAccount(accountRefrence);
    if (CheckAccountState == SERVER_OK)
    {
        printf("Account is Running");
    }
    else
    {
        printf("Account is Blocked");
    }

    return 0;
}
```

Body:
I want to share accountrefence variable to another c file where
the other c file has accountrefence = NULL;
and is having another called function which is using accountrefence variable.

The second function always sees the variable as NULL.
how can I share the variable between the 2 called function so that whenever the variable changes the 2nd called function sees it and do operations upon it?
the functions are in the first c file
the main is in the second c file

    EN_serverError_t isValidAccount(ST_cardData_t* cardData, ST_accountsDB_t* accountRefrence)

        for (int i = 0 ; i < 3; i++)
        {
            //printf("\n%s\n", accountRefrence[i].primaryAccountNumber);

            if (!(strcmp(cardData->primaryAccountNumber, accountsDB[i].primaryAccountNumber)))

            {
                accountRefrence = &accountsDB[i];
                return SERVER_OK;
            }
        }
        return ACCOUNT_NOT_FOUND;
    }
    ```
    EN_serverError_t isBlockedAccount(ST_accountsDB_t* accountRefrence)
    {
        printf("%p", accountRefrence);

        if (accountRefrence->state == RUNNING)
        {
            return SERVER_OK;
        }
        else
        {
            return BLOCKED_ACCOUNT;
        }
    }
    ST_transaction_t* accountRefrence = NULL;
    int main(void)
{
    CheckAccountDB = isValidAccount(cardData, accountRefrence);

        if (CheckAccountDB == ACCOUNT_NOT_FOUND)
        {
            printf("\nAccount Doesn't Exist");
        }
        else
        {
            printf("\nAccount Exist");
        }

    CheckAccountState = isBlockedAccount(accountRefrence);
    if (CheckAccountState == SERVER_OK)
    {
        printf("Account is Running");
    }
    else
    {
        printf("Account is Blocked");
    }

    return 0;
}