问:
Spinner with transparent background?
I have a spinner with a white background which is animated through a keyframe. So, having this code pen, how could I remove this color to "smt-spinner-inner-circle" class without affecting the original desing? If the background is removed, the portion is visible. I have tried to apply a clip but the result is not the expected.

http://codepen.io/anon/pen/WpagJN

Html:

```<code><div class="smt-spinner-circle">
   <div class="smt-spinner"></div>
   <div class="smt-spinner-inner-circle"></div>
</div>
</code>```

To sum up, I need the background of the spinner transparent, not red, since the website will be different backgrounds depending on the page you are (grey, white, etc)...

答:
Why not do like this, which will be transparent on top of any backgrounds, images included

.test {
  display: inline-block;
  padding: 20px;
}
.test.red{
  background: red;
}
.test.green{
  background: green;
}
.test.image{
  background: url(http://lorempixel.com/500/200/nature/1/);
}

.smt-spinner-circle {
  width: 50px;
  height: 50px;
  position: relative;
  margin: 20px;
  border-radius: 50%;
}
.smt-spinner {
  height: 100%;
  width: 100%;
  border-radius: 50%;
  border-right: 2px solid rgba(255,255,255,0.6);
  border-top: 2px solid blue;
  border-left: 2px solid blue;
  border-bottom: 2px solid blue;
  animation: rotate--spinner 1.6s infinite;
}

@keyframes rotate--spinner {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test red">
  <div class="smt-spinner-circle">
   <div class="smt-spinner"></div>
  </div>
</div>
<div class="test green">
  <div class="smt-spinner-circle">
   <div class="smt-spinner"></div>
  </div>
</div>
<div class="test image">
  <div class="smt-spinner-circle">
   <div class="smt-spinner"></div>
  </div>
</div></code>```

Title: Spinner with transparent background?

Body:
I have a spinner with a white background which is animated through a keyframe. So, having this code pen, how could I remove this color to "smt-spinner-inner-circle" class without affecting the original desing? If the background is removed, the portion is visible. I have tried to apply a clip but the result is not the expected.

http://codepen.io/anon/pen/WpagJN

Html:

To sum up, I need the background of the spinner transparent, not red, since the website will be different backgrounds depending on the page you are (grey, white, etc)...

Body:
Why not do like this, which will be transparent on top of any backgrounds, images included

.test {
  display: inline-block;
  padding: 20px;
}
.test.red{
  background: red;
}
.test.green{
  background: green;
}
.test.image{
  background: url(http://lorempixel.com/500/200/nature/1/);
}

.smt-spinner-circle {
  width: 50px;
  height: 50px;
  position: relative;
  margin: 20px;
  border-radius: 50%;
}
.smt-spinner {
  height: 100%;
  width: 100%;
  border-radius: 50%;
  border-right: 2px solid rgba(255,255,255,0.6);
  border-top: 2px solid blue;
  border-left: 2px solid blue;
  border-bottom: 2px solid blue;
  animation: rotate--spinner 1.6s infinite;
}

@keyframes rotate--spinner {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}

<div class="test red">
  <div class="smt-spinner-circle">
   <div class="smt-spinner"></div>
  </div>
</div>
<div class="test green">
  <div class="smt-spinner-circle">
   <div class="smt-spinner"></div>
  </div>
</div>
<div class="test image">
  <div class="smt-spinner-circle">
   <div class="smt-spinner"></div>
  </div>
</div>


来源: stackexchange

问:
Having trouble with select statements in a stored function
What I'm trying to do here is execute GetValue3 with @ID and get the @results that list @fullname, @phonenumber, @email, @city.

I'm getting 2 errors and I've been trying to figure out how to fix both.

Error #1

Select statements included within a function cannot return data to a client

Error #2

A select statement that assigns a value to a variable must not be combined with data-retrieval

What should I do?

```<code>Create Function GetValue3 (@ID INT)
returns nvarchar(350)
as
begin
    declare @results nvarchar(350)
    declare @fullname nvarchar(75)
    declare @phonenumber nvarchar(100)
    declare @email nvarchar(50)
    declare @city nvarchar(20)

    select -- this is where I get the first error.
        @fullname = p.Full_Name,
        @phonenumber = c.Phone,
        @email = c.Email,
        @city = c.CityID,
        @results = @fullname,
        @phonenumber, @email, @city -- this is where I get the 2nd error.
    from
        d_People p, d_Contacts c
    where
        c.PeopleID = p.PeopleID
        and p.PeopleID = @ID;

    return @results
end
</code>```

答:
Try with the below code:</p>

```<code>    Create Function GetValue3 (@ID INT)
    returns nvarchar(350)
    as
    begin
        declare @results nvarchar(350)
        declare @fullname nvarchar(75)
        declare @phonenumber nvarchar(100)
        declare @email nvarchar(50)
        declare @city nvarchar(20)

            select

                @fullname = p.Full_Name,
                @phonenumber = c.Phone,
                @email = c.Email,
                @city = c.CityID,
                @results = @fullname +','+ @phonenumber +','+ @email +','+ @city
                from d_People p, d_Contacts c
                where c.PeopleID=p.PeopleID and p.PeopleID=@ID;

    return @results
    end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What I'm trying to do here is execute GetValue3 with @ID and get the @results that list @fullname, @phonenumber, @email, @city.

I'm getting 2 errors and I've been trying to figure out how to fix both.

Error #1

Select statements included within a function cannot return data to a client

Error #2

A select statement that assigns a value to a variable must not be combined with data-retrieval

What should I do?

Create Function GetValue3 (@ID INT)
returns nvarchar(350)
as
begin
    declare @results nvarchar(350)
    declare @fullname nvarchar(75)
    declare @phonenumber nvarchar(100)
    declare @email nvarchar(50)
    declare @city nvarchar(20)

    select -- this is where I get the first error.
        @fullname = p.Full_Name,
        @phonenumber = c.Phone,
        @email = c.Email,
        @city = c.CityID,
        @results = @fullname,
        @phonenumber, @email, @city -- this is where I get the 2nd error.
    from
        d_People p, d_Contacts c
    where
        c.PeopleID = p.PeopleID
        and p.PeopleID = @ID;

    return @results
end

Body:
Try with the below code:

    Create Function GetValue3 (@ID INT)
    returns nvarchar(350)
    as
    begin
        declare @results nvarchar(350)
        declare @fullname nvarchar(75)
        declare @phonenumber nvarchar(100)
        declare @email nvarchar(50)
        declare @city nvarchar(20)

            select

                @fullname = p.Full_Name,
                @phonenumber = c.Phone,
                @email = c.Email,
                @city = c.CityID,
                @results = @fullname +','+ @phonenumber +','+ @email +','+ @city
                from d_People p, d_Contacts c
                where c.PeopleID=p.PeopleID and p.PeopleID=@ID;

    return @results
    end


问:
Searching in SQL field WHERE LIKE %$user_id%
I have a small problem.

I have my table as follows:

tbl_groups

```<code>id (int) | teacher_id (int) | student_ids (text)
------------------------------------------------
1        | 14               | 2015,2016,2017
2        | 35               | 15,16,17
3        | 14               | 631
</code>```

student_ids will get filled by a PHP array using implode().

However, when I execute the following query to search the group's id by a student id:

```<code>SELECT `id` FROM `tbl_groups` WHERE `student_ids` LIKE '%15%'
</code>```

I get row 1 and 2 returned. This happens because student_ids "15" will be searched for, and "2015" contains "15" so it will also return it.

How can I prevent this?

答:
It is worth reconsidering your database structure, instead of the layout you have suggested above consider having a table as follows

groups
id | teacher_id

student_group
student_id | group_id

You can then create a relationship where the group belongs to a teacher (One to Many) and a Many to Many relationship on student to group table allowing many students to be a member of many groups.

This will then allow you to query for groups containing a student by their ID more reliably.

Body:
I have a small problem.

I have my table as follows:

tbl_groups

id (int) | teacher_id (int) | student_ids (text)
------------------------------------------------
1        | 14               | 2015,2016,2017
2        | 35               | 15,16,17
3        | 14               | 631

student_ids will get filled by a PHP array using implode().

However, when I execute the following query to search the group's id by a student id:

SELECT `id` FROM `tbl_groups` WHERE `student_ids` LIKE '%15%'

I get row 1 and 2 returned. This happens because student_ids "15" will be searched for, and "2015" contains "15" so it will also return it.

How can I prevent this?


问:
Add timestamp in Powershell output
I have the following code that export a CSV-file from a query.
How do I add a "Get-date" (today) stamp in the end of the file in the filepath?</p>

```<code>$ds.Tables[0] | Export-csv -delimiter ";" -path "C:\temp\TempWarehousingControl.csv" -NoTypeInformation -Force -Encoding UTF8
Get-Content C:\temp\TempWarehousingControl.csv | %{ $_ -replace """""", "NULL"} |%{ $_ -replace """", ""} | out-file -FilePath C:\Batch\Output\WarehousingControl\WarehousingControl.csv -Force -Encoding utf8
</code>```

答:
Assuming that you meant "how do I add today's date to the end of the filepath" (vs the end of the file), this will do it:

```<code>"C:\Batch\Output\WarehousingControl\WarehousingControl-$(get-date -Format 'dd-MM-yyyy').csv"
</code>```

Included in your full code:

```<code>$ds.Tables[0] | Export-csv -delimiter ";" -path "C:\temp\TempWarehousingControl.csv" -NoTypeInformation -Force -Encoding UTF8
Get-Content C:\temp\TempWarehousingControl.csv | %{ $_ -replace """""", "NULL"} |%{ $_ -replace """", ""} | out-file -FilePath "C:\Batch\Output\WarehousingControl\WarehousingControl-$(get-date -Format 'dd-MM-yyyy').csv" -Force -Encoding utf8
</code>```

Explanation:

This is a subexpression $() which uses get-date to get the current date and formats it as dd-MM-yyyy (note month is a capital M as lowercase m is the code for minute).

Title: Add timestamp in Powershell output

Body:
I have the following code that export a CSV-file from a query.
How do I add a "Get-date" (today) stamp in the end of the file in the filepath?

$ds.Tables[0] | Export-csv -delimiter ";" -path "C:\temp\TempWarehousingControl.csv" -NoTypeInformation -Force -Encoding UTF8
Get-Content C:\temp\TempWarehousingControl.csv | %{ $_ -replace """""", "NULL"} |%{ $_ -replace """", ""} | out-file -FilePath C:\Batch\Output\WarehousingControl\WarehousingControl.csv -Force -Encoding utf8

Body:
Assuming that you meant "how do I add today's date to the end of the filepath" (vs the end of the file), this will do it:

"C:\Batch\Output\WarehousingControl\WarehousingControl-$(get-date -Format 'dd-MM-yyyy').csv"

Included in your full code:

$ds.Tables[0] | Export-csv -delimiter ";" -path "C:\temp\TempWarehousingControl.csv" -NoTypeInformation -Force -Encoding UTF8
Get-Content C:\temp\TempWarehousingControl.csv | %{ $_ -replace """""", "NULL"} |%{ $_ -replace """", ""} | out-file -FilePath "C:\Batch\Output\WarehousingControl\WarehousingControl-$(get-date -Format 'dd-MM-yyyy').csv" -Force -Encoding utf8

Explanation:

This is a subexpression $() which uses get-date to get the current date and formats it as dd-MM-yyyy (note month is a capital M as lowercase m is the code for minute).


问:
Grant access to private constructor without friends?
I am working on some code, where I encountered a situation similar to this one:

```<code>struct Bar;

struct Foo{
    friend struct Bar;
private:
    Foo(){}
    void f(){}
    void g(){}
};

struct Bar {
   Foo* f;
   Bar()  { f = new Foo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}
</code>```

I would prefer to have Bar not as friend of Foo, because besides Foos constructor Bar does not need access to any of Foos private methods (and thus should not have access). Is there a way to allow only Bar to create Foos without making them friends?

PS: realized that the question might not be 100% clear. I don't mind if it is via friends or not, just the fact that all Bar has access to all private methods is disturbing me (which is usually the case with friends) and that is what I want to avoid. Fortunately none of the answers given so far had a problem with that lousy formulation.

答:
One way that occurred to me was to have an internal class that makes Bar its friend so only Bar can create it and that internal class can be used as an additional parameter to Foo constructor so only the class's friends can invoke it.

```<code>class Foo
{
public:
    // only friends of the special key can invoke the constructor
    // or any member function that includes it as a dummy parameter
    class special_key {friend class Bar; special_key(){}};

    // making special_key a dummy parameter makes sure only friends of
    // the special key can invoke the function
    Foo(special_key) {}
    void f(){}
    void g(){}
};

class Bar
{
public:
    // only Bar functions can create the special key
    Bar() { f = std::make_unique<Foo>(Foo::special_key()); }

private:
    std::unique_ptr<Foo> f;
};
</code>```

As well as restricting access to specific functions this technique also allows the use of smart pointer make functions which direct friendship does not.

Body:
I am working on some code, where I encountered a situation similar to this one:

struct Bar;

struct Foo{
    friend struct Bar;
private:
    Foo(){}
    void f(){}
    void g(){}
};

struct Bar {
   Foo* f;
   Bar()  { f = new Foo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}

I would prefer to have Bar not as friend of Foo, because besides Foos constructor Bar does not need access to any of Foos private methods (and thus should not have access). Is there a way to allow only Bar to create Foos without making them friends?

PS: realized that the question might not be 100% clear. I don't mind if it is via friends or not, just the fact that all Bar has access to all private methods is disturbing me (which is usually the case with friends) and that is what I want to avoid. Fortunately none of the answers given so far had a problem with that lousy formulation.

Body:
One way that occurred to me was to have an internal class that makes Bar its friend so only Bar can create it and that internal class can be used as an additional parameter to Foo constructor so only the class's friends can invoke it.

class Foo
{
public:
    // only friends of the special key can invoke the constructor
    // or any member function that includes it as a dummy parameter
    class special_key {friend class Bar; special_key(){}};

    // making special_key a dummy parameter makes sure only friends of
    // the special key can invoke the function
    Foo(special_key) {}
    void f(){}
    void g(){}
};

class Bar
{
public:
    // only Bar functions can create the special key
    Bar() { f = std::make_unique<Foo>(Foo::special_key()); }

private:
    std::unique_ptr<Foo> f;
};

As well as restricting access to specific functions this technique also allows the use of smart pointer make functions which direct friendship does not.


问:
Problems With Error Casting In Swift
Not sure if this a bug or an intended feature.

To create a user with an email and password in Firebase, I've been using the following code:

```<code>FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
    if let error = error {
        guard let error = error as? FIRAuthErrorCode else { return } // ALWAYS FAILS
        ...code...
    }
    ...code...
}
</code>```

The error parameter in the completion handler for the method cannot be cast as FIRAuthErrorCode; it always fails. Is that a bug, or is that the expected behaviour?

Edit: I am aware that error codes can be used to distinguish between the different types of FIRAuthErrorCode errors. It's just not readable, and it doesn't make much sense for the error parameter in the completion handler to be not of be of type FIRAuthErrorCode. The cases and error codes of FIRAuthErrorCode can be found here.

答:
After contacting Firebase support about the issue, they've said that the errors that are passed back in completion handlers are just Error objects. They weren't FIRAuthErrorCode objects. To test for the various FIRAuthErrorCode cases, one would have to do something like this:

```<code>FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
    if let error = error {
        guard let error = FIRAuthErrorCode(rawValue: error._code) else {
            fatalError("This should never be executed")
        }
        switch error {
        case .errorCodeInvalidEmail: ...
        case .errorCodeWrongPassword: ...
        default: ...

        }
        ...code...
    }
    ...code...
}
</code>```

^ This preserves readability and makes error handling more intuitive. And, there is no need for error casting!

Title: Problems With Error Casting In Swift

Body:
Not sure if this a bug or an intended feature.

To create a user with an email and password in Firebase, I've been using the following code:

FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
    if let error = error {
        guard let error = error as? FIRAuthErrorCode else { return } // ALWAYS FAILS
        ...code...
    }
    ...code...
}

The error parameter in the completion handler for the method cannot be cast as FIRAuthErrorCode; it always fails. Is that a bug, or is that the expected behaviour?

Edit: I am aware that error codes can be used to distinguish between the different types of FIRAuthErrorCode errors. It's just not readable, and it doesn't make much sense for the error parameter in the completion handler to be not of be of type FIRAuthErrorCode. The cases and error codes of FIRAuthErrorCode can be found here.

Body:
After contacting Firebase support about the issue, they've said that the errors that are passed back in completion handlers are just Error objects. They weren't FIRAuthErrorCode objects. To test for the various FIRAuthErrorCode cases, one would have to do something like this:

FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
    if let error = error {
        guard let error = FIRAuthErrorCode(rawValue: error._code) else {
            fatalError("This should never be executed")
        }
        switch error {
        case .errorCodeInvalidEmail: ...
        case .errorCodeWrongPassword: ...
        default: ...

        }
        ...code...
    }
    ...code...
}

^ This preserves readability and makes error handling more intuitive. And, there is no need for error casting!


问:
border-radius for circle left and right with unequal width and height and variable height
This is what I'm trying to achieve:

As width and height are not equal setting border-radius:50% gives an oval which is not what I meant to achieve.
Giving fixed size (like border-radius:20px) would work if the height was fixed but how can I get this to work with variable height?

答:
Set border-radius to a higher value:</p>

```<code>border-radius: 9999px;
</code>```

Body:
Set border-radius to a higher value:

border-radius: 9999px;


问:
how to refer xsd schemalocation inside a jar file?
I have a xml schema (xsd) file which is inside a jar file that will be included in the runtime class path. In my Wsdl i need to import the schema by giving location inside the jar file.

I try to use XML catalog but the server i use (websphere) does not resolve xml catalog reference.

答:
We were facing a similar issue where the JAR containing the XSD was getting added to the classpath and we had to refer to it from WSDL using schemaLocation.
Our project was maven based, so we used the unpack goal of maven-dependency-plugin to download the file to the resources folder before compilation.

```<code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
    <execution>
        <id>unpack</id>
        <phase>generate-sources</phase>
        <goals>
            <goal>unpack</goal>
        </goals>
        <configuration>
            <artifactItems>
                <artifactItem>
                    <groupId>group</groupId>
                    <artifactId>artifact</artifactId>
                    <version>${version}</version>
                    <outputDirectory>${basedir}/src/main/resources/xsd</outputDirectory>
                    <includes>ToDownload.xsd</includes>
                </artifactItem>
            </artifactItems>
        </configuration>
    </execution>
</executions>
</code>```

This results in the xsd getting downloaded to the resources directory in a folder named xsd.

In WSDL schemaLocation="xsd/ToDownload.xsd".
This ensures that during compilation the WSDL will refer to the XSD which has been downloaded and locally available.

Body:
We were facing a similar issue where the JAR containing the XSD was getting added to the classpath and we had to refer to it from WSDL using schemaLocation.
Our project was maven based, so we used the unpack goal of maven-dependency-plugin to download the file to the resources folder before compilation.

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
    <execution>
        <id>unpack</id>
        <phase>generate-sources</phase>
        <goals>
            <goal>unpack</goal>
        </goals>
        <configuration>
            <artifactItems>
                <artifactItem>
                    <groupId>group</groupId>
                    <artifactId>artifact</artifactId>
                    <version>${version}</version>
                    <outputDirectory>${basedir}/src/main/resources/xsd</outputDirectory>
                    <includes>ToDownload.xsd</includes>
                </artifactItem>
            </artifactItems>
        </configuration>
    </execution>
</executions>

This results in the xsd getting downloaded to the resources directory in a folder named xsd.

In WSDL schemaLocation="xsd/ToDownload.xsd".
This ensures that during compilation the WSDL will refer to the XSD which has been downloaded and locally available.


问:
Parsing output of "top" command (Shell) with PHP
I'm trying to export the output of the "top" command (unix) with PHP. Invoking and reading the command/output is pretty simple using the "exex" function but the question is: is the "top" command output (order, names, etc.) always the same? Or is it related to the distribution I'm using?

Is there any way to parse these information "generally" on UNIX systems?

Thanks in advance

答:
As mentioned by Lucas, ps is probably printing what you would expect.

If your Unix flavour is Linux, I think pidstat (from the sysstat package) is better suited for your needs (not to mention, documented in a clearer way, in my opinion).


问:
add a element to json array with Key/value using angular js
I have a json array object like below

$scope.Json = [{
  Id:"5464",
  Class:"9",
  Rank:"4"
}]

I want to add a item "Name":"Vicky" to the Json. So that my result should be as below.

$scope.Json = [{
  Id:"5464",
  Class:"9",
  Rank:"4",
  Name:"Vicky"
}]

I am new to angular, can anyone help on this?

答:
Use Array map() method.

DEMO

var json = [{ Id:"5464", Class:"9", Rank:"4" }];

json.map(function(item) {
  item.Name = 'Vicky';
});

console.log(json);```


问:
Why doesn't Android Debug mode and Android Monitor work together
Why do android studio close its monitor if I debug the application ?
I need to change database table once I get results while debugging and then again debug , but the process goes like android debug closes the monitor as soon I start to debug .</p>

答: just go settings => Build, execution, deployment =>instant run => uncheck 'Enable Instant Run to hot swap code/resource changes on depoly'</p>


答:
You could create a simple spinner with only one element and different border styles.   </p>

```<code>.loader{
    border: 2px solid #CECECE;
    border-top-color: #14B48C;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    animation: spin 1s infinite;
}

@keyframes spin{
    from{transform: rotate(0deg);}
    to{transform: rotate(360deg);}
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Spinner with transparent background?

Body:
You could create a simple spinner with only one element and different border styles.

.loader{
    border: 2px solid #CECECE;
    border-top-color: #14B48C;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    animation: spin 1s infinite;
}

@keyframes spin{
    from{transform: rotate(0deg);}
    to{transform: rotate(360deg);}
}


问:
webpack-dev-server - support for POST, PUT, Delete Methods using proxy
I am using webpack-dev-server as a proxy to my original API URL to avoid CORS related issues and dynamically pointing to Dev, UAT, Mock server URL based on the environments.

For Mock dev - I prefer to use the JSON from the local file system and it servers its purpose for all the GET request.

How to to add support for 'POST, PUT, DELETE' so that the local JSON can be served directly?

One possible approach may be - Overriding the HTTP Request methods to GET as I am not passing any payload. But I can't find any configuration for that.

Below is the current configuration :

```<code>if (IS_MOCK_SERVER) {
    devServer.proxy = {
        '/api': {
            target: 'http://localhost:9090/data',
            secure: false,
            pathRewrite: function(req, options) {
                return req + '.json'
            }
        }
    }
} else {
    devServer.proxy = {
        '/api': {
            target: 'http://dev-server-url.com',
            secure: false
        }
    }
}
</code>```

I tried digging into the official documents, but didn't get much support on this topic.

The Webpack dev server makes use of http-proxy-middleware to optionally proxy requests to a separate, possibly external, backend server.

答:
As the Webpack dev server internally makes use of http-proxy-middleware to optionally proxy requests to other servers.

So, I opened a ticket at : https://github.com/chimurai/http-proxy-middleware/issues/151

Would be looking for a better solution in future.

But for time being, I found one workaround for the requirement/problem by Overriding the HTTP Method in API Util itself before passing it to Webpack-dev-server.

```<code>// Convert all the Request Method to Get ***ONLY IF*** MOCK-Server is running
if (process.env.IS_MOCK_SERVER) {
    payload.method = 'get';
}
</code>```

Body:
I am using webpack-dev-server as a proxy to my original API URL to avoid CORS related issues and dynamically pointing to Dev, UAT, Mock server URL based on the environments.

For Mock dev - I prefer to use the JSON from the local file system and it servers its purpose for all the GET request.

How to to add support for 'POST, PUT, DELETE' so that the local JSON can be served directly?

One possible approach may be - Overriding the HTTP Request methods to GET as I am not passing any payload. But I can't find any configuration for that.

Below is the current configuration :

if (IS_MOCK_SERVER) {
    devServer.proxy = {
        '/api': {
            target: 'http://localhost:9090/data',
            secure: false,
            pathRewrite: function(req, options) {
                return req + '.json'
            }
        }
    }
} else {
    devServer.proxy = {
        '/api': {
            target: 'http://dev-server-url.com',
            secure: false
        }
    }
}

I tried digging into the official documents, but didn't get much support on this topic.

The Webpack dev server makes use of http-proxy-middleware to optionally proxy requests to a separate, possibly external, backend server.

Body:
As the Webpack dev server internally makes use of http-proxy-middleware to optionally proxy requests to other servers.

So, I opened a ticket at : https://github.com/chimurai/http-proxy-middleware/issues/151

Would be looking for a better solution in future.

But for time being, I found one workaround for the requirement/problem by Overriding the HTTP Method in API Util itself before passing it to Webpack-dev-server.

// Convert all the Request Method to Get ***ONLY IF*** MOCK-Server is running
if (process.env.IS_MOCK_SERVER) {
    payload.method = 'get';
}


问:
Are my subclasses causing memory leaks?
I'm subclassing UINavigationController and UITableview and for some reason, my views are leaking memory, although I've implemented all of the proper methods and release calls. When I use the native class instead of a subclass, everything works just fine, without leaking.

EDIT:

Here's my superclass header:

```<code>//
//  MBAbstractViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MBAbstractViewController : UIViewController {
    IBOutlet UIImageView *backgroundImageView;
    NSString *announcementText;
}

@property (nonatomic, retain) NSString *type;
@property (nonatomic, retain) NSDictionary *options;
@property (nonatomic, retain) NSString *announcementText;

-(void) setAnnouncementText:(NSString *)text;

@end
</code>```

Superclass implementation:

```<code>//
//  MBAbstractViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAbstractViewController.h"

@implementation MBAbstractViewController

@synthesize type, options, announcementText;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    UIColor *clearColor = [[UIColor alloc] colorWithAlphaComponent:0.0];
    [self.view setBackgroundColor: clearColor];
    [clearColor release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||  interfaceOrientation == UIInterfaceOrientationLandscapeRight){
        return YES;
    }else{
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

}

- (void)dealloc {
    [announcementText release];
    [options release];
    [type release];
    [super dealloc];
}

@end
</code>```

Here's my subclass header:

```<code>//
//  MBAnnouncementViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "MBAbstractViewController.h"

@interface MBAnnouncementViewController : MBAbstractViewController {
    IBOutlet UILabel *announcement;
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size;

@end
</code>```

and the subclass implementation:

```<code>        //
//  MBAnnouncementViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAnnouncementViewController.h"
#import "Constants.h"[

@implementation MBAnnouncementViewController

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    [announcement setText:announcementText];

    UIImage *slideImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_slide", kTheme]description] ofType:@"png"]];
    [backgroundImageView setImage:slideImage];
    [slideImage release];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size{
    UIFont *font = [[UIFont alloc] fontWithSize:size];
    [announcement setFont:font];
    [font release];
    [announcement setText:text];

}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [announcementText release];
    [super dealloc];
}

@end
</code>```

What could be causing memory leaks in a subclass? Am I missing something? (There is more relevant code here.)

答:
You should not be alloc'ing UIColor in this way:

```<code>[[UIColor alloc] colorWithAlphaComponent:0.0];
</code>```

You've alloc'd the instance without initializing it, then you've called a factory method and lost the reference to the instance you alloc'd.

You'll want to call one of the initializers before calling colorWithAlphaComponent:.  I'm not sure what the behaviour will be if you don't do so.  Why not just [UIColor clearColor];?

You're making the same mistake with UIFont too:

```<code>UIFont *font = [[UIFont alloc] fontWithSize:size];
</code>```

You should never do this.  The only methods you chain onto +alloc should be initializers (which always return whatever was alloc'd).  You're leaking here, and also getting some weird unintended behaviour I dare say.

Also, as David Liu says, you appear to be over-releasing announcementText and under-releasing announcement, which will cause both a crash and a leak, depending on how lucky you get.

EDIT | Based on your update that shows your header files, there are further issues (not specifically related to leaks).

```<code>@property (nonatomic, retain) NSString *announcementText;
</code>```

You should never retain NSString*; instead you should copy it.

```<code>@property (nonatomic, copy) NSString *announcementText;
</code>```

This is because NSString* might actually be a mutable string and be changed later.  You may use retain if you're specifically wanting this however.

You also do not need to expressly declare -setAnnouncementText: when you have the @property announcementText.

In your subclass setAnnouncementText:withSize: actually does nothing to the announcementText ivar, which is confusing I guess.  You'll want to release the announcement ivar and fix the issue with UIColor and UIFont being used incorrectly (which are leaking).

ContentLicense: CC BY-SA 2.5

Title: Are my subclasses causing memory leaks?

Body:
I'm subclassing UINavigationController and UITableview and for some reason, my views are leaking memory, although I've implemented all of the proper methods and release calls. When I use the native class instead of a subclass, everything works just fine, without leaking.

EDIT:

Here's my superclass header:

//
//  MBAbstractViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MBAbstractViewController : UIViewController {
    IBOutlet UIImageView *backgroundImageView;
    NSString *announcementText;
}

@property (nonatomic, retain) NSString *type;
@property (nonatomic, retain) NSDictionary *options;
@property (nonatomic, retain) NSString *announcementText;

-(void) setAnnouncementText:(NSString *)text;

@end

Superclass implementation:

//
//  MBAbstractViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAbstractViewController.h"

@implementation MBAbstractViewController

@synthesize type, options, announcementText;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    UIColor *clearColor = [[UIColor alloc] colorWithAlphaComponent:0.0];
    [self.view setBackgroundColor: clearColor];
    [clearColor release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||  interfaceOrientation == UIInterfaceOrientationLandscapeRight){
        return YES;
    }else{
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

}

- (void)dealloc {
    [announcementText release];
    [options release];
    [type release];
    [super dealloc];
}

@end

Here's my subclass header:

//
//  MBAnnouncementViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "MBAbstractViewController.h"

@interface MBAnnouncementViewController : MBAbstractViewController {
    IBOutlet UILabel *announcement;
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size;

@end

and the subclass implementation:

        //
//  MBAnnouncementViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAnnouncementViewController.h"
#import "Constants.h"[

@implementation MBAnnouncementViewController

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    [announcement setText:announcementText];

    UIImage *slideImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_slide", kTheme]description] ofType:@"png"]];
    [backgroundImageView setImage:slideImage];
    [slideImage release];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size{
    UIFont *font = [[UIFont alloc] fontWithSize:size];
    [announcement setFont:font];
    [font release];
    [announcement setText:text];

}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [announcementText release];
    [super dealloc];
}

@end

What could be causing memory leaks in a subclass? Am I missing something? (There is more relevant code here.)

Body:
You should not be alloc'ing UIColor in this way:

[[UIColor alloc] colorWithAlphaComponent:0.0];

You've alloc'd the instance without initializing it, then you've called a factory method and lost the reference to the instance you alloc'd.

You'll want to call one of the initializers before calling colorWithAlphaComponent:.  I'm not sure what the behaviour will be if you don't do so.  Why not just [UIColor clearColor];?

You're making the same mistake with UIFont too:

UIFont *font = [[UIFont alloc] fontWithSize:size];

You should never do this.  The only methods you chain onto +alloc should be initializers (which always return whatever was alloc'd).  You're leaking here, and also getting some weird unintended behaviour I dare say.

Also, as David Liu says, you appear to be over-releasing announcementText and under-releasing announcement, which will cause both a crash and a leak, depending on how lucky you get.

EDIT | Based on your update that shows your header files, there are further issues (not specifically related to leaks).

@property (nonatomic, retain) NSString *announcementText;

You should never retain NSString*; instead you should copy it.

@property (nonatomic, copy) NSString *announcementText;

This is because NSString* might actually be a mutable string and be changed later.  You may use retain if you're specifically wanting this however.

You also do not need to expressly declare -setAnnouncementText: when you have the @property announcementText.

In your subclass setAnnouncementText:withSize: actually does nothing to the announcementText ivar, which is confusing I guess.  You'll want to release the announcement ivar and fix the issue with UIColor and UIFont being used incorrectly (which are leaking).


问:
I want to create a listview like in play store installed apps fragment
I want to create a list view which shows some detail (batch name in my case) on the top of some listview items like this screenshot of play store. Here it shows downloading on top of a few items and updates or installed on others. How can I do this?</p>

答:
Your official reference for creating RecyclerView:

Creating Lists and Cards

Also, you may follow this:

Using lists and grids in Android with RecylerView - Tutorial

You will exactly get the most of building RecyclerView considering design patterns

Here is an example of creating RecyclerView with header:

```<code>    public class HeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;
    String[] data;

    public HeaderAdapter(String[] data) {
        this.data = data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            //inflate your layout and pass it to view holder
            return new VHItem(null);
        } else if (viewType == TYPE_HEADER) {
            //inflate your layout and pass it to view holder
            return new VHHeader(null);
        }

        throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof VHItem) {
            String dataItem = getItem(position);
            //cast holder to VHItem and set data
        } else if (holder instanceof VHHeader) {
            //cast holder to VHHeader and set data for header.
        }
    }

    @Override
    public int getItemCount() {
        return data.length + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position))
            return TYPE_HEADER;

        return TYPE_ITEM;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

    private String getItem(int position) {
        return data[position - 1];
    }

    class VHItem extends RecyclerView.ViewHolder {
        TextView title;

        public VHItem(View itemView) {
            super(itemView);
        }
    }

    class VHHeader extends RecyclerView.ViewHolder {
        Button button;

        public VHHeader(View itemView) {
            super(itemView);
        }
    }
}
</code>```

Body:
Your official reference for creating RecyclerView:

Creating Lists and Cards

Also, you may follow this:

Using lists and grids in Android with RecylerView - Tutorial

You will exactly get the most of building RecyclerView considering design patterns

Here is an example of creating RecyclerView with header:

    public class HeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;
    String[] data;

    public HeaderAdapter(String[] data) {
        this.data = data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            //inflate your layout and pass it to view holder
            return new VHItem(null);
        } else if (viewType == TYPE_HEADER) {
            //inflate your layout and pass it to view holder
            return new VHHeader(null);
        }

        throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof VHItem) {
            String dataItem = getItem(position);
            //cast holder to VHItem and set data
        } else if (holder instanceof VHHeader) {
            //cast holder to VHHeader and set data for header.
        }
    }

    @Override
    public int getItemCount() {
        return data.length + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position))
            return TYPE_HEADER;

        return TYPE_ITEM;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

    private String getItem(int position) {
        return data[position - 1];
    }

    class VHItem extends RecyclerView.ViewHolder {
        TextView title;

        public VHItem(View itemView) {
            super(itemView);
        }
    }

    class VHHeader extends RecyclerView.ViewHolder {
        Button button;

        public VHHeader(View itemView) {
            super(itemView);
        }
    }
}


问:
Converting NSString to char byte array
In my program, I receive a NSString like this one : AA010158AA7D385002. And I need to pass it to a method which accept a char byte array, as below :

```<code>char[9] = {0xAA, 0x01, 0x01, 0x58, 0xAA, 0x7D, 0x38, 0x50, 0x02};
</code>```

How to convert my NSString to char byte array like this one?

Thanks!

答:
Use this answer if i am correct,i did little coding but might be there are possibilities of simpler solutions also like @user3182143

```<code>NSString * inputStr = @"AA010158AA7D385002";
NSMutableArray *charByteArray = [[NSMutableArray alloc]initWithCapacity:1];
int i = 0;
for (i = 0; i+2 <= inputStr.length; i+=2) {

    NSRange range = NSMakeRange(i, 2);
    NSString* charStr = [inputStr substringWithRange:range];
    [charByteArray addObject:[NSString stringWithFormat:@"0x%@",charStr]];

}
</code>```

Output :

char[9] = (
      0xAA,
      0x01,
      0x01,
      0x58,
      0xAA,
      0x7D,
      0x38,
      0x50,
      0x02
  )

Title: Converting NSString to char byte array

Body:
In my program, I receive a NSString like this one : AA010158AA7D385002. And I need to pass it to a method which accept a char byte array, as below :

char[9] = {0xAA, 0x01, 0x01, 0x58, 0xAA, 0x7D, 0x38, 0x50, 0x02};

How to convert my NSString to char byte array like this one?

Thanks!

Body:
Use this answer if i am correct,i did little coding but might be there are possibilities of simpler solutions also like @user3182143

NSString * inputStr = @"AA010158AA7D385002";
NSMutableArray *charByteArray = [[NSMutableArray alloc]initWithCapacity:1];
int i = 0;
for (i = 0; i+2 <= inputStr.length; i+=2) {

    NSRange range = NSMakeRange(i, 2);
    NSString* charStr = [inputStr substringWithRange:range];
    [charByteArray addObject:[NSString stringWithFormat:@"0x%@",charStr]];

}

Output :

char[9] = (
      0xAA,
      0x01,
      0x01,
      0x58,
      0xAA,
      0x7D,
      0x38,
      0x50,
      0x02
  )


问:
Retrofit - android.os.NetworkOnMainThreadException
I am using Retrofit 2 to get json and parse it to POJO. My purpose is getting one value of that object.

```<code>compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
</code>```

My REST client:

```<code>public interface MyClient {

    @GET("/part1/part2")
    Call<MyItem> getMyItem(@Query("param1") String param1,
                                                 @Query("param2") String param2,
                                                 @Query("param3") String param3);

}
</code>```

Here I found great great tool to create service:

```<code>public class ServiceGenerator {

    public static final String API_BASE_URL = "http://my.api.com";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
    }
}
</code>```

Then I am creating new service using Service generator class:

```<code>MyClient api = ServiceGenerator.createService(MyClient.class);
        Call<MyItem> call = api.getMyItem(param1, param2, param3);
        MyItem myItem= null;
        try {
            myItem= call.execute().body();
            Log.d("MyTag", myItem.getValue());
        } catch (IOException e) {
            e.printStackTrace();
        }
</code>```

When I am trying to run this code I am getting this error:

android.os.NetworkOnMainThreadException
                                                                at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
                                                                at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
                                                                at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
                                                                at java.net.InetAddress.getAllByName(InetAddress.java:215)
                                                                at okhttp3.Dns$1.lookup(Dns.java:39)
                                                                at okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173)
                                                                at okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139)
                                                                at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81)
                                                                at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
                                                                at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:127)
                                                                at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
                                                                at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:289)
                                                                at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:241)
                                                                at okhttp3.RealCall.getResponse(RealCall.java:240)
                                                                at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198)
                                                                at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160)
                                                                at okhttp3.RealCall.execute(RealCall.java:57)
                                                                at retrofit2.OkHttpCall.execute(OkHttpCall.java:177)
                                                                at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:87)
                                                                at uz.cp.ox.data.MyRepository.getMyItem(MyRepository.java:31)
                                                                at uz.cp.ox.presenters.MyPresenter.do(MyPresenter.java:30)
                                                                at uz.cp.ox.activities.MyActivity.onClick(MyActivity.java:52)
                                                                at android.view.View.performClick(View.java:4756)
                                                                at android.view.View$PerformClick.run(View.java:19749)
                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                at android.os.Looper.loop(Looper.java:135)
                                                                at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

I thought that Retrofit automatically does the job in the background thread. Or I misunderstood something. What is wrong in this situation and how to solve it?

答:
In Retrofit Two Types of Method execution takes place-
Enqueue - Works on background thread automatically handle by retrofit.
Execute - Works on UI thread manually required to put in either background thread or take help of async task.

Body:
I am using Retrofit 2 to get json and parse it to POJO. My purpose is getting one value of that object.

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'

My REST client:

public interface MyClient {

    @GET("/part1/part2")
    Call<MyItem> getMyItem(@Query("param1") String param1,
                                                 @Query("param2") String param2,
                                                 @Query("param3") String param3);

}

Here I found great great tool to create service:

public class ServiceGenerator {

    public static final String API_BASE_URL = "http://my.api.com";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
    }
}

Then I am creating new service using Service generator class:

MyClient api = ServiceGenerator.createService(MyClient.class);
        Call<MyItem> call = api.getMyItem(param1, param2, param3);
        MyItem myItem= null;
        try {
            myItem= call.execute().body();
            Log.d("MyTag", myItem.getValue());
        } catch (IOException e) {
            e.printStackTrace();
        }

When I am trying to run this code I am getting this error:

android.os.NetworkOnMainThreadException
                                                                at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
                                                                at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
                                                                at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
                                                                at java.net.InetAddress.getAllByName(InetAddress.java:215)
                                                                at okhttp3.Dns$1.lookup(Dns.java:39)
                                                                at okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173)
                                                                at okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139)
                                                                at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81)
                                                                at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
                                                                at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:127)
                                                                at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
                                                                at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:289)
                                                                at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:241)
                                                                at okhttp3.RealCall.getResponse(RealCall.java:240)
                                                                at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198)
                                                                at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160)
                                                                at okhttp3.RealCall.execute(RealCall.java:57)
                                                                at retrofit2.OkHttpCall.execute(OkHttpCall.java:177)
                                                                at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:87)
                                                                at uz.cp.ox.data.MyRepository.getMyItem(MyRepository.java:31)
                                                                at uz.cp.ox.presenters.MyPresenter.do(MyPresenter.java:30)
                                                                at uz.cp.ox.activities.MyActivity.onClick(MyActivity.java:52)
                                                                at android.view.View.performClick(View.java:4756)
                                                                at android.view.View$PerformClick.run(View.java:19749)
                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                at android.os.Looper.loop(Looper.java:135)
                                                                at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

I thought that Retrofit automatically does the job in the background thread. Or I misunderstood something. What is wrong in this situation and how to solve it?


问:
Bitbucket repository started returning "remote: Too many invalid password attempts. Try logging in through the website." (403) since yesterday
Since yesterday, bitbucket repository started returning this on any request:

```<code>remote: Too many invalid password attempts. Try logging in through the website.
fatal: unable to access 'https://xxxxxxxxx@bitbucket.org/xxxxxxxxxx/xxxxxxxxxxx.git/': The requested URL returned error: 403
</code>```

This happens on both the server (trying to git pull) and client (SourceTree on mac).

The user employed on both sides is the same, I can login to bitbucket and see no problems.
Both SourceTree and git on the server use different "App Password" generated in bitbucket.
I am the only person using this account daily.

I created a new App Password and tried with it just to get the same error.

What can I do to solve the case?

Update #1: Generating a new App Password does not work for both server and client. Re-adding a SourceTree account with Basic authentication does not help too. Bitbucket even does not allow to come to authentication, as it seems - the new App Passwords "Last Access" snows nothing.

Update #2: The accepted answer is indeed a solution. This is quite strange, but resetting the password of the main bitbucket user account works. But the sequence is as follows: reset bitbucket user password; create a new app password for both server and client (SourceTree); for mac, remove the record for bitbucket in KeyChain Access; only try to pull or push from SourceTree after removing the record or the account is locked immediately!

答:
Atlassian have just released a fix:

Hi there,

We just deployed the fix for the root issue causing this bug. If you
  could please retry your actions, and let us know if you run in to any
  further issues.

We recommend that, you log out of Bitbucket Cloud and login once
  again. Then please retry again.

We apologize for any delays, or outages this issue may have caused
  you, and your teams. Please feel free to let us know if you have any
  questions.

Thank you,
  Pravin

Update 2017-03-30:

Hi Everyone,

For the past few days some users may have experienced 503 or 403
  errors related to authentication issues when using Git and Mercurial
  over HTTPS on Bitbucket Cloud.

We have just deployed a fix to the platform for this issue. If you
  could please navigate to "id.atlassian.com" in your browser, and make
  sure you log out of any active sessions.

If you could then attempt to login to id.atlassian.com with your
  email, and password - please make sure to NOT use the Google login
  form, and instead use the basic email/password fields. You may be
  asked to go through a captcha screen, or even reset your password if
  necessary.

Once you get logged in properly to id.atlassian.com, if you could
  please try your GIT/Mercurial operations again, and let us know if you
  are able to successfully authenticate.

Please let us know if you encounter any issues, or have any questions.

We would again like to thank you for your patience, and apologize for
  any downtime these issues may have caused you or your team.

Thank you, The Bitbucket Cloud Team

Body:
Since yesterday, bitbucket repository started returning this on any request:

remote: Too many invalid password attempts. Try logging in through the website.
fatal: unable to access 'https://xxxxxxxxx@bitbucket.org/xxxxxxxxxx/xxxxxxxxxxx.git/': The requested URL returned error: 403

This happens on both the server (trying to git pull) and client (SourceTree on mac).

The user employed on both sides is the same, I can login to bitbucket and see no problems.
Both SourceTree and git on the server use different "App Password" generated in bitbucket.
I am the only person using this account daily.

I created a new App Password and tried with it just to get the same error.

What can I do to solve the case?

Update #1: Generating a new App Password does not work for both server and client. Re-adding a SourceTree account with Basic authentication does not help too. Bitbucket even does not allow to come to authentication, as it seems - the new App Passwords "Last Access" snows nothing.

Update #2: The accepted answer is indeed a solution. This is quite strange, but resetting the password of the main bitbucket user account works. But the sequence is as follows: reset bitbucket user password; create a new app password for both server and client (SourceTree); for mac, remove the record for bitbucket in KeyChain Access; only try to pull or push from SourceTree after removing the record or the account is locked immediately!


问:
Error on substr(explode)
Do you have any idea what I did wrong in the code row below.
Get an error from my DW editor with no description.</p>

```<code>$oauth = explode('&',base64_decode($_POST['oauth_token'])); // is ak
$user_id = substr(explode('=',$oauth['1'])['1'],4); // get error
</code>```

答:
try to remove the ' after explode like that :</p>

```<code>$user_id = substr(explode('=',$oauth['1'])[1],4);
</code>```

Title: Error on substr(explode)

Body:
Do you have any idea what I did wrong in the code row below.
Get an error from my DW editor with no description.

$oauth = explode('&',base64_decode($_POST['oauth_token'])); // is ak
$user_id = substr(explode('=',$oauth['1'])['1'],4); // get error

Body:
try to remove the ' after explode like that :

$user_id = substr(explode('=',$oauth['1'])[1],4);


问:
Bug in Deleting Row on UITableView at Multiple time delete row
Two bug in this code.

First one when i delete Row in tableview delete last row not selected row.

Second Bug is when try to delete more than one row that time will delete successfully but when reload tableview Only one row deleted. Rest row will appear again.

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
      return result.count;
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];
        if (!(cell == nil)) {
              name = (UILabel *)[cell viewWithTag:10];
              name.text = [result objectAtIndex : indexPath.row];
        }
        name.tag=indexPath.row;
            return cell;
    }
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        return YES;
    }
    - (IBAction)action:(id)sender {
        [_myTableView setEditing:YES animated:YES];
    }
    - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return UITableViewCellEditingStyleDelete;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];
        if (!(cell == nil)) {
              name = (UILabel *)[cell viewWithTag:10];
              name.text = [result objectAtIndex : indexPath.row];
        }
        name.tag=indexPath.row;
            return cell;
    }
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        return YES;
    }

    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) {

            [result removeObjectAtIndex:indexPath.row];
            [tableView reloadData];
            [spinner startAnimating];
            NSString *id = [profile objectForKey:@"user_id"];
            NSString *tb =tid;

            NSString *string = [NSString stringWithFormat:@"userid=%@&topiid=%@",id,tb];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"myDeleteUrl"]];

            NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            [request setHTTPMethod:@"POST"];
            [request setHTTPBody : data];
            NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration
defaultSessionConfiguration]]; [[session dataTaskWithRequest : request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

                NSDictionary *JSON= [NSJSONSerialization JSONObjectWithData :data options :NSJSONReadingMutableContainers error: nil];

               NSArray *alertArray = [JSON objectForKey:@"deletebookmark"];

                for (NSDictionary *alert in alertArray ){

                    if ([[alert objectForKey:@"status"] isEqualToString:@"done"]) {
                        NSLog(@"done");
                         [spinner stopAnimating];
                   }
                    else{
                       NSLog(@"notDone");
                        [spinner stopAnimating];
                    }
                 }

            }]resume];

        }
    }
</code>```

答:
Try this way

```<code>[result removeObjectAtIndex:indexPath.row];

[tableView reloadData];// comment this line above code

[spinner stopAnimating];

//After that you can add

[tableView reloadData]; // above stopanimating line.
</code>```

Add this cellForRowAtIndexPath method

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:@"cell"];

    }

    name = (UILabel *)[cell viewWithTag:10];

    name.text = [result objectAtIndex : indexPath.row];

    name.tag=indexPath.row;

    return cell;

 }
</code>```

Body:
Two bug in this code.

First one when i delete Row in tableview delete last row not selected row.

Second Bug is when try to delete more than one row that time will delete successfully but when reload tableview Only one row deleted. Rest row will appear again.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
      return result.count;
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];
        if (!(cell == nil)) {
              name = (UILabel *)[cell viewWithTag:10];
              name.text = [result objectAtIndex : indexPath.row];
        }
        name.tag=indexPath.row;
            return cell;
    }
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        return YES;
    }
    - (IBAction)action:(id)sender {
        [_myTableView setEditing:YES animated:YES];
    }
    - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return UITableViewCellEditingStyleDelete;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];
        if (!(cell == nil)) {
              name = (UILabel *)[cell viewWithTag:10];
              name.text = [result objectAtIndex : indexPath.row];
        }
        name.tag=indexPath.row;
            return cell;
    }
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        return YES;
    }

    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) {

            [result removeObjectAtIndex:indexPath.row];
            [tableView reloadData];
            [spinner startAnimating];
            NSString *id = [profile objectForKey:@"user_id"];
            NSString *tb =tid;

            NSString *string = [NSString stringWithFormat:@"userid=%@&topiid=%@",id,tb];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"myDeleteUrl"]];

            NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            [request setHTTPMethod:@"POST"];
            [request setHTTPBody : data];
            NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration
defaultSessionConfiguration]]; [[session dataTaskWithRequest : request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

                NSDictionary *JSON= [NSJSONSerialization JSONObjectWithData :data options :NSJSONReadingMutableContainers error: nil];

               NSArray *alertArray = [JSON objectForKey:@"deletebookmark"];

                for (NSDictionary *alert in alertArray ){

                    if ([[alert objectForKey:@"status"] isEqualToString:@"done"]) {
                        NSLog(@"done");
                         [spinner stopAnimating];
                   }
                    else{
                       NSLog(@"notDone");
                        [spinner stopAnimating];
                    }
                 }

            }]resume];

        }
    }

Body:
Try this way

[result removeObjectAtIndex:indexPath.row];

[tableView reloadData];// comment this line above code

[spinner stopAnimating];

//After that you can add

[tableView reloadData]; // above stopanimating line.

Add this cellForRowAtIndexPath method

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath : indexPath];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:@"cell"];

    }

    name = (UILabel *)[cell viewWithTag:10];

    name.text = [result objectAtIndex : indexPath.row];

    name.tag=indexPath.row;

    return cell;

 }


问:
Retrieving row data from a JTable using rowindex
How can I retrieve row data from a JTable using its rowindex?

答:
```
<code>

import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;

/**
 * Basic JTable with some convenience methods.
 * @author dvargo
 */
public class ConvenienceTable extends JTable
{

    /**
     * The pop up menu for the table
     */
    private JPopupMenu Pmenu = new JPopupMenu();

    /**
     * Holds the currently being/last row clicked in the table.
     */
    private int rowClicked = -1;

    /**
     * Holds the currently being/last column clicked in the table.
     */
    private int colClicked = -1;

    /**
     * If the table is editable or not
     */
    private boolean isEditable = true;

    /**
     * Default construct that uses the default table model
     */
    public ConvenienceTable()
    {
        super();
        addPopUpMenu();
    }

    /**
     * Constructor that lets you set the table model to use
     * @param model The table model you would like to use
     */
    public ConvenienceTable(AbstractTableModel model)
    {
        super(model);
        addPopUpMenu();
    }

    /**
     * Returns the contents of of a cell as a string
     * @param row The row of the cell
     * @param col The col of the cell
     * @return The string representation of a cell
     */
    public String getValueforCell(int row, int col)
    {
        return (String) getModel().getValueAt(row, col).toString();
    }

    /**
     * Inserts a single row with all cells empty into the table
     */
    public void insertRow()
    {
        //get the model the table is using
        TableModel temp = getModel();
        //cast it so we can do something useful with it
        DefaultTableModel tm = (DefaultTableModel) temp;
        tm.addRow(new Object[]{});
        resizeAndRepaint();
    }

    /**
     * Inserts multiple rows with each cell empty into the table
     * @param numberOfRowsToAdd The number of rows to add to the table
     */
    public void insertRow(int numberOfRowsToAdd)
    {
        //get the model the table is using
        TableModel temp = getModel();
        //cast it so we can do something useful with it
        DefaultTableModel tm = (DefaultTableModel) temp;
        for (int i = 0; i &lt numberOfRowsToAdd; i++)
        {
            tm.addRow(new Object[]{});
        }
    }
        /**
     * Insets a row with the given data as the rows contents
     * @param data The data to input into the row
     */
    public void insertRow(String[] data)
    {
        insertRow();
        int row = getRowCount() - 1;
        int colCounter = 0;
        for(String currData : data)
        {
            setValueAt(currData,row,colCounter);
            colCounter++;
            if(colCounter  &lgt = getColumnCount())
            {
                break;
            }
        }
    }

    /**
     * Inserts a column at the end of the columns.
     * @param colName The name for this column
     */
    public void insertColumn(String colName)
    {
        //get the model the table is using
        TableModel temp = getModel();
        //cast it so we can do something useful with it
        DefaultTableModel tm = (DefaultTableModel) temp;
        tm.addColumn(colName, new Object[]
                {
                });
        getTableHeader().resizeAndRepaint();
        resizeAndRepaint();
    }

    /**
     * Inserts a multiple columns into the table
     * @param numberOfColumns The number of columns to add to the table
     */
    public void insertColumn(int numberOfColumns)
    {
        //get the model the table is using
        TableModel temp = getModel();
        //cast it so we can do something useful with it
        DefaultTableModel tm = (DefaultTableModel) temp;
        for (int i = 0; i &lt numberOfColumns; i++)
        {
            tm.addColumn(new Integer(i).toString(), new Object[]
                    {
                    });
            getTableHeader().resizeAndRepaint();
        }
    }

    /**
     * Deletes a row from the table at a given index
     * @param rowIndex The row index to delete. Row index 0 is below the column
     * headers
     */
    public void deleteRow(int rowIndex)
    {
        if (rowIndex &lt 0)
        {
            return;
        }
        //get the model the table is using
        TableModel temp = getModel();
        //cast it so we can do something useful with it
        DefaultTableModel tm = (DefaultTableModel) temp;
        tm.removeRow(rowIndex);
        getTableHeader().resizeAndRepaint();
    }

    /**
     * Delete a column from the table
     * @param colIndex The index of the column to delete
     */
    public void deleteColumn(int colIndex)
    {
        if (colIndex &lt 1)
        {
            return;
        }
        removeColumn(getColumnModel().getColumn(colIndex));
        getTableHeader().resizeAndRepaint();
    }

    /**
     * Changes the name of a column
     * @param colIndex The index of the column to change name
     * @param newName The name of the column
     */
    public void setColumnName(int colIndex, String newName)
    {
        getColumnModel().getColumn(colIndex).setHeaderValue(newName);
        getTableHeader().resizeAndRepaint();
    }

    /**
     * Sets the columns of the table
     */
    public void setColumnNames(String[] names)
    {
        setNumberOfCols(names.length);
        for (int i = 0; i &lt names.length; i++)
        {
            setColumnName(i, names[i]);
        }
    }

    /**
     * Sets the number of row in the table to a certain value. The rows are added
     * to the end of the table
     * @param numberOfRows The number of rows that should be in the table
     *
     */
    public void setNumberOfRows(int numberOfRows)
    {
        if (numberOfRows == getRowCount() || numberOfRows &lt 0) //user requested the same number of rows
        {
            return;
        }
        else if (numberOfRows  &lgt  getRowCount()) //user requested more rows
        {
            int numberOfRowsToAdd = Math.abs(getRowCount() - numberOfRows);
            insertRow(numberOfRowsToAdd);
        }
        else if (numberOfRows &lt getRowCount()) //user request les rows
        {
            int numberOfRowsToDelete = Math.abs(getRowCount() - numberOfRows);
            for (int i = 0; i &lt numberOfRowsToDelete; i++)
            {
                deleteRow(getRowCount() - 1);
            }
        }
        resizeAndRepaint();
    }

    /**
     * Sets the number of cols for the table. The columns are added and deleted
     * at the end of the table
     * @param numberOfCols
     */
    public void setNumberOfCols(int numberOfCols)
    {
        //user requested the same number of rows
        if (numberOfCols == getColumnCount() || numberOfCols &lt 0)
        {
            return;
        }
        else if (numberOfCols  &lgt  getColumnCount()) //user requested more rows
        {
            int numberOfColsToAdd = Math.abs(getColumnCount() - numberOfCols);
            insertColumn(numberOfColsToAdd);
        }
        else if (numberOfCols  getColumnCount()) //user request les rows
        {
            int numberOfColsToDelete = Math.abs(getColumnCount() - numberOfCols);
            for (int i = 0; i  &lt  numberOfColsToDelete; i++)
            {
                deleteColumn(getColumnCount() - 1);
            }
        }
        resizeAndRepaint();
    }

    /**
     * Returns the string name value of the column
     * @param colIndex The index of the column whose name you want
     * @return The name of the column
     */
    public String getColumnName(int colIndex)
    {
        return (String) getColumnModel().getColumn(colIndex).getHeaderValue();
    }

    /**
     * Returns an array holding all the column names
     * @return The column names
     */
    public String[] getColumnNames()
    {
        String[] colNames = new String[getColumnCount()];
        for (int i = 0; i  &lt  getColumnCount(); i++)
        {
            colNames[i] = getColumnName(i);
        }
        return colNames;
    }

    /**
     * Gets the index in the table for a column with the given name
     * @param colName The name of the column
     * @return The index of the column in the table or -1 if it is not found
     */
    public int getColumnIndex(String colName)
    {
        String [] names = getColumnNames();
        int retVal = -1;
        for(int i = 0; i &lt  names.length; i++)
        {
            if(names[i].equals(colName))
            {
                retVal = i;
            }
        }
        return retVal;
    }

    /**
     * Allows the user to paste multiple lines and columns into the table
     * @param row The row where the paste is to start from
     * @param col The column where the paste is to start from
     */
    public void paste(int row, int col)
    {
        //used to determine what info goes in which coloumn of the table
        String newLineDelim = "\n";
        //used to determine what info goes in what cell in a row
        String nextElementDelim = "\t";

        String pasteString = ClipboardUtility.getClipboardContents(); //get this info on the clipboard

        //see if we can handle parsing this string
        if (pasteString.contains(newLineDelim) == false || pasteString.contains(nextElementDelim) == false)
        {
            //paste it all into the first cell if we done recognize it
            setValueAt(pasteString, row, col);
        }

        //parse the columns first
        String[] pasteSplitString = pasteString.split(newLineDelim);

        String[] temp = null;
        String[][] finalInfo = new String[pasteSplitString.length][getColumnCount()];

        //now parse the columns into the individual cells
        for (int i = 0; i  &lt  pasteSplitString.length; i++)
        {
            temp = pasteSplitString[i].split(nextElementDelim);
            finalInfo[i] = temp;
        }

        //put this info in the table
        for (int i = 0; i  &lt  finalInfo.length; i++)
        {
            for (int j = 0; j  &lt  finalInfo[i].length; j++)
            {
                //its in a try catch incase the indexes do not match up, allows us to do a partial paste
                try
                {
                    //see if you need to add a row to the table
                    if (i + row  &lgt  getRowCount() - 1)
                    {
                        insertRow();
                    }
                    getModel().setValueAt(finalInfo[i][j], i + row, j + col);
                }
                catch (Exception e)
                {
                    System.err.println("Could not paste");
                }
            }
        }
    }

    /**
     * Copies the text in the selected cells in the table to the clipboard
     */
    public void copy()
    {
        //were going to use the \t for next column and \n for next row format
        String newCol = "\t";
        String newRow = "\n";

        //index to start coping from
        int rowStart = getSelectedRow();
        int colStart = getSelectedColumn();

        //index to stop copying from
        int colEnd = colStart + getSelectedColumnCount();
        int rowEnd = rowStart + getSelectedRowCount();

        //will hold the string of data were copying
        StringBuilder copyString = new StringBuilder();

        //copy it cell by cell
        for (int row = rowStart; row  &lt  rowEnd; row++)
        {
            if (row != rowStart)
            {
                copyString.append(newRow);
            }
            for (int col = colStart; col  &lt  colEnd; col++)
            {
                String currCellVal = (String) (getValueAt(row, col));
                //so you dont get "null" copied to the clipboard
                if (currCellVal == null)
                {
                    currCellVal = "";
                }
                copyString.append(currCellVal);
                if (col + 1  &lt  colEnd)
                {
                    copyString.append(newCol);
                }
            }
        }

        //post the string to the clipboard
        ClipboardUtility.setClipboardContents(copyString.toString());

    }

    /**
     * Returns the table as a array of strings with the data separated by a delimiter.
     * Each string in the array represents a row in the table.
     * @param delim The delimiter to separate the columns by
     * @return The data in the table
     */
    public String[] getTableData(String delim)
    {
        String[] data = new String[getRowCount()];

        int colCount = getColumnCount();
        int rowCount = getRowCount();

        //get the row data
        StringBuffer currRow = new StringBuffer();
        for (int row = 0; row  &lt  rowCount; row++)
        {
            for (int col = 0; col  &lt  colCount; col++)
            {
                currRow.append(getValueAt(row, col));
                currRow.append(delim);
            }
            data[row] = currRow.toString();
            currRow = new StringBuffer();
        }
        return data;
    }

    /**
     * Returns the data in the table as a 2d string array [row][col]
     * @return The data in the table
     */
    public String[][] getTableData()
    {
        String[][] data = new String[this.getRowCount()][this.getColumnCount()];
        for (int r = 0; r  &lt  getRowCount(); r++)
        {
            for (int c = 0; c  &lt  getColumnCount(); c++)
            {
                data[r][c] = getValueforCell(r, c);
            }
        }
        return data;
    }

    /**
     * Return a row from the table as a array of strings
     * @param rowIndex The index of the row you would like
     * @return Returns the row from the table as an array of strings or null if
     * the index is invalid
     */
    public String[] getRowData(int rowIndex)
    {
        //test the index
        if (rowIndex  &lgt  getRowCount() || rowIndex  &lt  0)
        {
            return null;
        }
        ArrayList &lt String &lgt  data = new ArrayList &lt String &lgt ();
        for (int c = 0; c  &lt  getColumnCount(); c++)
        {
            data.add((String) getValueforCell(rowIndex, c));
        }
        String[] retVal = new String[data.size()];
        for (int i = 0; i  &lt  retVal.length; i++)
        {
            retVal[i] = data.get(i);
        }
        return retVal;
    }

    /**
     * Returns the data for a row as a hash map with the column being the key
     * and the cell being the value
     * @param rowIndex The row to get the data for
     * @return A map represneting the row
     */
    public Map &lt String,String &lgt  getRowDataAsMap(int rowIndex)
    {
        Map &lt String,String &lgt  retVal = new HashMap &lt String, String &lgt ();
        String [] rowData = getRowData(rowIndex);
        String [] colData = getColumnNames();
        for(int i = 0; i  &lt  colData.length; i++)
        {
            retVal.put(colData[i],rowData[i]);
        }
        return retVal;
    }

    /**
     * Sets the data in the table
     * @param data String array of delimited data for the table
     * @param delim The delimeter
     */
    public void setData(String[] data, String delim)
    {
        setNumberOfCols(parseTableData(data[0], delim).length);
        setNumberOfRows(data.length);
        String[] currRow;
        for (int r = 0; r  &lt  data.length; r++)
        {
            currRow = parseTableData(data[r], delim);
            for (int c = 0; c  &lt  currRow.length; c++)
            {
                setValueAt(currRow[c], r, c);
            }
        }
    }

    /**
     * Sets the values in the table
     * @param data
     */
    public void setData(String[][] data)
    {
        setNumberOfRows(data.length);
        setNumberOfCols(data[0].length);
        for (int r = 0; r  &lt  data.length; r++)
        {
            for (int c = 0; c  &lt  data[r].length; c++)
            {
                setValueAt(data[r][c], r, c);
            }
        }
    }

    /**
     * Sets the data for a table starting at a given location in the table
     * @param data The delimited data to add to the table
     * @param delim The delimiter for the data
     * @param row The row where to start adding the data
     * @param col The col where to start adding the table
     */
    public void setData(String[] data, String delim, int row, int col)
    {
        setNumberOfCols(col + parseTableData(data[0], delim).length);
        setNumberOfRows(row + data.length);
        String[] currRow;
        for (int r = row; r  &lt  data.length; r++)
        {
            currRow = parseTableData(data[r], delim);
            for (int c = col; c  &lt  currRow.length; c++)
            {
                setValueAt(currRow[c], r, c);
            }
        }
    }

    /**
     * Removes all the rows in the table
     */
    public void clearTable()
    {
        DefaultTableModel dm = (DefaultTableModel) getModel();
        dm.getDataVector().removeAllElements();
    }

    /**
     * Adds a menu item to the pop up menu with an action listener.
     * @param newItem The menu item to add
     * @param actionListener The actionlistener to add to this menu item
     */
    public void addPopUpMenuItem(JMenuItem newItem, ActionListener actionListener)
    {
        newItem.addActionListener(actionListener);
        Pmenu.add(newItem);
    }

    /**
     * Adds a menu item to the pop up menu. Not this can be as simple Jseparator
     * or a menu item with a actionlistener already attached.
     * @param newItem The menu item to add
     */
    public void addPopUpMenuItem(JMenuItem newItem)
    {
        Pmenu.add(newItem);
    }

    /**
     * Adds a separator to the JMenu
     */
    public void addPopUpMenuSeperator()
    {
        Pmenu.add(new JSeparator());
    }

    /**
     * Gets the current row being clicked
     * @return The current row being clicked
     */
    public int getRowClicked()
    {
        return rowClicked;
    }

    /**
     * Gets the current column being clicked
     * @return The current column being clicked
     */
    public int getColClicked()
    {
        return colClicked;
    }

    /**
     * Adds the pop up menu and additional functionality to the table. The key
     * thing here is that this function adds the action listeners that determine
     * what row and what column is being clicked in the table.
     */
    private void addPopUpMenu()
    {
        //sets the popup menu so it will show
        addMouseListener(new MouseAdapter()
        {

            public void mouseReleased(MouseEvent e)
            {
                rowClicked = rowAtPoint(e.getPoint());
                colClicked = columnAtPoint(e.getPoint());
                if (e.isPopupTrigger())
                {
                    Pmenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }

            public void mouseClicked(MouseEvent e)
            {
                rowClicked = rowAtPoint(e.getPoint());
                colClicked = columnAtPoint(e.getPoint());
            }
        });
    }

    /**
     * Parses out the table data from a string (usually xml) using the passed in
     * delimiter. This is pretty much just like the sting classes split method
     * @param data The data to parse
     * @param delim The delimiter to use
     * @return An array of the tokens parsed out of the data string
     */
    public String[] parseTableData(String data, String delim)
    {
        ArrayList &lt String &lgt  tempArrayHolder = new ArrayList &lt String &lgt ();
        StringTokenizer st = new StringTokenizer(data, delim);
        while (st.hasMoreTokens())
        {
            tempArrayHolder.add(st.nextToken());
        }
        String[] retValArray = new String[tempArrayHolder.size()];
        for (int i = 0; i  &lt  tempArrayHolder.size(); i++)
        {
            retValArray[i] = tempArrayHolder.get(i);
        }
        return retValArray;
    }

    /**
     * Determines if the table is editable or not. Note that this is for the whole
     * table and not individual cells.
     * @param isEditable True if the table is editable, false if the table is not
     * editable
     */
    public void setEditable(boolean isEditable)
    {
        this.isEditable = isEditable;
    }

    /**
     * Overridden to allow the hole table to be set to non editable or editable.
     * Depends on the value of isEditable
     * @param row The for the cell to see if it is editable
     * @param col The col for the cell to see if it is editable
     * @return True if the cell is editable false otherwise
     */
    @Override
    public boolean isCellEditable(int row, int col)
    {
        if (isEditable == false)
        {
            return false;
        }
        return super.isCellEditable(row, col);
    }

    /**
     * Returns the indexes of the selected rows in the table
     * Overridden due to the inconsistent behavior of the default
     * @return A list of the selected rows
     */
    @Override
    public int[] getSelectedRows()
    {
        List &lt Integer &lgt  temp = new ArrayList &lt Integer &lgt ();
        for(int i = 0; i  &lt  getRowCount(); i++)
        {
            if(isRowSelected(i))
            {
                temp.add(i);
            }
        }
        int [] retVal = new int[temp.size()];
        for(int i =0; i  &lt  temp.size(); i++)
        {
            retVal[i] = temp.get(i);
        }
        return retVal;
    }

}

 </code>
 ```