问:
Get smallest available key (>= 1) in a HashMap
I am using a Map in which I save all tracks that the user registers. Every new track should be assigned a new ID which starts at 1. However, if tracks 1, 2, 3, 4 exist and the user deletes track with ID 1 the next added track gets the smallest available ID >=1 which in this case would be 1.

How is it possible to do this efficiently? Or is there a better datatype available?

```<code>private Map<Integer, Track> tracks;

public Register() {
    this.trains = new HashMap<>();
}

public void addTrack(Track track) {
    int id = <get Smallest Value Available >= 1>;
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
    } else {
        Terminal.printError("track with ID " + id + " doesn't exist.");
    }
}
</code>```

答:
Say if from 100 trains number 40 and number 60 are free, you want to get 40 from {40, 60}.</p>

```<code>private final Map<Integer, Track> tracks = new HashMap<>();;
private final SortedSet<Integer> freeIds = new TreeSet<>();

public synchronized void addTrack(Track track) {
    int id;
    if (freeIds.isEmpty()) {
        id = 1 + tracks.size(); // Numbering from 1
    } else {
        id = freeIds.first();
        freeIds.remove(id);
    }
    track.setId(id);
    tracks.put(id, track);
}

public synchronized void removeTrack(int id) {
    Track track = tracks.remove(id);
    if (track != null) {
        track.setId(-1);
        freeIds.add(id);
    } else {
        Terminal.printError("track with ID " + track.getId() + " doesn't exist.");
    }
}
</code>```

Body:
I am using a Map in which I save all tracks that the user registers. Every new track should be assigned a new ID which starts at 1. However, if tracks 1, 2, 3, 4 exist and the user deletes track with ID 1 the next added track gets the smallest available ID >=1 which in this case would be 1.

How is it possible to do this efficiently? Or is there a better datatype available?

private Map<Integer, Track> tracks;

public Register() {
    this.trains = new HashMap<>();
}

public void addTrack(Track track) {
    int id = <get Smallest Value Available >= 1>;
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
    } else {
        Terminal.printError("track with ID " + id + " doesn't exist.");
    }
}

Body:
Say if from 100 trains number 40 and number 60 are free, you want to get 40 from {40, 60}.

private final Map<Integer, Track> tracks = new HashMap<>();;
private final SortedSet<Integer> freeIds = new TreeSet<>();

public synchronized void addTrack(Track track) {
    int id;
    if (freeIds.isEmpty()) {
        id = 1 + tracks.size(); // Numbering from 1
    } else {
        id = freeIds.first();
        freeIds.remove(id);
    }
    track.setId(id);
    tracks.put(id, track);
}

public synchronized void removeTrack(int id) {
    Track track = tracks.remove(id);
    if (track != null) {
        track.setId(-1);
        freeIds.add(id);
    } else {
        Terminal.printError("track with ID " + track.getId() + " doesn't exist.");
    }
}


来源: stackexchange

问:
How can I recursively print a File Array?
I would like to know how to recursively print a File[]. I have made a program but it seems that the program is going out of bounds and I don't know how to fix it. Can someone please give me a few pointers or hints on how to solve this problem? Thanks.

```<code>import java.io.*;

public class RecursiveDir {

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[]args) throws IOException {
    System.out.print("Please enter a directory name: ");
    File f = new File(br.readLine());

    FileFilter filter = new FileFilter() {

        public boolean accept(File f) {
            if(f.isDirectory()) {
                return true;
            }
            return false;
        }

    };

    File[] list = f.listFiles(filter);
    System.out.println(returnDir(list,list.length));
}

public static File returnDir(File[] file,int counter) {
    File f = file[counter];
    if(counter == 0) {
        return file[0];
    }else {
        return f = returnDir(file,counter--);
    }
}
}
</code>```

EDIT: I followed the comments below and changed return f = returnDir(file,counter--); to
return f = returnDir(file,--counter); and also changed returnDir(list,list.length); to
returnDir(list,list.length-1);, my code runs fine but now nothing is printing.

答: You seem to be missing your System.out.println() calls. You are looping through the files and not doing anything with them.</p>

ContentLicense: CC BY-SA 3.0

Body:
I would like to know how to recursively print a File[]. I have made a program but it seems that the program is going out of bounds and I don't know how to fix it. Can someone please give me a few pointers or hints on how to solve this problem? Thanks.

import java.io.*;

public class RecursiveDir {

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[]args) throws IOException {
    System.out.print("Please enter a directory name: ");
    File f = new File(br.readLine());

    FileFilter filter = new FileFilter() {

        public boolean accept(File f) {
            if(f.isDirectory()) {
                return true;
            }
            return false;
        }

    };

    File[] list = f.listFiles(filter);
    System.out.println(returnDir(list,list.length));
}

public static File returnDir(File[] file,int counter) {
    File f = file[counter];
    if(counter == 0) {
        return file[0];
    }else {
        return f = returnDir(file,counter--);
    }
}
}

EDIT: I followed the comments below and changed return f = returnDir(file,counter--); to
return f = returnDir(file,--counter); and also changed returnDir(list,list.length); to
returnDir(list,list.length-1);, my code runs fine but now nothing is printing.


问:
Wordpress template registration cuztomization
I want to develop a wordpress intranet site using Alliance template. Are the template registration forms customizable, so that only users with company email id are allowed to register? is there any plugin for doing so?</p>

答:
try to create a theme from scratch so there will be no issues ever

keep all css, js files in folder instead of using cdn

create accounts manually for company members, assign job role as subscriber

can use 'is admin' plugin or code to hide pages from non logged in users

can use this if new to wordpress coding https://wordpress.org/plugins/user-registration/

ContentLicense: CC BY-SA 4.0


问:
ReactJs project
After I initialized the project with the command: "npx create-react-app my-app", then I "cd into my-app" and ran the "npm start" command, what is the screen about cmd? So guys, can you give me instructions on how to handle this error, I thank you very much!
enter image description here</p>

答: Execute "npm install" before "npm start". "npm install" creates node modules folder without which you cannot run the application</p>

Title: ReactJs project


问:
NoClassDefFoundError: AmazonSNSClient in Java SDK
I got the error Class Definition not found when I try to instantiate AWSSNSClient.This code is not running in AWS Lambda its local system.
Here is my Java code

```<code>   18->   AmazonSNSClient snsClient = new AmazonSNSClient(credentials);
        snsClient.setRegion(Region.getRegion(Regions.));
        ObjectMapper Obj = new ObjectMapper();
        PublishRequest publishRequest = new PublishRequest();
        publishRequest.setTargetArn("");
        publishRequest.setMessage("");
        PublishResult publishResponse = snsClient.publish(publishRequest);
</code>```

My pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cmds</groupId>
    <artifactId></artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name></name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.amazonaws</groupId>
                <artifactId>aws-java-sdk-bom</artifactId>
                <version>1.11.379</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-kubernetes-config</artifactId>
            <version>1.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-flow</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>amazon-sqs-java-messaging-lib</artifactId>
            <version>1.0.8</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-sns</artifactId>
            <version>1.11.721</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>

    </build>

</project>
</code>```

I received the following error when the java code executes

java.lang.NoClassDefFoundError: com/amazonaws/services/sns/AmazonSNSClient
at com.cmds.booking.infrastructure.SNSService.publishMessage(SNSService.java:18)

Any dependency issue ? Where I have gone wrong ?

答:
I have examined your Java code snippet to the best of my ability and there are two issues that I've noted:

( i ) The line below is incomplete :

```<code>snsClient.setRegion(Region.getRegion(Regions.));
</code>```

and should be changed to :

```<code>snsClient.setRegion(Region.getRegion(Regions.US_EAST_1)); //US_EAST_1 can be replaced with your desired region
</code>```

( ii ) The following declaration are deprecated:

```<code>new AmazonSNSClient(credentials)
</code>```

and

```<code>snsClient.setRegion(Region.getRegion(Regions.fromName(region)));
</code>```

Instead, AWS service clients should be created as follows :

If you are using a credential file then you can use the following :

```<code>BasicAWSCredentials basicAwsCredentials = new BasicAWSCredentials(AccessKey,SecretAccessKey);
AmazonSNS snsClient = AmazonSNSClient
                    .builder()
                    .withRegion(your_region)
                    .withCredentials(new AWSStaticCredentialsProvider(basicAwsCredentials))
                    .build();
</code>```

If you are going to use InstanceProfileCredentialProvider then you can use the following :

```<code>AmazonSNS sns = AmazonSNSClientBuilder
                .standard()
                .withCredentials(new InstanceProfileCredentialsProvider(true))
                .build();
</code>```

More information can be found on AWS Java developer guide

Hope this helps!

Body:
I got the error Class Definition not found when I try to instantiate AWSSNSClient.This code is not running in AWS Lambda its local system.
Here is my Java code

   18->   AmazonSNSClient snsClient = new AmazonSNSClient(credentials);
        snsClient.setRegion(Region.getRegion(Regions.));
        ObjectMapper Obj = new ObjectMapper();
        PublishRequest publishRequest = new PublishRequest();
        publishRequest.setTargetArn("");
        publishRequest.setMessage("");
        PublishResult publishResponse = snsClient.publish(publishRequest);

My pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath />
    </parent>
    <groupId>com.cmds</groupId>
    <artifactId></artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name></name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.amazonaws</groupId>
                <artifactId>aws-java-sdk-bom</artifactId>
                <version>1.11.379</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-kubernetes-config</artifactId>
            <version>1.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-flow</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>amazon-sqs-java-messaging-lib</artifactId>
            <version>1.0.8</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-sns</artifactId>
            <version>1.11.721</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>

    </build>

</project>

I received the following error when the java code executes

java.lang.NoClassDefFoundError: com/amazonaws/services/sns/AmazonSNSClient
at com.cmds.booking.infrastructure.SNSService.publishMessage(SNSService.java:18)

Any dependency issue ? Where I have gone wrong ?

Body:
I have examined your Java code snippet to the best of my ability and there are two issues that I've noted:

( i ) The line below is incomplete :

snsClient.setRegion(Region.getRegion(Regions.));

and should be changed to :

snsClient.setRegion(Region.getRegion(Regions.US_EAST_1)); //US_EAST_1 can be replaced with your desired region

( ii ) The following declaration are deprecated:

new AmazonSNSClient(credentials)

and

snsClient.setRegion(Region.getRegion(Regions.fromName(region)));

Instead, AWS service clients should be created as follows :

If you are using a credential file then you can use the following :

BasicAWSCredentials basicAwsCredentials = new BasicAWSCredentials(AccessKey,SecretAccessKey);
AmazonSNS snsClient = AmazonSNSClient
                    .builder()
                    .withRegion(your_region)
                    .withCredentials(new AWSStaticCredentialsProvider(basicAwsCredentials))
                    .build();

If you are going to use InstanceProfileCredentialProvider then you can use the following :

AmazonSNS sns = AmazonSNSClientBuilder
                .standard()
                .withCredentials(new InstanceProfileCredentialsProvider(true))
                .build();

More information can be found on AWS Java developer guide

Hope this helps!


问:
Google calendar API grantOfflineAccess() without a pop up
We have been working on an app that requires access to a users google calendar. We have been using the grantOfflineAccess() method described in google api's documentation - https://developers.google.com/identity/sign-in/web/reference#googleusergrantofflineaccessoptions

However, the problem we are facing is that this opens a pop up and we need to do this via a redirect. Does anyone have any ideas todo this without a pop up showing up?

Safari and Firefox block pop ups and this does not really work well on safari on mobile.
I was able to find a GitHub issue for this https://github.com/google/google-api-javascript-client/issues/288 but I have seen other websites do this without a pop up. You can check zendesk & frontapp.com - both of whom take offline grant for the users signing in.

Any ideas or help would be appreciated.

答:
The only way to access a users data is to have a user grant you permission to access that data.   This is done though Oauth2 a user is promoted to login to their google account then they are given a screen with the scopes of permissions that you are requesting.

There is no way around this.  YOu will always have to ask a user at lease once to grant you permission to access their data if you are requesting offline access you will be given a refresh token that you can use to request a new access token and access the users data when they are not online.

As for popups they shouldn't be displaying as popups they should be opening in a new browser window.


问:
Efficient bitwise operations for counting bits or find the right|left most ones
Given an unsigned int, I have to implement the following operations :

Count the number of bits set to 1

Find the index of the left-most 1 bit

Find the index of the righ-most 1 bit

(the operation should not be architecture dependents).

I've done this using bitwise shift, but I have to iterate through almost all the bits(es.32) .
For example, counting 1's:

```<code>unsigned int number= ...;
while(number != 0){
    if ((number & 0x01) != 0)
        ++count;
    number >>=1;
}
</code>```

The others operation are similar.

So my question is: is there any faster way to do that?

答:
"The righ-most 1 bit" of number x is given by

```<code>pos(1st '1') = log_2(x XOR (x-1) + 1) - 1
</code>```

E.g.:

```<code>x               = 1100101000;
x-1             = 1100100111;
x XOR (x-1)     = 0000001111;
x XOR (x-1) + 1 = 0000010000;
</code>```

The base2-log of the last line then gives you the correct position + 1. So substract 1 from the log-result and you'll have the most-right '1' bit.

For the most-right '0' bit you may use

```<code>pos(1st '0') = log_2(x XOR (x+1) + 1) - 1
</code>```

Body:
Given an unsigned int, I have to implement the following operations :

Count the number of bits set to 1

Find the index of the left-most 1 bit

Find the index of the righ-most 1 bit

(the operation should not be architecture dependents).

I've done this using bitwise shift, but I have to iterate through almost all the bits(es.32) .
For example, counting 1's:

unsigned int number= ...;
while(number != 0){
    if ((number & 0x01) != 0)
        ++count;
    number >>=1;
}

The others operation are similar.

So my question is: is there any faster way to do that?

Body:
"The righ-most 1 bit" of number x is given by

pos(1st '1') = log_2(x XOR (x-1) + 1) - 1

E.g.:

x               = 1100101000;
x-1             = 1100100111;
x XOR (x-1)     = 0000001111;
x XOR (x-1) + 1 = 0000010000;

The base2-log of the last line then gives you the correct position + 1. So substract 1 from the log-result and you'll have the most-right '1' bit.

For the most-right '0' bit you may use

pos(1st '0') = log_2(x XOR (x+1) + 1) - 1


问:
wxMessageBox with an auto-close timer in wxPython
Platforms: Windows, OS X

Python Version: Active State Python 2.7

wxPython Version: Version 2.9

Here is a sample code in which I use a wxMessageBox:

```<code>import wx,os

class Frame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(100, 100),style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN)

        host=os.system('hostname')
        if host!='superman':
            self.dialogBox=wx.MessageBox('The host name should be superman. Closing this dialog box in 2s...','Info')
            self.Destroy()
        else:
            self.Center()
            self.Show()

if __name__ == '__main__':
    app = wx.App(redirect=False)
    frame = Frame(None, -1, 'Sample')
    app.MainLoop()
</code>```

According to the above piece of code, If the host name is not 'superman' , then the user is displayed a message box and prompted to press 'OK'. If the user presses 'OK' button on the message box, then the control moves to the next line in the code (i.e., line number 10) where the frame is destroyed. I want to be to able to automatically close the dialog box and go to the next line in the code i.e., self.Destroy() if the user does not press the 'OK' button in the next 2 seconds. Any thoughts on how do I do that in wxpython ?

答:
If you create your own custom dialog by subclassing wx.Dialog you can use a wx.Timer to generate a periodic event to which you can bind a handler which updates the message every time the timer event fires, then after x event fires you can destroy the dialog.

Working example:

```<code>import wx
import os

class MessageDialog(wx.Dialog):
    def __init__(self, message, title, ttl=10):
        wx.Dialog.__init__(self, None, -1, title,size=(400, 150))
        self.CenterOnScreen(wx.BOTH)
        self.timeToLive = ttl

        stdBtnSizer = self.CreateStdDialogButtonSizer(wx.OK|wx.CANCEL)
        stMsg = wx.StaticText(self, -1, message)
        self.stTTLmsg = wx.StaticText(self, -1, 'Closing this dialog box in %ds...'%self.timeToLive)

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(stMsg, 1, wx.ALIGN_CENTER|wx.TOP, 10)
        vbox.Add(self.stTTLmsg,1, wx.ALIGN_CENTER|wx.TOP, 10)
        vbox.Add(stdBtnSizer,1, wx.ALIGN_CENTER|wx.TOP, 10)
        self.SetSizer(vbox)

        self.timer = wx.Timer(self)
        self.timer.Start(1000)#Generate a timer event every second
        self.timeToLive = 10
        self.Bind(wx.EVT_TIMER, self.onTimer, self.timer)

    def onTimer(self, evt):
        self.timeToLive -= 1
        self.stTTLmsg.SetLabel('Closing this dialog box in %ds...'%self.timeToLive)

        if self.timeToLive == 0:
            self.timer.Stop()
            self.Destroy()

class Frame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(100, 100),style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN)

        host=os.system('hostname')
        if host!='superman':
            dlg = MessageDialog('The host name should be superman', 'Info', ttl=10)
            dlg.ShowModal()
        else:
            self.Center()
            self.Show()

if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = Frame(None, -1, "")
    frame.Show(1)
    app.MainLoop()
</code>```

Body:
Platforms: Windows, OS X

Python Version: Active State Python 2.7

wxPython Version: Version 2.9

Here is a sample code in which I use a wxMessageBox:

import wx,os

class Frame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(100, 100),style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN)

        host=os.system('hostname')
        if host!='superman':
            self.dialogBox=wx.MessageBox('The host name should be superman. Closing this dialog box in 2s...','Info')
            self.Destroy()
        else:
            self.Center()
            self.Show()

if __name__ == '__main__':
    app = wx.App(redirect=False)
    frame = Frame(None, -1, 'Sample')
    app.MainLoop()

According to the above piece of code, If the host name is not 'superman' , then the user is displayed a message box and prompted to press 'OK'. If the user presses 'OK' button on the message box, then the control moves to the next line in the code (i.e., line number 10) where the frame is destroyed. I want to be to able to automatically close the dialog box and go to the next line in the code i.e., self.Destroy() if the user does not press the 'OK' button in the next 2 seconds. Any thoughts on how do I do that in wxpython ?

Body:
If you create your own custom dialog by subclassing wx.Dialog you can use a wx.Timer to generate a periodic event to which you can bind a handler which updates the message every time the timer event fires, then after x event fires you can destroy the dialog.

Working example:

import wx
import os

class MessageDialog(wx.Dialog):
    def __init__(self, message, title, ttl=10):
        wx.Dialog.__init__(self, None, -1, title,size=(400, 150))
        self.CenterOnScreen(wx.BOTH)
        self.timeToLive = ttl

        stdBtnSizer = self.CreateStdDialogButtonSizer(wx.OK|wx.CANCEL)
        stMsg = wx.StaticText(self, -1, message)
        self.stTTLmsg = wx.StaticText(self, -1, 'Closing this dialog box in %ds...'%self.timeToLive)

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(stMsg, 1, wx.ALIGN_CENTER|wx.TOP, 10)
        vbox.Add(self.stTTLmsg,1, wx.ALIGN_CENTER|wx.TOP, 10)
        vbox.Add(stdBtnSizer,1, wx.ALIGN_CENTER|wx.TOP, 10)
        self.SetSizer(vbox)

        self.timer = wx.Timer(self)
        self.timer.Start(1000)#Generate a timer event every second
        self.timeToLive = 10
        self.Bind(wx.EVT_TIMER, self.onTimer, self.timer)

    def onTimer(self, evt):
        self.timeToLive -= 1
        self.stTTLmsg.SetLabel('Closing this dialog box in %ds...'%self.timeToLive)

        if self.timeToLive == 0:
            self.timer.Stop()
            self.Destroy()

class Frame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(100, 100),style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN)

        host=os.system('hostname')
        if host!='superman':
            dlg = MessageDialog('The host name should be superman', 'Info', ttl=10)
            dlg.ShowModal()
        else:
            self.Center()
            self.Show()

if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = Frame(None, -1, "")
    frame.Show(1)
    app.MainLoop()


问:
Google Sheets Formula Assistance - Matching Names to List of Data
I have a bank export that removes the category of the spend. To reconcile my budget to my categories I'd like to run the list of Descriptions the bank provides to match them against my list of categories.

Example list of Descriptions matched to my Categories:

ACH XXX9797 Google Bill --> Electronics

XXXX12345 Citi ---> Credit

Card XXXX456894 Chase ---> Credit Card

XXXX858035 Target ----> Grocery

I also need it to be flexible enough so when it doesn't find a match it leaves the cell blank.

答:
you can create a table of keywords and respective categories (see green table) and then use regex with VLOOKUP to match it. formula would be:

```<code>=ARRAYFORMULA(IFNA(VLOOKUP(IFNA(REGEXEXTRACT(A2:A&"",
 TEXTJOIN("|", 1, SORT(Sheet1!F2:F, 1, 0)))), Sheet1!F2:G, 2, 0)))
</code>```

Body:
you can create a table of keywords and respective categories (see green table) and then use regex with VLOOKUP to match it. formula would be:

=ARRAYFORMULA(IFNA(VLOOKUP(IFNA(REGEXEXTRACT(A2:A&"",
 TEXTJOIN("|", 1, SORT(Sheet1!F2:F, 1, 0)))), Sheet1!F2:G, 2, 0)))


问:
How use external entities in nestjs project with typeorm?
I'm trying to use type orm entities defined outside of the project. That is,  I have two projects: models and core-api. Models is an npm package that exports the entities definition. So, from core-api(nestjs project) i'm trying to define the connection using those entities. Something like this:

```<code>@Module({
    imports: [ TypeOrmModule.forRoot({
    type: 'postgres',
    host: 'postgres',
    port: 5432,
    username: 'myuser',
    password: 'mypass',
    database: 'mydb',
    entities: [
        __dirname + '../node_modules/something/models/src/*.entity.ts'
    ],
    synchronize: true,
    }), AModule ],
    controllers: [],
    providers: [],
})
export class AppModule {}
</code>```

Then, in A module, I'm importing the A entity from the npm package:

```<code>import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AsController } from './As.controller';
import { AsService } from './As.service';
import { A } from 'something/models';

@Module({
  imports: [TypeOrmModule.forFeature([ A ])],
  controllers: [AController],
  providers: [AService],
})
export class AModule {}
</code>```

This ends up with the next error:

RepositoryNotFoundError: No repository for "A" was found. Looks like this entity is not registered in current "https://stackoverflow.com/a/54191513/3943197https://stackoverflow.com/a/54191513/3943197default" connection?

I'm quite lost in how to follow since i don't understand how it works under the hood. I saw the code of typeorm and @nestjs/typeorm but I couldn't figure out how to solve it.

Thanks!

UPDATE:
I could make it work adding the entity class instead of a path like @serianox said. Also, the something/models npm package exports a standalone nest module. This module import/export the entities defined on the package. Thus, I could inject the entities on the main application.

答:
I think found a workaround for this problem;

we can import modules from npm module like this

```<code>import * as Models from "your-models-package";
</code>```

then iterate them and store in an array

```<code>const models = [];
for (const key in Models) {
  if (Models.hasOwnProperty(key)) {
    const model = Models[key];
    models.push(model);
  }
}
</code>```

finaly use in module definition

```<code>const dbConfig = TypeOrmModule.forRoot({
  type: "postgres",
  database: config.postgres.db,
  host: config.postgres.host,
  port: Number(config.postgres.port),
  username: config.postgres.user,
  password: config.postgres.pass,
  entities: models,
  synchronize: true,
});
</code>```

I hope it helps

cheers

Body:
I'm trying to use type orm entities defined outside of the project. That is,  I have two projects: models and core-api. Models is an npm package that exports the entities definition. So, from core-api(nestjs project) i'm trying to define the connection using those entities. Something like this:

@Module({
    imports: [ TypeOrmModule.forRoot({
    type: 'postgres',
    host: 'postgres',
    port: 5432,
    username: 'myuser',
    password: 'mypass',
    database: 'mydb',
    entities: [
        __dirname + '../node_modules/something/models/src/*.entity.ts'
    ],
    synchronize: true,
    }), AModule ],
    controllers: [],
    providers: [],
})
export class AppModule {}

Then, in A module, I'm importing the A entity from the npm package:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AsController } from './As.controller';
import { AsService } from './As.service';
import { A } from 'something/models';

@Module({
  imports: [TypeOrmModule.forFeature([ A ])],
  controllers: [AController],
  providers: [AService],
})
export class AModule {}

This ends up with the next error:

RepositoryNotFoundError: No repository for "A" was found. Looks like this entity is not registered in current "https://stackoverflow.com/a/54191513/3943197https://stackoverflow.com/a/54191513/3943197default" connection?

I'm quite lost in how to follow since i don't understand how it works under the hood. I saw the code of typeorm and @nestjs/typeorm but I couldn't figure out how to solve it.

Thanks!

UPDATE:
I could make it work adding the entity class instead of a path like @serianox said. Also, the something/models npm package exports a standalone nest module. This module import/export the entities defined on the package. Thus, I could inject the entities on the main application.

Body:
I think found a workaround for this problem;

we can import modules from npm module like this

import * as Models from "your-models-package";

then iterate them and store in an array

const models = [];
for (const key in Models) {
  if (Models.hasOwnProperty(key)) {
    const model = Models[key];
    models.push(model);
  }
}

finaly use in module definition

const dbConfig = TypeOrmModule.forRoot({
  type: "postgres",
  database: config.postgres.db,
  host: config.postgres.host,
  port: Number(config.postgres.port),
  username: config.postgres.user,
  password: config.postgres.pass,
  entities: models,
  synchronize: true,
});

I hope it helps

cheers


问:
How to get Azure DevOps client using python script
I am trying to get client of Azure DevOps by using python script.
Here is the code that I am using for this purpose:

```<code>from azure.devops.connection import Connection
   git_client = p_context.connection.clients.get_git_client()
</code>```

p_context is access token of my Azure DevOps organization.

Following is the error that I am facing:

```<code>Traceback (most recent call last):
  File "/home/vsts/work/1/s/IdentifyGitBuildCommitItems.py", line 95, in <module>
    t = get_commit_changes_for_build(context ,azdevops_projectid ,azdevops_build_id ,azdevops_build_number ,bld_commit.id ,azdevops_repository_name)
  File "/home/vsts/work/1/s/IdentifyGitBuildCommitItems.py", line 51, in get_commit_changes_for_build
    comt = git_client.get_changes(p_commit_id ,repository_id=p_repository_name ,project=p_project_id)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/released/git/git_client_base.py", line 250, in get_changes
    query_parameters=query_parameters)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 104, in _send
    response = self._send_request(request=request, headers=headers, content=content, media_type=media_type)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 68, in _send_request
    self._handle_error(request, response)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 295, in _handle_error
    status_code=response.status_code))
azure.devops.exceptions.AzureDevOpsClientRequestError: Page not found.  Operation returned a 404 status code.
##[error]/opt/hostedtoolcache/Python/3.6.10/x64/bin/python failed with return code: 1
</code>```

This is the full GitHub example that I am following for my use case: https://github.com/venkatra/dbt_hacks/blob/PERSISTENT_TABLE_MATERIALIZATION/IdentifyGitBuildCommitItems.py

答:
I have figured out the issue and resolve the error.
Error was prompting due to my source code was present in my personal GitHub account not in the Azure Git repository. When I moved source code from personal Git to Azure Git repository error got resolved. </p>

Body:
I am trying to get client of Azure DevOps by using python script.
Here is the code that I am using for this purpose:

from azure.devops.connection import Connection
   git_client = p_context.connection.clients.get_git_client()

p_context is access token of my Azure DevOps organization.

Following is the error that I am facing:

Traceback (most recent call last):
  File "/home/vsts/work/1/s/IdentifyGitBuildCommitItems.py", line 95, in <module>
    t = get_commit_changes_for_build(context ,azdevops_projectid ,azdevops_build_id ,azdevops_build_number ,bld_commit.id ,azdevops_repository_name)
  File "/home/vsts/work/1/s/IdentifyGitBuildCommitItems.py", line 51, in get_commit_changes_for_build
    comt = git_client.get_changes(p_commit_id ,repository_id=p_repository_name ,project=p_project_id)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/released/git/git_client_base.py", line 250, in get_changes
    query_parameters=query_parameters)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 104, in _send
    response = self._send_request(request=request, headers=headers, content=content, media_type=media_type)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 68, in _send_request
    self._handle_error(request, response)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 295, in _handle_error
    status_code=response.status_code))
azure.devops.exceptions.AzureDevOpsClientRequestError: Page not found.  Operation returned a 404 status code.
##[error]/opt/hostedtoolcache/Python/3.6.10/x64/bin/python failed with return code: 1

This is the full GitHub example that I am following for my use case: https://github.com/venkatra/dbt_hacks/blob/PERSISTENT_TABLE_MATERIALIZATION/IdentifyGitBuildCommitItems.py


问:
Uncaught (in promise): Error: Loading chunk app-pages-pages-module failed
```<code>Uncaught (in promise): Error: Loading chunk app-pages-pages-module failed.
(missing: http://localhost:4200/app-pages-pages-module.js)
onScriptComplete@http://localhost:4200/runtime.js:134:29
wrapFn@http://localhost:4200/polyfills.js:9296:39
./node_modules/zone.js/dist/zone.js/</ZoneDelegate.prototype.invokeTask@http://localhost:4200/polyfills.js:8387:31
onInvokeTask@http://localhost:4200/vendor.js:79507:33
./node_modules/zone.js/dist/zone.js/</ZoneDelegate.prototype.invokeTask@http://localhost:4200/polyfills.js:8386:60
./node_modules/zone.js/dist/zone.js/</Zone.prototype.runTask@http://localhost:4200/polyfills.js:8159:47
./node_modules/zone.js/dist/zone.js/</ZoneTask.invokeTask@http://localhost:4200/polyfills.js:8462:34
invokeTask@http://localhost:4200/polyfills.js:9708:14
globalZoneAwareCallback@http://localhost:4200/polyfills.js:9734:27
</code>```

I am getting above error while I run my Angular 7 app in Firefox otherwise, if I run in Chrome/IE or any other browser, everything is working find without any issue.

I tried to add global error handler to test if this is the error using

```<code>import { ErrorHandler, Injectable } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
    handleError(error: any): void {
        const chunkFailedMessage = /Loading chunk .* failed/;

        if (chunkFailedMessage.test(error.message)) {
            console.log(error.message);
        }
    }
}
</code>```

Initially I tried reloading instead of logging error on a console but firefox keep reloading website infinitely.

Is there any specific thing I have to consider? Or is there any other code you people want me to attach here to fix the issue?

Thanks in advance for the help!!!

EDIT:
I'm using lazy loading modules. Here is the code for your reference if that is the culprit.

```<code>const routes: Routes = [
    {
        path: 'pages',
        loadChildren: 'app/pages/pages.module#PagesModule',
    }
    .
    .
    .
}
</code>```

I am using Angular 7

After enabling router tracing I found below error message:

```<code>NavigationError(id: 2, url: '/pages/dashboard', error: Error: Loading chunk pages-pages-module failed.
(missing: http://localhost:4200/pages-pages-module.js))
</code>```

答:
If you're using Angular 9, then you should upgrade to using import() syntax, as per the upgrade guide and the deprecated api docs.

I'm not expecting this to fix the problem, but it's a good place to start.

Obviously this is irrelevant if you're < v9.

Body:
Uncaught (in promise): Error: Loading chunk app-pages-pages-module failed.
(missing: http://localhost:4200/app-pages-pages-module.js)
onScriptComplete@http://localhost:4200/runtime.js:134:29
wrapFn@http://localhost:4200/polyfills.js:9296:39
./node_modules/zone.js/dist/zone.js/</ZoneDelegate.prototype.invokeTask@http://localhost:4200/polyfills.js:8387:31
onInvokeTask@http://localhost:4200/vendor.js:79507:33
./node_modules/zone.js/dist/zone.js/</ZoneDelegate.prototype.invokeTask@http://localhost:4200/polyfills.js:8386:60
./node_modules/zone.js/dist/zone.js/</Zone.prototype.runTask@http://localhost:4200/polyfills.js:8159:47
./node_modules/zone.js/dist/zone.js/</ZoneTask.invokeTask@http://localhost:4200/polyfills.js:8462:34
invokeTask@http://localhost:4200/polyfills.js:9708:14
globalZoneAwareCallback@http://localhost:4200/polyfills.js:9734:27

I am getting above error while I run my Angular 7 app in Firefox otherwise, if I run in Chrome/IE or any other browser, everything is working find without any issue.

I tried to add global error handler to test if this is the error using

import { ErrorHandler, Injectable } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
    handleError(error: any): void {
        const chunkFailedMessage = /Loading chunk .* failed/;

        if (chunkFailedMessage.test(error.message)) {
            console.log(error.message);
        }
    }
}

Initially I tried reloading instead of logging error on a console but firefox keep reloading website infinitely.

Is there any specific thing I have to consider? Or is there any other code you people want me to attach here to fix the issue?

Thanks in advance for the help!!!

EDIT:
I'm using lazy loading modules. Here is the code for your reference if that is the culprit.

const routes: Routes = [
    {
        path: 'pages',
        loadChildren: 'app/pages/pages.module#PagesModule',
    }
    .
    .
    .
}

I am using Angular 7

After enabling router tracing I found below error message:

NavigationError(id: 2, url: '/pages/dashboard', error: Error: Loading chunk pages-pages-module failed.
(missing: http://localhost:4200/pages-pages-module.js))


问:
How to set drawable on an imageview using rxjava and rxandroid
I am able to use text using rxjava and rxandroid in my code using Textview. Now i m thinking of replacing the textview with imageview and displaying the drawable on the imageview. But I m getting errors. Since, I m new to rxjava, I m probably sure that I m missing something. An help would be really gr8!

Since to show a text, we used the parameter as String...So I thought for a drawable, I thought I might need the parameter as a Drawable...But its giving error..

```<code>package com.prajwal.rxjava_rxandroid;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    ImageView textView;
    Observable<Integer> stringObservable;
    DisposableObserver<Drawable> disposableObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textview);

        stringObservable = Observable.just(R.drawable.ic_launcher_background);

disposableObserver = new DisposableObserver<Drawable>() {
    @Override
    public void onNext(Drawable drawable) {
        Glide.with(getApplicationContext()).load(drawable).into(textView);
    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onComplete() {

    }
};

        stringObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposableObserver.dispose();
    }
}
</code>```

Error: Cannot resolve method subscribe(Drawable)

答:
Find out the solution:

```<code>package com.prajwal.rxjava_rxandroid;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    ImageView textView;
    Observable<Integer> stringObservable;
    DisposableObserver<Integer> disposableObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textview);

        stringObservable = Observable.just(R.drawable.ic_launcher_background);

/*
        stringObserver = new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {
                textView.setText(s); //emitted data is set to textview.
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };
*/

    disposableObserver = new DisposableObserver<Integer>() {
    @Override
    public void onNext(Integer integer) {
        Glide.with(getApplicationContext()).load(integer).asBitmap().into(textView);
    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onComplete() {

    }
};

        stringObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposableObserver.dispose();
    }
}
</code>```

I was passing the parameter as Drawable whereas I needed to pass the
  parameter as an Integer since .load() of Glide doesnt take Drawable as
  a parameter.

Body:
I am able to use text using rxjava and rxandroid in my code using Textview. Now i m thinking of replacing the textview with imageview and displaying the drawable on the imageview. But I m getting errors. Since, I m new to rxjava, I m probably sure that I m missing something. An help would be really gr8!

Since to show a text, we used the parameter as String...So I thought for a drawable, I thought I might need the parameter as a Drawable...But its giving error..

package com.prajwal.rxjava_rxandroid;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    ImageView textView;
    Observable<Integer> stringObservable;
    DisposableObserver<Drawable> disposableObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textview);

        stringObservable = Observable.just(R.drawable.ic_launcher_background);

disposableObserver = new DisposableObserver<Drawable>() {
    @Override
    public void onNext(Drawable drawable) {
        Glide.with(getApplicationContext()).load(drawable).into(textView);
    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onComplete() {

    }
};

        stringObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposableObserver.dispose();
    }
}

Error: Cannot resolve method subscribe(Drawable)

Body:
Find out the solution:

package com.prajwal.rxjava_rxandroid;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    ImageView textView;
    Observable<Integer> stringObservable;
    DisposableObserver<Integer> disposableObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textview);

        stringObservable = Observable.just(R.drawable.ic_launcher_background);

/*
        stringObserver = new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {
                textView.setText(s); //emitted data is set to textview.
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };
*/

    disposableObserver = new DisposableObserver<Integer>() {
    @Override
    public void onNext(Integer integer) {
        Glide.with(getApplicationContext()).load(integer).asBitmap().into(textView);
    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onComplete() {

    }
};

        stringObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposableObserver.dispose();
    }
}

I was passing the parameter as Drawable whereas I needed to pass the
  parameter as an Integer since .load() of Glide doesnt take Drawable as
  a parameter.


问:
Problems detecting collision (Eyeshot) in an array of Tasks
I'm trying to check for each movement in a different task and after checking if there was a collision, in some iterations it generates an Exception "A source matrix was not long or sufficient. Check the index and length, as well as the lower limits of the matrix."
If you try to run sequentially in a "for" the error does not occur, I need to run in parallel to increase performance.
In debugging tests I notice that the error always occurs when trying to run cd.DoWork()</p>

```<code>   private void btn_Tasks_Click(object sender, EventArgs e)
    {
        // The source of your work items, create a sequence of Task instances.
        Task[] tasks = Enumerable.Range(0,tabelaPosicao.Count).Select(i =>
            // Create task here.
            Task.Run(() =>
            {
                VerifiCollision(i);

            })

        // No signalling, no anything.
        ).ToArray();

        // Wait on all the tasks.
        Task.WaitAll(tasks);

    }
   private void VerifiCollision(object x)
    {
        int xx = (int)x;

        int AuxIncrMorsa = Convert.ToInt32(tabelaPosicao[xx].Posicao) * -1;
        bRef_BaseMorsa.Transformation = new Translation(0, AuxIncrMorsa, 0);

        CollisionDetection cd = new CollisionDetection(new List<Entity>() { bRef_BaseMorsa }, new List<Entity>() { bRef_Matriz }, model1.Blocks, true, CollisionDetection2D.collisionCheckType.OBWithSubdivisionTree, maxTrianglesNumForOctreeNode: 5);

        {
            if (cd != null)
            {
                try
                {
                     cd.DoWork();

                }
                catch (Exception e)
                {
                    e.StackTrace;
                }
                catch (AggregateException ae)
                {
                    var messege = ae.Message;
                }
            }

            model1.Entities.ClearSelection();

            if (cd3.Result != null && cd3.Result.Count > 0)
            {

              tabelaPosicao[xx].Tuple = new Tuple<string, string>(cd3.Result[0].Item1.ParentName,
              cd3.Result[0].Item2.ParentName);

            }
         }

    }
</code>```

答: I solved it by cloning the Bloks and BlockReference, so each iteration with its transformation performed separately, so there was no possibility that the transformation of one iteration would interfere with another. Grateful for the help.</p>

Body:
I'm trying to check for each movement in a different task and after checking if there was a collision, in some iterations it generates an Exception "A source matrix was not long or sufficient. Check the index and length, as well as the lower limits of the matrix."
If you try to run sequentially in a "for" the error does not occur, I need to run in parallel to increase performance.
In debugging tests I notice that the error always occurs when trying to run cd.DoWork()

   private void btn_Tasks_Click(object sender, EventArgs e)
    {
        // The source of your work items, create a sequence of Task instances.
        Task[] tasks = Enumerable.Range(0,tabelaPosicao.Count).Select(i =>
            // Create task here.
            Task.Run(() =>
            {
                VerifiCollision(i);

            })

        // No signalling, no anything.
        ).ToArray();

        // Wait on all the tasks.
        Task.WaitAll(tasks);

    }
   private void VerifiCollision(object x)
    {
        int xx = (int)x;

        int AuxIncrMorsa = Convert.ToInt32(tabelaPosicao[xx].Posicao) * -1;
        bRef_BaseMorsa.Transformation = new Translation(0, AuxIncrMorsa, 0);

        CollisionDetection cd = new CollisionDetection(new List<Entity>() { bRef_BaseMorsa }, new List<Entity>() { bRef_Matriz }, model1.Blocks, true, CollisionDetection2D.collisionCheckType.OBWithSubdivisionTree, maxTrianglesNumForOctreeNode: 5);

        {
            if (cd != null)
            {
                try
                {
                     cd.DoWork();

                }
                catch (Exception e)
                {
                    e.StackTrace;
                }
                catch (AggregateException ae)
                {
                    var messege = ae.Message;
                }
            }

            model1.Entities.ClearSelection();

            if (cd3.Result != null && cd3.Result.Count > 0)
            {

              tabelaPosicao[xx].Tuple = new Tuple<string, string>(cd3.Result[0].Item1.ParentName,
              cd3.Result[0].Item2.ParentName);

            }
         }

    }


问:
SignalR - connection.hubName is undefined
I have the following SignalR hub class (only the top is shown):

```<code>[HubName("DataServiceHub")]
public class DataServiceHub : Hub, IDataServiceHub, IDisconnect, IConnected
{
.
.
</code>```

I'm then self hosting the hub in a Console App using the following code in Main function:

```<code>string hubsUrl = appSettingsReader.GetValue("hubsUrl", typeof(string)).ToString();
var hubsServer = new Server(hubsUrl);
hubsServer.Configuration.DisconnectTimeout = TimeSpan.Zero;
hubsServer.MapHubs();
hubsServer.Start();
</code>```

The values of hubsUrl is "http://localhost:4322/"

Once I've run up the Console App If I browse in Chrome "http://localhost:4322/signalr/hubs" I can see the SignalR javascript and my hub at the bottom:

```<code>signalR.dataServiceHub = {
    _: {
        hubName: 'dataServiceHub',
</code>```

I'm trying to connect to this hub from an MVC3 app running on a HTTPS/SSL setup (i.e. the site url prefix is "https://localhost/"

In my Razor page I definately include the SignalR js:

```<code><script src="/Website/Scripts/kendo/2012.2.710/jquery.min.js" type="text/javascript"></script>
<script src="/Website/Scripts/jquery.signalR-0.5.3.min.js" type="text/javascript"></script>
<script src="http://localhost:4322/signalr/hubs" type="text/javascript"></script>
</code>```

Note that we're using Kendo so the jquery js include is via that.

Then in the $(document).ready(function () {  I have the following:

```<code>jQuery.support.cors = true;
var connection = $.hubConnection('http://localhost:4322');
var hub = connection.dataServiceHub;
</code>```

But 'hub' is always 'undefined'.

What am I missing here?

If this is cross domain problem - how do I resolve it?

答:
If you using https don't specify url neither through argument nor via 'url'-property in case when your hub working on the same url. Your hub, otherwise, will be undefined.

UPD

I screwed up guys. I was so hurry to post about specific behavior I 've just detected so I had no check out any possible version more.

However there was a bug in application that provides wrong url to hub with another port than was needed. therefore switching off property setting url for hub proxy has made my client workly.

watch for links your application provides...

Body:
I have the following SignalR hub class (only the top is shown):

[HubName("DataServiceHub")]
public class DataServiceHub : Hub, IDataServiceHub, IDisconnect, IConnected
{
.
.

I'm then self hosting the hub in a Console App using the following code in Main function:

string hubsUrl = appSettingsReader.GetValue("hubsUrl", typeof(string)).ToString();
var hubsServer = new Server(hubsUrl);
hubsServer.Configuration.DisconnectTimeout = TimeSpan.Zero;
hubsServer.MapHubs();
hubsServer.Start();

The values of hubsUrl is "http://localhost:4322/"

Once I've run up the Console App If I browse in Chrome "http://localhost:4322/signalr/hubs" I can see the SignalR javascript and my hub at the bottom:

signalR.dataServiceHub = {
    _: {
        hubName: 'dataServiceHub',

I'm trying to connect to this hub from an MVC3 app running on a HTTPS/SSL setup (i.e. the site url prefix is "https://localhost/"

In my Razor page I definately include the SignalR js:

Note that we're using Kendo so the jquery js include is via that.

Then in the $(document).ready(function () {  I have the following:

jQuery.support.cors = true;
var connection = $.hubConnection('http://localhost:4322');
var hub = connection.dataServiceHub;

But 'hub' is always 'undefined'.

What am I missing here?

If this is cross domain problem - how do I resolve it?


问:
Python: list index out of range even if I am looking at element with index 0
sorry if this question has already been asked but I can't find any answer that solves my problem.
I am using Python 3.8 with PyCharm on Mac (if that information can help).
I just started learning python and have a solid C and MatLab background.
My goal here is to read some information about train stations from a file in the format

and then ask the user for a station and give out the names of the stations that are connected by trains. Here is my code:

```<code>fin = open('trains', 'r')
string = fin.read()
lines = string.split('\n')
print(lines)
station = input("Insert station name\n")
from_station = [] #stations from which trains arrive at the user's station
to_station = [] #stations to which trains arrive from user's station
for i in range(0,len(lines)):
    words = lines[i].split()
    for i in range(0,4):
        print(words[i]) #put to check if the words list actually stores the different words
    if words[0] == station:
        to_station.append(words[2])
    if words[2] == station:
        from_station.append(words[0])
print("Trains arriving from stations: ")
print(from_station)
print("Trains going to stations: ")
print(to_station)
fin.close()
</code>```

I keep getting the Index out of bounds error for print(words[i]) in line 17 even if my complier (or interpreter) manages to print the right informartions without any problem.
I cannot manage to compile the code after the end of the for.

Thank you in advance for your help

EDIT: Even if I make that correction you suggested - I didn't notice in the inner loop that mistake - I still keep getting that error. I get that error even if I remove that inner loop altogether.

答:
issue is in this line

```<code>words = lines[i].split()
</code>```

you need to check the len(words) each time and need to confirm that len(words) is in bound of your indices range
exactly viewing your data can resolve the issue

Body:
sorry if this question has already been asked but I can't find any answer that solves my problem.
I am using Python 3.8 with PyCharm on Mac (if that information can help).
I just started learning python and have a solid C and MatLab background.
My goal here is to read some information about train stations from a file in the format

and then ask the user for a station and give out the names of the stations that are connected by trains. Here is my code:

fin = open('trains', 'r')
string = fin.read()
lines = string.split('\n')
print(lines)
station = input("Insert station name\n")
from_station = [] #stations from which trains arrive at the user's station
to_station = [] #stations to which trains arrive from user's station
for i in range(0,len(lines)):
    words = lines[i].split()
    for i in range(0,4):
        print(words[i]) #put to check if the words list actually stores the different words
    if words[0] == station:
        to_station.append(words[2])
    if words[2] == station:
        from_station.append(words[0])
print("Trains arriving from stations: ")
print(from_station)
print("Trains going to stations: ")
print(to_station)
fin.close()

I keep getting the Index out of bounds error for print(words[i]) in line 17 even if my complier (or interpreter) manages to print the right informartions without any problem.
I cannot manage to compile the code after the end of the for.

Thank you in advance for your help

EDIT: Even if I make that correction you suggested - I didn't notice in the inner loop that mistake - I still keep getting that error. I get that error even if I remove that inner loop altogether.

Body:
issue is in this line

words = lines[i].split()

you need to check the len(words) each time and need to confirm that len(words) is in bound of your indices range
exactly viewing your data can resolve the issue


问:
chase payment integration in php or cakephp
Can any one please let me know is Chase payment gateway provides API for cakephp or php? did any of you have experience with CHASE API? </p>

答:
APIs are language agnostic. They don't care what language you use as long as you can make APIs calls properly according to the documentation.

What you probably mean is "do they offer a SDK for PHP"? The answer seems to be, no, according to their downloads page. However I did find some PHP code supposedly works. Try it out and see if it works for you.


问:
Upgrade to Ionic 5 with Angular 9 from Ionic 4 / Angular 7
There is a great tutorial video on the official Ionic YouTube channel which will show you a best-case scenario for upgrading to Ionic 5 and Angular 9.

However for my simple prototype app that I had made last year (just a demo that let me reorder a list) I tried to update but almost immediately came off the rails.

It turned out to be using "@angular/core": "^7.2.2" which broke the app from ionic serve because it was expecting Angular 8.

Then I tried to run the ng upgrade but got hit with incompatible peer dependencies for codelyzer, @ionic/angular-toolkit, and @angular/http.

So I tried to upgrade to Angular 8 first with npm i @angular/core@"~8.x.x" but that failed as it needed npm i zone.js@~0.9.1.

How can I update successfully to the latest and greatest?

答:
So for people coming from angular 7 it seems for this project the correct upgrade commands are:

npm i @ionic/angular@latest
npm i zone.js@~0.9.1
npm i @angular/core@"~8.x.x"
npm i @ionic/angular-toolkit@latest
npm i codelyzer@latest
npm remove @angular/http
ng update @angular/core @angular/cli --allow-dirty
```

and it finally updated everything. However I did see a warning saying Package not installed: "--allow-dirty". Skipping.

However, then after that I dared to try ionic build and it failed with this error, which got me stuck for another 15 minutes:

zone-flags.ts is missing from the TypeScript compilation.

It seems that the polyfills.ts uses the .ts extension in the include which is breaking the compilation.

I changed this line in polyfills.ts:

import './zone-flags.ts';

To this:

import './zone-flags';

AND IT COMPILED.

But did it ionic serve?

No. No it did not.

The browser showed this in the console:

Error: Angular JIT compilation failed: '@angular/compiler' not loaded!

So after some more searching, I found that if you open main.ts and then add

import '@angular/compiler';

Near the top then all will be right and good with the world once more...

...unless your project then needs the markup breaking changes resolving, but you're on your own for that.

Body:
So for people coming from angular 7 it seems for this project the correct upgrade commands are:

npm i @ionic/angular@latest
npm i zone.js@~0.9.1
npm i @angular/core@"~8.x.x"
npm i @ionic/angular-toolkit@latest
npm i codelyzer@latest
npm remove @angular/http
ng update @angular/core @angular/cli --allow-dirty

and it finally updated everything. However I did see a warning saying Package not installed: "--allow-dirty". Skipping.

However, then after that I dared to try ionic build and it failed with this error, which got me stuck for another 15 minutes:

zone-flags.ts is missing from the TypeScript compilation.

It seems that the polyfills.ts uses the .ts extension in the include which is breaking the compilation.

I changed this line in polyfills.ts:

import './zone-flags.ts';

To this:

import './zone-flags';

AND IT COMPILED.

But did it ionic serve?

No. No it did not.

The browser showed this in the console:

Error: Angular JIT compilation failed: '@angular/compiler' not loaded!

So after some more searching, I found that if you open main.ts and then add

import '@angular/compiler';

Near the top then all will be right and good with the world once more...

...unless your project then needs the markup breaking changes resolving, but you're on your own for that.


问:
Multipart file upload via Powershell Invoke-RestMethod
I'm trying to upload a file to Webex Teams (messaging app) using API via Powershell. I got this to work with Python but can't seem to make it work with Powershell. Not sure what I'm missing here.

Here's my Python code which works for uploading files:

```<code>from requests_toolbelt import MultipartEncoder
import requests
filepath = r'C:\Users\user\Documents\myfile.txt'
filetype = 'text/csv'
roomId = 'Y2lzY2........'
token = 'MDZlM2Ni.......'
url = "https://api.ciscospark.com/v1/messages"
my_fields={'roomId': roomId, 'text': 'Hello World', 'files': ('myfile', open(filepath, 'rb'), filetype)}
m = MultipartEncoder(fields=my_fields)
r = requests.post(url, data=m, headers={'Content-Type': m.content_type, 'Authorization': 'Bearer ' + token})
</code>```

Here's my Powershell code which works for sending messages:

```<code>$BearerToken = "MDZlM2Ni........."
$SpaceId = "Y2lzY2........."
$body = @{roomId = $SpaceId; text = "Hello World"} | ConvertTo-Json
$Url = "https://api.ciscospark.com/v1/messages"
$Headers = @{"Authorization" = "Bearer $BearerToken"; "Content-Type" = "application/json"}
Invoke-RestMethod -Method POST -Headers $Headers -Uri $Url -Body $body
</code>```

Here's my Powershell code which doesn't work for uploading files. What am I missing here compared to the Python code above?

```<code>$BearerToken = "MDZlM2Ni........."
$SpaceId = "Y2lzY2........."
$body = @{roomId = $SpaceId; text = "Hello World"; files = 'C:\Users\user\Documents\myfile.txt; type=text/csv'} | ConvertTo-Json
$Url = "https://api.ciscospark.com/v1/messages"
$Headers = @{"Authorization" = "Bearer $BearerToken"; "Content-Type" = "multipart/form-data"}
Invoke-RestMethod -Method POST -Headers $Headers -Uri $Url -Body $body
</code>```

答:
I am not a python expert but seeing both codes there are some ambiguities here.

Any response that you are receiving from server will be worth sharing and I just ran some of your commands which are showing that the body although is json formatted but the path to the file is being treated as string which means that the file is not being attached

```<code>{
    "roomId":  "Y2lzY2.........",
    "files":  "C:\\Users\\user\\Documents\\myfile.txt; type=text/csv",
    "text":  "Hello World"
}
</code>```

Above is the output of the body when I execute your code as you can see that the data from the file is not loaded and in Python code you are opening the file and sending it to the request, you can use the code mentioned below to achieve that

```<code>$file = Get-Content C:\sample.txt
$body = @{roomId = $SpaceId; text = "Hello World"; files=$file+'; type=text/csv'} | ConvertTo-Json
Write-Output $body
</code>```

This loads the file contents in plain text and adds it to the json.

The code below is reading all the bytes and attaching that to the body as an attachment

```<code>$file = Get-ChildItem -Path "C:\\sample.txt"
$file = [System.IO.File]::ReadAllBytes($file.FullName)
$body = @{roomId = $SpaceId; text = "Hello World"; files=$file+'; type=text/csv'} | ConvertTo-Json
Write-Output $body
</code>```

Hope it helps.

Body:
I'm trying to upload a file to Webex Teams (messaging app) using API via Powershell. I got this to work with Python but can't seem to make it work with Powershell. Not sure what I'm missing here.

Here's my Python code which works for uploading files:

from requests_toolbelt import MultipartEncoder
import requests
filepath = r'C:\Users\user\Documents\myfile.txt'
filetype = 'text/csv'
roomId = 'Y2lzY2........'
token = 'MDZlM2Ni.......'
url = "https://api.ciscospark.com/v1/messages"
my_fields={'roomId': roomId, 'text': 'Hello World', 'files': ('myfile', open(filepath, 'rb'), filetype)}
m = MultipartEncoder(fields=my_fields)
r = requests.post(url, data=m, headers={'Content-Type': m.content_type, 'Authorization': 'Bearer ' + token})

Here's my Powershell code which works for sending messages:

$BearerToken = "MDZlM2Ni........."
$SpaceId = "Y2lzY2........."
$body = @{roomId = $SpaceId; text = "Hello World"} | ConvertTo-Json
$Url = "https://api.ciscospark.com/v1/messages"
$Headers = @{"Authorization" = "Bearer $BearerToken"; "Content-Type" = "application/json"}
Invoke-RestMethod -Method POST -Headers $Headers -Uri $Url -Body $body

Here's my Powershell code which doesn't work for uploading files. What am I missing here compared to the Python code above?

$BearerToken = "MDZlM2Ni........."
$SpaceId = "Y2lzY2........."
$body = @{roomId = $SpaceId; text = "Hello World"; files = 'C:\Users\user\Documents\myfile.txt; type=text/csv'} | ConvertTo-Json
$Url = "https://api.ciscospark.com/v1/messages"
$Headers = @{"Authorization" = "Bearer $BearerToken"; "Content-Type" = "multipart/form-data"}
Invoke-RestMethod -Method POST -Headers $Headers -Uri $Url -Body $body

Body:
I am not a python expert but seeing both codes there are some ambiguities here.

Any response that you are receiving from server will be worth sharing and I just ran some of your commands which are showing that the body although is json formatted but the path to the file is being treated as string which means that the file is not being attached

{
    "roomId":  "Y2lzY2.........",
    "files":  "C:\\Users\\user\\Documents\\myfile.txt; type=text/csv",
    "text":  "Hello World"
}

Above is the output of the body when I execute your code as you can see that the data from the file is not loaded and in Python code you are opening the file and sending it to the request, you can use the code mentioned below to achieve that

$file = Get-Content C:\sample.txt
$body = @{roomId = $SpaceId; text = "Hello World"; files=$file+'; type=text/csv'} | ConvertTo-Json
Write-Output $body

This loads the file contents in plain text and adds it to the json.

The code below is reading all the bytes and attaching that to the body as an attachment

$file = Get-ChildItem -Path "C:\\sample.txt"
$file = [System.IO.File]::ReadAllBytes($file.FullName)
$body = @{roomId = $SpaceId; text = "Hello World"; files=$file+'; type=text/csv'} | ConvertTo-Json
Write-Output $body

Hope it helps.


问:
Angular - How to disable mouse click events outside a specific DIV based on a condition?
I'm using a RAD tool that generates angular code, and I want to make some modifications to a specific behaviour.

I have a grid and I can enter "edit" mode for a specific row with a button click, now once in edit mode, I want to disable completely mouse clicks outside the div containing that grid, because if the users clicks on some components outside the grid, before saving his edit, it will cause some bugs.

So I when the "Edit" button is clicked, I want to stop mouse events outside a specific div, and as soon as the "Save" button is clicked, I want to allow again mouse events everywhere.

I have no code to show, as it would be just some html code with some buttons tags.

The solution I'm looking for is just to know what is the correct way to do this, then I Can implement it by myself

答:
If you pass the event into your method, you can call stopPropagation to prevent it falling through to the elements behind it;

```<code>
    (click)="myMethod($event)"

    myMethod(event: any){
      event.stopPropagation();
      ...
    }

</code>```

Alternatively you can call stopPropagation right on the template

```<code>
    (click)="myMethod(); $event.stopPropagation()"

</code>```

You can make this conditional by combining it with whatever variable you have to set edit mode, i.e.

```<code>    this.editMode && event.stopPropagation()
</code>```

Body:
If you pass the event into your method, you can call stopPropagation to prevent it falling through to the elements behind it;

    (click)="myMethod($event)"

    myMethod(event: any){
      event.stopPropagation();
      ...
    }

Alternatively you can call stopPropagation right on the template

    (click)="myMethod(); $event.stopPropagation()"

You can make this conditional by combining it with whatever variable you have to set edit mode, i.e.

    this.editMode && event.stopPropagation()


问:
Sql query, selecting on unique identifier gives - Error converting data type varchar to uniqueidentifier
How do I select a column of type uniqueidentifier when I have a guid?

I've tried doing following:

```<code>SELECT * FROM MyTable WHERE id = '442402e-207d-b012-4b60-005056c00123'

and

SELECT * FROM MyTable WHERE id = '{442402e-207d-b012-4b60-005056c00123}'
</code>```

Both give me same error: Error converting data type varchar to uniqueidentifier.

答:
You are missing a digit in the first section

4067876A-E3C3-4A3D-B2D3-E879474168C6 is a valid GUID

442402e-207d-b012-4b60-005056c00123 is not

Body:
How do I select a column of type uniqueidentifier when I have a guid?

I've tried doing following:

SELECT * FROM MyTable WHERE id = '442402e-207d-b012-4b60-005056c00123'

and

SELECT * FROM MyTable WHERE id = '{442402e-207d-b012-4b60-005056c00123}'

Both give me same error: Error converting data type varchar to uniqueidentifier.


问:
How can I solve this IOException?
I am trying to get a user token from a url but I keep getting an IOException:

(W/System.err: java.io.FileNotFoundException: url)

I have  tried to run the API from postman, and that seems to work. The request method is GET:

private class userlogin extends AsyncTask<String, String, String> {
  @Override
  public void onPreExecute() {
      progressDialog = new ProgressDialog(userLogin.this);
      progressDialog.setMessage("please wait.........");
      progressDialog.setIndeterminate(false);
      progressDialog.setCancelable(false);
      progressDialog.setTitle("Logging in");
      progressDialog.show();
  }

  @Override
  public String doInBackground(String... para) {

      try {
          URL url = new URL(webconfigs.LOGIN_URL);
          Map<String, String> params = new LinkedHashMap<>();
          params.put("grant_type", "password");
          params.put("username", para[0]);
          params.put("password", para[1]);
          utility.updateSharedPreference(userLogin.this, "Username", para[0]);
          utility.updateSharedPreference(getApplicationContext(), "Password", para[1]);
          //just to check if it is sored in the shared prefrence
          utility.fetchFromSharedPreference(getApplicationContext(), "Username");
          utility.fetchFromSharedPreference(getApplicationContext(), "Password");
          Log.e(">>Username>>", para[0]);
          Log.e(">>Password>>", para[1]);

          StringBuilder postData = new StringBuilder();
          for (Map.Entry<String, String> param : params.entrySet()) {

              if (postData.length() != 0) postData.append('&');
              postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
              postData.append('=');
              postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
          }
          String urlparameters = postData.toString();
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setConnectTimeout(3000);
          conn.setRequestMethod("GET");
          conn.setRequestProperty("Content-Type", webconfigs.CONTENT_TYPE);
          conn.setDoOutput(true);
          //connect  the url
          conn.connect();
          //conn.setDoOutput(true);
          OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
          writer.write(urlparameters);
          writer.flush();
          //create our buffered reader to read from the input stream reader
          BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          StringBuilder st = new StringBuilder();

          //checking the status of the response code
          Integer resposeCode =  conn.getResponseCode();
          String responsecode1 = resposeCode.toString();
          Log.e("the respose code is :", responsecode1);
          String line;
          String result= "";
          // consume the response and read it line by line as
          while ((line = reader.readLine()) != null) {
             st.append(line);

          }
          reader.close();
          writer.close();
          result = st.toString();
          return result;

      } catch (Exception e) {
          e.printStackTrace();
      }

        return null;
  }

  @Override
  protected void onPostExecute(String result) {
      super.onPostExecute(result);

      Log.e(">>>>LOGINSERVERRESPONSE", ">>>>>" + result);
      progressDialog.dismiss();
      try {
          JSONObject results = new JSONObject(result);
          String token = results.getString("access_token");
          if (token != null) {
              String accessToken = results.getString("access_token");
              String tokenType = results.getString("token_type");
              String dateIssued = results.getString(".issued");
              String expiryDate = results.getString(".expires_in");
          }

      } catch (Exception e) {
      }
      startActivity(new Intent(getApplicationContext(), drawerLayout.class));
  }

}
```

答: the problem with using the asynchtask is that when the credentials that are used are wrong the problem will exist ,incase that happens,use a different user from the database</p>

Title: How can I solve this IOException?


问:
Remove white spaces from json after loading it from file using System.Text.Json in .net core 3.1
I am using .NET Core 3.1 with System.Text.Json I am reading JSON from file

```<code>var jsonFilename = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "WellKnownConfig.json");
if (System.IO.File.Exists(jsonFilename))
{
    var fileContent = System.IO.File.ReadAllText(jsonFilename);
    if (!string.IsNullOrWhiteSpace(fileContent))
    {
         //var o = JsonDocument.Parse(fileContent);
         Result = new OkObjectResult(fileContent);
    }
    else
    {
        Result = new NoContentResult();
    }
}
</code>```

The problem is it is having whitespaces. anyway, I can remove white spaces without string parsing.
Like some way from System.Text.Json by loading into some object while using JsonDocument or JsonSerializer

Also is there some way I can minify this JSON after loading it from file

I have seen some solution for newtonjson

Minify a json string using .NET

答:
Following Did the trick. I hope it will help other's as well</p>
```<code>var fileContent = System.IO.File.ReadAllText(jsonFilename);
if (!string.IsNullOrWhiteSpace(fileContent) && Utility.IsValidJson(fileContent))
{
    var obj = JsonSerializer.Deserialize<object>(fileContent);
    Result = new OkObjectResult(obj);
}
else
{
    Result = new NoContentResult();
}
</code>```

Body:
I am using .NET Core 3.1 with System.Text.Json I am reading JSON from file

var jsonFilename = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "WellKnownConfig.json");
if (System.IO.File.Exists(jsonFilename))
{
    var fileContent = System.IO.File.ReadAllText(jsonFilename);
    if (!string.IsNullOrWhiteSpace(fileContent))
    {
         //var o = JsonDocument.Parse(fileContent);
         Result = new OkObjectResult(fileContent);
    }
    else
    {
        Result = new NoContentResult();
    }
}

The problem is it is having whitespaces. anyway, I can remove white spaces without string parsing.
Like some way from System.Text.Json by loading into some object while using JsonDocument or JsonSerializer

Also is there some way I can minify this JSON after loading it from file

I have seen some solution for newtonjson

Minify a json string using .NET

Body:
Following Did the trick. I hope it will help other's as well

var fileContent = System.IO.File.ReadAllText(jsonFilename);
if (!string.IsNullOrWhiteSpace(fileContent) && Utility.IsValidJson(fileContent))
{
    var obj = JsonSerializer.Deserialize<object>(fileContent);
    Result = new OkObjectResult(obj);
}
else
{
    Result = new NoContentResult();
}


问:
pthread_join fails in forking TCP server when handling multiple clients
I have to create a multithread TCP/IP server which contains a variable to count the number of clients connected (and those which disconnect) and print the number of clients connected when a client connects to the server.

This is my client.c file:

```<code>#define PORT 4444

int main ()
{
    int clientSocket;
    struct sockaddr_in serverAddress;
    char buffer[1024];
    ssize_t nread;

    clientSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (clientSocket == -1) {
        perror("[-]Errore durante la creazione della socket\n");
        exit(-1);
    }
    printf("[+]Client socket has been created\n");

    memset(&serverAddress, '\0', sizeof(serverAddress));

    serverAddress.sin_family = AF_INET;
    serverAddress.sin_port = htons(PORT);
    serverAddress.sin_addr.s_addr = INADDR_ANY;

    if (connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == -1) {
        perror("Errore con la connessione\n");
        exit(-1);
    }

    while (1) {

        printf("> ");
        fflush(stdin);
        scanf("%s", buffer);

        if (nread != -1)
            buffer[nread] = '\0';*/

        if (send(clientSocket, buffer, strlen(buffer), 0) == -1) {
            perror("Errore con l'invio");
            exit(1);
        }

        if(strcmp(buffer, ":exit") == 0) {
            close(clientSocket);
            printf("[-]Disconnected from Server\n");
            exit(0);
        }

        if ( (nread=recv(clientSocket, buffer, sizeof buffer - 1, 0)) <= 0) {
            perror("[-]Error in receiving data from server\n");
        }
        else {
            buffer[nread] = '\0';
            printf("Server received: %s\n", buffer);
        }

    }

    close(clientSocket);

    return 0;
}
</code>```

and this is my server.c file:

```<code>#define PORT 4444
#define MAX_CONNESSIONI 100

typedef struct myStruct {
    int clientCollegati;
    int clientCheSiSonoScollegati;
    pthread_mutex_t mutex; // Creazione del mutex per sincronizzare la struttura
} myStruct;

myStruct *test;

myStruct *initStruct();
void *incrementa(void*);

int main ()
{
    int serverSocket, bindStatus;
    struct sockaddr_in serverAddress;
    int clientSocket;
    struct sockaddr_in newAddress;
    char buffer[1024];
    pid_t child;
    socklen_t addrSize;
    ssize_t nread;
    pthread_t tid;

    test = initStruct();

    if (pthread_create(&tid, NULL, incrementa, NULL) != 0) {
        perror("Errore nella creazione del thread t1\n");
        exit(1);
    }
    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == -1) {
        perror("[-]Errore durante la creazione della socket\n");
        exit(-1);
    }

    memset(&serverAddress, '\0', sizeof(serverAddress));

    serverAddress.sin_family = AF_INET;
    serverAddress.sin_port = htons(PORT);
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    bindStatus = bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
    if (bindStatus == -1) {
        perror("[-]Errore durante il binding\n");
        exit(1);
    }
    printf("[+]Bind to port %d\n", PORT);

    if (listen(serverSocket, MAX_CONNESSIONI) != -1) {
        printf("Listening . . .\n\n");
    }
    else {
        perror("[-]Error during listening\n");
        exit(1);
    }

    while (1) {

        clientSocket = accept(serverSocket, (struct sockaddr*)&newAddress, &addrSize);
        if (clientSocket == -1) {
            exit(-1);
        }
        printf("%s:%d joined\n", inet_ntoa(newAddress.sin_addr), ntohs(newAddress.sin_port));

        if (pthread_join(tid, NULL)) { // returns 3
            perror("pthread_join error\n");
            exit(1);
        }

        printf("There is/are %d client(s) connected\n", test->clientCollegati);

        child = fork();
        if (child == 0) {

            close(serverSocket);

            while (1) {

                if ( (nread=recv(clientSocket, buffer, sizeof buffer - 1, 0)) <= 0) {
                    perror("[-]Error in receiving data from server\n");
                }
                else {
                    buffer[nread] = '\0';
                }

                if (strcmp(buffer, ":exit") == 0) {
                    printf("%s:%d left\n", inet_ntoa(newAddress.sin_addr), ntohs(newAddress.sin_port));
                    break;
                }
                else {
                    printf("%s:%d wrote: %s\n", inet_ntoa(newAddress.sin_addr), ntohs(newAddress.sin_port), buffer);
                    send(clientSocket, buffer, strlen(buffer), 0);
                    bzero(buffer, sizeof(buffer));
                }

            }

        }

    }

    close(clientSocket);

    return 0;
}

myStruct *initStruct()
{
    struct myStruct *ptr = malloc(sizeof(myStruct));

    ptr->clientCollegati = 0;
    ptr->clientCheSiSonoScollegati = 0;

    pthread_mutex_init(&ptr->mutex, NULL); // inizializzazione dinamica del mutex

    return ptr;

}

void *incrementa(void *ptr)
{

    pthread_mutex_lock(&test->mutex);

    test->clientCollegati++;

    pthread_mutex_unlock(&test->mutex);

    pthread_exit(0);

}
</code>```

Unfortunately this seems not to work properly, ans you can see server output and here client1 and here client2 output

Where's the mistake? I suppose that the problem is when tid finish and a second call to that pthread_join is invoked to a non-existent thread (because there is a single thread)

答:
Your code logic is wrong. You are doing a single pthread_create() and then multiple pthread_join(). If you want to increment the values for every connected client you have to do one pthread_create() after every single successful accept(), followed by one pthread_join(). Note: all this must happen before the call to fork().

Where's the mistake? I suppose that the problem is when tid finish and a second call to that pthread_join is invoked to a non-existent thread (because there is a single thread)

That's exactly what happens. In your current program, the first pthread_join() is successful, and any successive call fails with errno 3 (no such process) because the thread doesn't exist anymore. So you already figured this out. Why are you creating one thread but joining it multiple times if you know that's wrong?

The way your program is written (fork after the increment) also means that there really is no reason at all to use threads to do the increment, and you don't even need the mutex, since only one single thread will access the value at any given time. In other words, your server isn't multithreaded at all. If you only want to do this as an experiment that's ok, but it doesn't make much sense.

What you probably want to do (to have a multithreaded server) is to have one thread per client instead of forking each time, with the client code in the thread function (in that case having a mutex makes sense). Beware though that this does not scale well for large numbers of clients (in general, the classical fork() approach is better, in which case you really don't need any thread).

Body:
I have to create a multithread TCP/IP server which contains a variable to count the number of clients connected (and those which disconnect) and print the number of clients connected when a client connects to the server.

This is my client.c file:

#define PORT 4444

int main ()
{
    int clientSocket;
    struct sockaddr_in serverAddress;
    char buffer[1024];
    ssize_t nread;

    clientSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (clientSocket == -1) {
        perror("[-]Errore durante la creazione della socket\n");
        exit(-1);
    }
    printf("[+]Client socket has been created\n");

    memset(&serverAddress, '\0', sizeof(serverAddress));

    serverAddress.sin_family = AF_INET;
    serverAddress.sin_port = htons(PORT);
    serverAddress.sin_addr.s_addr = INADDR_ANY;

    if (connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == -1) {
        perror("Errore con la connessione\n");
        exit(-1);
    }

    while (1) {

        printf("> ");
        fflush(stdin);
        scanf("%s", buffer);

        if (nread != -1)
            buffer[nread] = '\0';*/

        if (send(clientSocket, buffer, strlen(buffer), 0) == -1) {
            perror("Errore con l'invio");
            exit(1);
        }

        if(strcmp(buffer, ":exit") == 0) {
            close(clientSocket);
            printf("[-]Disconnected from Server\n");
            exit(0);
        }

        if ( (nread=recv(clientSocket, buffer, sizeof buffer - 1, 0)) <= 0) {
            perror("[-]Error in receiving data from server\n");
        }
        else {
            buffer[nread] = '\0';
            printf("Server received: %s\n", buffer);
        }

    }

    close(clientSocket);

    return 0;
}

and this is my server.c file:

#define PORT 4444
#define MAX_CONNESSIONI 100

typedef struct myStruct {
    int clientCollegati;
    int clientCheSiSonoScollegati;
    pthread_mutex_t mutex; // Creazione del mutex per sincronizzare la struttura
} myStruct;

myStruct *test;

myStruct *initStruct();
void *incrementa(void*);

int main ()
{
    int serverSocket, bindStatus;
    struct sockaddr_in serverAddress;
    int clientSocket;
    struct sockaddr_in newAddress;
    char buffer[1024];
    pid_t child;
    socklen_t addrSize;
    ssize_t nread;
    pthread_t tid;

    test = initStruct();

    if (pthread_create(&tid, NULL, incrementa, NULL) != 0) {
        perror("Errore nella creazione del thread t1\n");
        exit(1);
    }
    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == -1) {
        perror("[-]Errore durante la creazione della socket\n");
        exit(-1);
    }

    memset(&serverAddress, '\0', sizeof(serverAddress));

    serverAddress.sin_family = AF_INET;
    serverAddress.sin_port = htons(PORT);
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    bindStatus = bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
    if (bindStatus == -1) {
        perror("[-]Errore durante il binding\n");
        exit(1);
    }
    printf("[+]Bind to port %d\n", PORT);

    if (listen(serverSocket, MAX_CONNESSIONI) != -1) {
        printf("Listening . . .\n\n");
    }
    else {
        perror("[-]Error during listening\n");
        exit(1);
    }

    while (1) {

        clientSocket = accept(serverSocket, (struct sockaddr*)&newAddress, &addrSize);
        if (clientSocket == -1) {
            exit(-1);
        }
        printf("%s:%d joined\n", inet_ntoa(newAddress.sin_addr), ntohs(newAddress.sin_port));

        if (pthread_join(tid, NULL)) { // returns 3
            perror("pthread_join error\n");
            exit(1);
        }

        printf("There is/are %d client(s) connected\n", test->clientCollegati);

        child = fork();
        if (child == 0) {

            close(serverSocket);

            while (1) {

                if ( (nread=recv(clientSocket, buffer, sizeof buffer - 1, 0)) <= 0) {
                    perror("[-]Error in receiving data from server\n");
                }
                else {
                    buffer[nread] = '\0';
                }

                if (strcmp(buffer, ":exit") == 0) {
                    printf("%s:%d left\n", inet_ntoa(newAddress.sin_addr), ntohs(newAddress.sin_port));
                    break;
                }
                else {
                    printf("%s:%d wrote: %s\n", inet_ntoa(newAddress.sin_addr), ntohs(newAddress.sin_port), buffer);
                    send(clientSocket, buffer, strlen(buffer), 0);
                    bzero(buffer, sizeof(buffer));
                }

            }

        }

    }

    close(clientSocket);

    return 0;
}

myStruct *initStruct()
{
    struct myStruct *ptr = malloc(sizeof(myStruct));

    ptr->clientCollegati = 0;
    ptr->clientCheSiSonoScollegati = 0;

    pthread_mutex_init(&ptr->mutex, NULL); // inizializzazione dinamica del mutex

    return ptr;

}

void *incrementa(void *ptr)
{

    pthread_mutex_lock(&test->mutex);

    test->clientCollegati++;

    pthread_mutex_unlock(&test->mutex);

    pthread_exit(0);

}

Unfortunately this seems not to work properly, ans you can see server output and here client1 and here client2 output

Where's the mistake? I suppose that the problem is when tid finish and a second call to that pthread_join is invoked to a non-existent thread (because there is a single thread)


问:
How to check all elements in an array same as some element in the other array
I have a question about How to check all elements in an array same as some elements in other array.

array1= [[1,2], [2,3], [3,3]]
array2 = [[1,2],[2,3]]

so in this case it will return true, because all the elements in array2 are same as array1.

Doses anybody some solution

答:
What you want to do is use Array.prototype.some() to calculate intersection between your two arrays. A nested .some() is needed, because we need to stringify the arrays and compare them as JSON string, since [1,2] !== [1,2], for example.

See proof-of-concept code below:

const array1 = [[1,2], [2,3], [3,3]];
const array2 = [[1,2],[2,3]];
const array3 = [[3,4],[4,5]];
const array4 = [[3,3]];

function isIntersecting(arr1, arr2) {
  return arr1.some(x => {
    return arr2.some(y => {
      return JSON.stringify(x) === JSON.stringify(y);
    });
  });
}

console.log(isIntersecting(array1, array2));  // Should return true
console.log(isIntersecting(array1, array3));  // Should return false
console.log(isIntersecting(array2, array3));  // Should return false
console.log(isIntersecting(array1, array4));  // Should return true```


问:
Are Ignite's SQL Queries Transactional?
We are implementing Apache Ignite's transaction using org.apache.ignite.transactions. Transaction object.

But we would like to know if it supports SQL Querying.

答:
No, you can't properly use SQL transactions, though Ignite has an experimental support for MVCC.
I'd suggest you to keep using the Transaction object and K-V API.

Please, follow the links:
https://apacheignite.readme.io/docs/transactions#section-atomicity-mode and
https://apacheignite-sql.readme.io/docs/multiversion-concurrency-control

Title: Are Ignite's SQL Queries Transactional?