问:
"bash: django-admin: command not found" after running django-admin
I had similar problems with pip that was fixed with "python3 -m" but now after install Django I want to make a new project.

When I try to run "django-admin startproject ..." I get "bash: django-admin: command not found".

I don't know if I should mention it but, this is in a virtualenv.

python3 -m pip freeze: Django==3.0.6

echo $PATH: /home/alatimer/Environments/DjangoTutoria_env/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

答:
Your problem is that your shell doesn't know where that program is, and the places it searches doesn't have it.

Notably, the shell would look for a program specifically if the name were qualified some way, where you name a location at the start. So, you could use "/long/path/to/django-admin" or "./django-admin" (if it's in the "." current directory).

Always qualify names that aren't standard programs. It isn't safe to mutate PATH to include a path relative to your current directory .. Instead, name your personal programs with location when you run them, ./program .


来源: stackexchange

问:
POJO class from JSON with a value that can either be string on integer
I have a JSON file with a value "code" that can either be a string or an integer.

```<code>{
    "code": 110005,
    "name": "abcd"
},
{
    "code": "090270",
    "name": "efgh"
}
</code>```

How do I create a POJO class with this?
Expected Output is string

答: Just create POJO with String. Whatever the value you provide for the fields, a String or integer, it would be considered as String in code. </p>

ContentLicense: CC BY-SA 4.0

Body:
I have a JSON file with a value "code" that can either be a string or an integer.

{
    "code": 110005,
    "name": "abcd"
},
{
    "code": "090270",
    "name": "efgh"
}

How do I create a POJO class with this?
Expected Output is string


问:
How to store y_pred variable result from “for-lop” values in numpy array or list?
I am writing code for SVR. I have datasets that have more than 2000 rows and 22 columns. After prediction at every iteration for y_pred by using for loop so I need to store all of the y_pred values which come from for loop. I want to store these values in a list or a numpy array. I am writing my code but it does not work. Please help me to write this code in a proper way. I know the role that is

```<code>numpyarray = np.empty((1001,2000, 23))
for i in range(1001):
    numpyarray[i, :] = numpyarrayfunction
</code>```

Comment: But it does not work.

My full Code:

```<code>import pandas as pd
import numpy as np

# Make fake dataset
dataset = pd.DataFrame(data= np.random.rand(2000,22))
dataset['age'] = np.random.randint(2, size=2000)

# Separate the target from the other features
target = dataset['age']
data = dataset.drop('age', axis = 1)

X_train, y_train = data.loc[:1000], target.loc[:1000]

X_test,  y_test  = data.loc[1001], target.loc[1001]

X_test = np.array(X_test).reshape(1, -1)
print(X_test.shape)

SupportVectorRefModel = SVR()
SupportVectorRefModel.fit(X_train, y_train)

y_pred = SupportVectorRefModel.predict(X_test)
y_pred

for i in range(1, 1001):
    X_train, y_train = dataset.iloc[i:1000+i], target.iloc[i:1000+i]
    X_test, y_test = dataset.iloc[i], target.iloc[i]

    X_test = np.array(X_test).reshape(1, -1)
    print(X_test.shape)

    SupportVectorRefModel = SVR()
    SupportVectorRefModel.fit(X_train, y_train)
    y_pred = SupportVectorRefModel.predict(X_test)
</code>```

My current code:

```<code>numpyarray = np.empty((1001,2000, 23))
    for i in range(1001):
        numpyarray[i, :] = numpyarrayfunction
</code>```

答:
Is this what you want? </p>

```<code>from sklearn import svm
import pandas as pd
import numpy  as np

dataset        = pd.DataFrame(data= np.random.rand(2000,22))
dataset['age'] = np.random.randint(2, size=2000)
target         = dataset['age']
data           = dataset.drop('age', axis = 1)

y_pred = np.empty((1000,))
for i in range(1, 1001):
    X_train, y_train = dataset.iloc[i:1000+i], target.iloc[i:1000+i]
    X_test,  y_test  = dataset.iloc[i],        target.iloc[i]
    X_test           = np.array(X_test).reshape(1, -1)
    model            = svm.SVR(gamma='scale') # Avoid the printed future warning.
    model.fit(X_train, y_train)
    y_pred[i-1]      = model.predict(X_test)
print(y_pred)
</code>```

Body:
I am writing code for SVR. I have datasets that have more than 2000 rows and 22 columns. After prediction at every iteration for y_pred by using for loop so I need to store all of the y_pred values which come from for loop. I want to store these values in a list or a numpy array. I am writing my code but it does not work. Please help me to write this code in a proper way. I know the role that is

numpyarray = np.empty((1001,2000, 23))
for i in range(1001):
    numpyarray[i, :] = numpyarrayfunction

Comment: But it does not work.

My full Code:

import pandas as pd
import numpy as np

# Make fake dataset
dataset = pd.DataFrame(data= np.random.rand(2000,22))
dataset['age'] = np.random.randint(2, size=2000)

# Separate the target from the other features
target = dataset['age']
data = dataset.drop('age', axis = 1)

X_train, y_train = data.loc[:1000], target.loc[:1000]

X_test,  y_test  = data.loc[1001], target.loc[1001]

X_test = np.array(X_test).reshape(1, -1)
print(X_test.shape)

SupportVectorRefModel = SVR()
SupportVectorRefModel.fit(X_train, y_train)

y_pred = SupportVectorRefModel.predict(X_test)
y_pred

for i in range(1, 1001):
    X_train, y_train = dataset.iloc[i:1000+i], target.iloc[i:1000+i]
    X_test, y_test = dataset.iloc[i], target.iloc[i]

    X_test = np.array(X_test).reshape(1, -1)
    print(X_test.shape)

    SupportVectorRefModel = SVR()
    SupportVectorRefModel.fit(X_train, y_train)
    y_pred = SupportVectorRefModel.predict(X_test)

My current code:

numpyarray = np.empty((1001,2000, 23))
    for i in range(1001):
        numpyarray[i, :] = numpyarrayfunction

Body:
Is this what you want?

from sklearn import svm
import pandas as pd
import numpy  as np

dataset        = pd.DataFrame(data= np.random.rand(2000,22))
dataset['age'] = np.random.randint(2, size=2000)
target         = dataset['age']
data           = dataset.drop('age', axis = 1)

y_pred = np.empty((1000,))
for i in range(1, 1001):
    X_train, y_train = dataset.iloc[i:1000+i], target.iloc[i:1000+i]
    X_test,  y_test  = dataset.iloc[i],        target.iloc[i]
    X_test           = np.array(X_test).reshape(1, -1)
    model            = svm.SVR(gamma='scale') # Avoid the printed future warning.
    model.fit(X_train, y_train)
    y_pred[i-1]      = model.predict(X_test)
print(y_pred)


问:
Amazon DAX client throws "No endpoints available" exception
I am trying to connect to DAX from a localhost using the following code:

```<code>    ClientConfig daxConfig = new ClientConfig()
            .withEndpoints("dax-cluster.yhdqu5.clustercfg.dax.use1.cache.amazonaws.com:8111");
    AmazonDaxClient client = new ClusterDaxClient(daxConfig);
</code>```

The cluster is up and running, I've created it in a public subnet and opened port 8111 in the security group, but despite this I receive the following exception:

```<code>Caused by: java.io.IOException: No endpoints available
    at com.amazon.dax.client.cluster.Cluster.leaderClient(Cluster.java:560)
    at com.amazon.dax.client.dynamodbv2.ClusterDaxClient$3.getClient(ClusterDaxClient.java:154)
    at com.amazon.dax.client.dynamodbv2.ClusterDaxClient$RetryHandler.makeRequestWithRetries(ClusterDaxClient.java:632)
    ... 10 more
    Suppressed: java.io.IOException: No endpoints available
        ... 13 more
        Suppressed: java.io.IOException: No endpoints available
            ... 13 more
</code>```

Other answers on StackOverflow suggest that this may be caused by incorrectly configured security group and to test it I've launched an instance in the same VPC/subnet and used the same security group and I was able to ssh to this host (both 22nd and 8111-st ports are opened in the security group). So there should be some other DAX related reason.

The firewall on my machine is turned off.

But if I ssh to a machine in EC2, then I can connect to the DAX cluster:

```<code>[ec2-user@ip-10-0-0-44 ~]$ nc -z dax-cluster.yhdqu5.clustercfg.dax.use1.cache.amazonaws.com 8111
Connection to dax-cluster.yhdqu5.clustercfg.dax.use1.cache.amazonaws.com 8111 port [tcp/*] succeeded!
</code>```

答:
There is a way to access it from outside the VPC, You will have to create a NLB which fronts the dax replicas. Then you need to use VPC endpoint service to provide a link which can access this. You can then use the endpoints provided to make calls.

```<code>VPCEndpoint -> NLB -> Dax replica 1
                   -> Dax replica 2
</code>```

You can then used code sample below to connect to DAX

```<code>import com.amazon.dax.client.dynamodbv2.DaxClient;
AmazonDynamoDB amazonDynamoDb = new DaxClient(
                "vpce-XXX-YYY.vpce-svc-ZZZ.us-west-2.vpce.amazonaws.com",
                8111, region, credentials);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to connect to DAX from a localhost using the following code:

    ClientConfig daxConfig = new ClientConfig()
            .withEndpoints("dax-cluster.yhdqu5.clustercfg.dax.use1.cache.amazonaws.com:8111");
    AmazonDaxClient client = new ClusterDaxClient(daxConfig);

The cluster is up and running, I've created it in a public subnet and opened port 8111 in the security group, but despite this I receive the following exception:

Caused by: java.io.IOException: No endpoints available
    at com.amazon.dax.client.cluster.Cluster.leaderClient(Cluster.java:560)
    at com.amazon.dax.client.dynamodbv2.ClusterDaxClient$3.getClient(ClusterDaxClient.java:154)
    at com.amazon.dax.client.dynamodbv2.ClusterDaxClient$RetryHandler.makeRequestWithRetries(ClusterDaxClient.java:632)
    ... 10 more
    Suppressed: java.io.IOException: No endpoints available
        ... 13 more
        Suppressed: java.io.IOException: No endpoints available
            ... 13 more

Other answers on StackOverflow suggest that this may be caused by incorrectly configured security group and to test it I've launched an instance in the same VPC/subnet and used the same security group and I was able to ssh to this host (both 22nd and 8111-st ports are opened in the security group). So there should be some other DAX related reason.

The firewall on my machine is turned off.

But if I ssh to a machine in EC2, then I can connect to the DAX cluster:

[ec2-user@ip-10-0-0-44 ~]$ nc -z dax-cluster.yhdqu5.clustercfg.dax.use1.cache.amazonaws.com 8111
Connection to dax-cluster.yhdqu5.clustercfg.dax.use1.cache.amazonaws.com 8111 port [tcp/*] succeeded!

Body:
There is a way to access it from outside the VPC, You will have to create a NLB which fronts the dax replicas. Then you need to use VPC endpoint service to provide a link which can access this. You can then use the endpoints provided to make calls.

VPCEndpoint -> NLB -> Dax replica 1
                   -> Dax replica 2

You can then used code sample below to connect to DAX

import com.amazon.dax.client.dynamodbv2.DaxClient;
AmazonDynamoDB amazonDynamoDb = new DaxClient(
                "vpce-XXX-YYY.vpce-svc-ZZZ.us-west-2.vpce.amazonaws.com",
                8111, region, credentials);


问:
Coloring x-axis labels for split barplot ggplot2

I'm trying to make a split barplot with different colors for the x-axis labels. I want the x-axis labels (e.g. Vogesella) to show up as the correct color when they are plotted on the graph according to the host species.

As you can see, none of the Vogesella x-axis labels are correct, and they are defaulting to black. I tried using vectorized input to element_text, but I get a warning saying that it isn't officially supported. Is there some workaround I can do to make this possible?

Here is the code that I used to make the simplified barplot.

System Info:
platform       x86_64-apple-darwin15.6.0

arch           x86_64

os             darwin15.6.0

system         x86_64, darwin15.6.0

status

major          3

minor          6.3

year           2020

month          02

day            29

svn rev        77875

language       R

version.string R version 3.6.3 (2020-02-29)
nickname       Holding the Windsock

```<code> df %>%
      ggplot( aes(x = genus, y = avg_rel_abund, fill = host_species))+
      geom_bar(stat = "Identity") +
      facet_grid(cols = vars(host_species), scales = "free") +
      scale_fill_brewer(type = "qual", palette = 1) +
      theme(axis.title.x = element_blank(),
      axis.text.x = element_text(angle = 70, hjust = 1, size = 10,
      color = df$color),
      axis.title.y = element_text(size = 10),
      axis.text.y = element_text(size = 10)) +
      guides(fill = guide_legend(size = 10)) +
      labs( y = "Relative Abundance (Genus)", title = "Day 3 Genera
      Present in Host Phycospheres", fill = "Host Species") +
      scale_y_continuous("Average Relative Abundance") +
      scale_x_reordered()
</code>```

Dataset:

```<code>
    df <- structure(list(genus = structure(c(3L, 1L, 4L, 2L, 5L), .Label = c("Vogesella___Coelastrum",
    "Vogesella___Scenedesmus", "Vogesella___Chlorella", "Vogesella___Monoraphidium",
    "Vogesella___Selenastrum"), class = "factor"), host_species = structure(c(1L,
    2L, 4L, 3L, 5L), .Label = c("Chlorella", "Coelastrum", "Scenedesmus",
    "Monoraphidium", "Selenastrum"), class = "factor"), avg_rel_abund = c(0.0476201763676562,
    0.0723617033127999, 0.0254124767307784, 0.0615452700310325, 0.0124210779718639
    ), time = c("D3", "D3", "D3", "D3", "D3"), color = c("#7FC97F",
    "#BEAED4", "black", "#FDC086", "#386CB0")), row.names = c(NA,
    -5L), class = c("tbl_df", "tbl", "data.frame"))

</code>```

答:
This is one way to do it using geom_col rather than facet_grid. You can adjust the text at the head of the bars and or the plot size to make the text fit.

library(ggplot2)
library(forcats)

ggplot(df, aes(x = fct_inorder(genus, host_species), y = avg_rel_abund, fill = host_species))+
  geom_col() +
  geom_text(aes(label = host_species, y = Inf), vjust = 1, size = 3)+
  scale_fill_brewer(type = "qual", palette = 1) +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(angle = 70, hjust = 1, size = 10,
                                   colour = df$color),
        axis.title.y = element_text(size = 10),
        axis.text.y = element_text(size = 10)) +
  guides(fill = guide_legend(size = 10)) +
  labs(y = "Average Relative Abundance",
       title = "Day 3 Genera\nPresent in Host Phycospheres",
       fill = "Host Species")

```

Created on 2020-05-29 by the reprex package (v0.3.0)

Body:
I'm trying to make a split barplot with different colors for the x-axis labels. I want the x-axis labels (e.g. Vogesella) to show up as the correct color when they are plotted on the graph according to the host species.

As you can see, none of the Vogesella x-axis labels are correct, and they are defaulting to black. I tried using vectorized input to element_text, but I get a warning saying that it isn't officially supported. Is there some workaround I can do to make this possible?

Here is the code that I used to make the simplified barplot.

System Info:
platform       x86_64-apple-darwin15.6.0

arch           x86_64

os             darwin15.6.0

system         x86_64, darwin15.6.0

status

major          3

minor          6.3

year           2020

month          02

day            29

svn rev        77875

language       R

version.string R version 3.6.3 (2020-02-29)
nickname       Holding the Windsock

 df %>%
      ggplot( aes(x = genus, y = avg_rel_abund, fill = host_species))+
      geom_bar(stat = "Identity") +
      facet_grid(cols = vars(host_species), scales = "free") +
      scale_fill_brewer(type = "qual", palette = 1) +
      theme(axis.title.x = element_blank(),
      axis.text.x = element_text(angle = 70, hjust = 1, size = 10,
      color = df$color),
      axis.title.y = element_text(size = 10),
      axis.text.y = element_text(size = 10)) +
      guides(fill = guide_legend(size = 10)) +
      labs( y = "Relative Abundance (Genus)", title = "Day 3 Genera
      Present in Host Phycospheres", fill = "Host Species") +
      scale_y_continuous("Average Relative Abundance") +
      scale_x_reordered()

Dataset:

    df <- structure(list(genus = structure(c(3L, 1L, 4L, 2L, 5L), .Label = c("Vogesella___Coelastrum",
    "Vogesella___Scenedesmus", "Vogesella___Chlorella", "Vogesella___Monoraphidium",
    "Vogesella___Selenastrum"), class = "factor"), host_species = structure(c(1L,
    2L, 4L, 3L, 5L), .Label = c("Chlorella", "Coelastrum", "Scenedesmus",
    "Monoraphidium", "Selenastrum"), class = "factor"), avg_rel_abund = c(0.0476201763676562,
    0.0723617033127999, 0.0254124767307784, 0.0615452700310325, 0.0124210779718639
    ), time = c("D3", "D3", "D3", "D3", "D3"), color = c("#7FC97F",
    "#BEAED4", "black", "#FDC086", "#386CB0")), row.names = c(NA,
    -5L), class = c("tbl_df", "tbl", "data.frame"))

Body:
This is one way to do it using geom_col rather than facet_grid. You can adjust the text at the head of the bars and or the plot size to make the text fit.

library(ggplot2)
library(forcats)

ggplot(df, aes(x = fct_inorder(genus, host_species), y = avg_rel_abund, fill = host_species))+
  geom_col() +
  geom_text(aes(label = host_species, y = Inf), vjust = 1, size = 3)+
  scale_fill_brewer(type = "qual", palette = 1) +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(angle = 70, hjust = 1, size = 10,
                                   colour = df$color),
        axis.title.y = element_text(size = 10),
        axis.text.y = element_text(size = 10)) +
  guides(fill = guide_legend(size = 10)) +
  labs(y = "Average Relative Abundance",
       title = "Day 3 Genera\nPresent in Host Phycospheres",
       fill = "Host Species")

Created on 2020-05-29 by the reprex package (v0.3.0)


问:
Why the compiler complains that std::thread arguments must be invocable after conversion to rvalues?
Why the compiler complains if the the thread function delaration is changed to void thr(std::shared_ptr<Base>& p).Complie error:

gcc-10.1.0/include/c++/10.1.0/thread: In instantiation of
  'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void
  (&)(std::shared_ptr&); _Args = {std::shared_ptr&};
   = void]':
  gcc-10.1.0/include/c++/10.1.0/thread:136:44: error: static assertion
  failed: std::thread arguments must be invocable after conversion to
  rvalues

136 |           typename decay<_Args>::type...>::value,

Can someone explain me, step by step.

I would be grateful for any hint on this question.

```<code>#include <iostream>
#include <memory>
#include <thread>
#include <chrono>
#include <mutex>

struct Base
{
    Base() { std::cout << "  Base::Base()\n"; }
    // Note: non-virtual destructor is OK here
    ~Base() { std::cout << "  Base::~Base()\n"; }
};

struct Derived: public Base
{
    Derived() { std::cout << "  Derived::Derived()\n"; }
    ~Derived() { std::cout << "  Derived::~Derived()\n"; }
};

void thr(std::shared_ptr<Base> p)
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::shared_ptr<Base> lp = p; // thread-safe, even though the
                                  // shared use_count is incremented
    {
        static std::mutex io_mutex;
        std::lock_guard<std::mutex> lk(io_mutex);
        std::cout << "local pointer in a thread:\n"
                  << "  lp.get() = " << lp.get()
                  << ", lp.use_count() = " << lp.use_count() << '\n';
    }
}

int main()
{
    std::shared_ptr<Base> p = std::make_shared<Derived>();

    std::cout << "Created a shared Derived (as a pointer to Base)\n"
              << "  p.get() = " << p.get()
              << ", p.use_count() = " << p.use_count() << '\n';
    std::thread t1(thr, p), t2(thr, p), t3(thr, p);
    p.reset(); // release ownership from main
    std::cout << "Shared ownership between 3 threads and released\n"
              << "ownership from main:\n"
              << "  p.get() = " << p.get()
              << ", p.use_count() = " << p.use_count() << '\n';
    t1.join(); t2.join(); t3.join();

    std::cout << "after joining the threads\n" <<
     "  p.get() = " << p.get() << ", p.use_count() " <<p.use_count() << std::endl;
    std::cout << "All threads completed, the last one deleted Derived\n";
}
</code>```

The outputs:

```<code>Base::Base()
  Derived::Derived()
Created a shared Derived (as a pointer to Base)
  p.get() = 0x57be80, p.use_count() = 1
Shared ownership between 3 threads and released
ownership from main:
  p.get() = 0, p.use_count() = 0
local pointer in a thread:
  lp.get() = 0x57be80, lp.use_count() = 4
local pointer in a thread:
  lp.get() = 0x57be80, lp.use_count() = 3
local pointer in a thread:
  lp.get() = 0x57be80, lp.use_count() = 2
  Derived::~Derived()
  Base::~Base()
after joining the threads
  p.get() = 0, p.use_count() 0
All threads completed, the last one deleted Derived
</code>```

答:
The arguments passed to the std::thread constructor will be copied and then forwarded as rvalues to the function that runs in the new thread. So when you create a std::thread like this:

```<code>std::thread t1(thr, p)
</code>```

the argument p will be copied, then forwarded as an rvalue. If the function thr expects an lvalue reference then it can't be called with an rvalue.

The static assertion is telling that you that you can't call thr(shared_ptr<Base>&) with an rvalue shared_ptr<Base>. (Before I added the static assertion you just got a horrible template instantiation error from deep inside the guts of std::thread, now the idea is that it tells you what's wrong in English).

The solution to passing a reference into the function is to use the std::ref function to create a reference_wrapper object:

```<code>std::thread t1(thr, std::ref(p))
</code>```

This will create a std::reference_wrapper<std::shared_ptr<Base>> which gets copied and forwarded to thr as an rvalue, and then that rvalue can be converted to shared_ptr<Base>& to initialize the parameter of the thr function.

This is also clearly explained at https://en.cppreference.com/w/cpp/thread/thread/thread#Notes

Body:
Why the compiler complains if the the thread function delaration is changed to void thr(std::shared_ptr<Base>& p).Complie error:

gcc-10.1.0/include/c++/10.1.0/thread: In instantiation of
  'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void
  (&)(std::shared_ptr&); _Args = {std::shared_ptr&};
   = void]':
  gcc-10.1.0/include/c++/10.1.0/thread:136:44: error: static assertion
  failed: std::thread arguments must be invocable after conversion to
  rvalues

136 |           typename decay<_Args>::type...>::value,

Can someone explain me, step by step.

I would be grateful for any hint on this question.

#include <iostream>
#include <memory>
#include <thread>
#include <chrono>
#include <mutex>

struct Base
{
    Base() { std::cout << "  Base::Base()\n"; }
    // Note: non-virtual destructor is OK here
    ~Base() { std::cout << "  Base::~Base()\n"; }
};

struct Derived: public Base
{
    Derived() { std::cout << "  Derived::Derived()\n"; }
    ~Derived() { std::cout << "  Derived::~Derived()\n"; }
};

void thr(std::shared_ptr<Base> p)
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::shared_ptr<Base> lp = p; // thread-safe, even though the
                                  // shared use_count is incremented
    {
        static std::mutex io_mutex;
        std::lock_guard<std::mutex> lk(io_mutex);
        std::cout << "local pointer in a thread:\n"
                  << "  lp.get() = " << lp.get()
                  << ", lp.use_count() = " << lp.use_count() << '\n';
    }
}

int main()
{
    std::shared_ptr<Base> p = std::make_shared<Derived>();

    std::cout << "Created a shared Derived (as a pointer to Base)\n"
              << "  p.get() = " << p.get()
              << ", p.use_count() = " << p.use_count() << '\n';
    std::thread t1(thr, p), t2(thr, p), t3(thr, p);
    p.reset(); // release ownership from main
    std::cout << "Shared ownership between 3 threads and released\n"
              << "ownership from main:\n"
              << "  p.get() = " << p.get()
              << ", p.use_count() = " << p.use_count() << '\n';
    t1.join(); t2.join(); t3.join();

    std::cout << "after joining the threads\n" <<
     "  p.get() = " << p.get() << ", p.use_count() " <<p.use_count() << std::endl;
    std::cout << "All threads completed, the last one deleted Derived\n";
}

The outputs:

Base::Base()
  Derived::Derived()
Created a shared Derived (as a pointer to Base)
  p.get() = 0x57be80, p.use_count() = 1
Shared ownership between 3 threads and released
ownership from main:
  p.get() = 0, p.use_count() = 0
local pointer in a thread:
  lp.get() = 0x57be80, lp.use_count() = 4
local pointer in a thread:
  lp.get() = 0x57be80, lp.use_count() = 3
local pointer in a thread:
  lp.get() = 0x57be80, lp.use_count() = 2
  Derived::~Derived()
  Base::~Base()
after joining the threads
  p.get() = 0, p.use_count() 0
All threads completed, the last one deleted Derived

Body:
The arguments passed to the std::thread constructor will be copied and then forwarded as rvalues to the function that runs in the new thread. So when you create a std::thread like this:

std::thread t1(thr, p)

the argument p will be copied, then forwarded as an rvalue. If the function thr expects an lvalue reference then it can't be called with an rvalue.

The static assertion is telling that you that you can't call thr(shared_ptr<Base>&) with an rvalue shared_ptr<Base>. (Before I added the static assertion you just got a horrible template instantiation error from deep inside the guts of std::thread, now the idea is that it tells you what's wrong in English).

The solution to passing a reference into the function is to use the std::ref function to create a reference_wrapper object:

std::thread t1(thr, std::ref(p))

This will create a std::reference_wrapper<std::shared_ptr<Base>> which gets copied and forwarded to thr as an rvalue, and then that rvalue can be converted to shared_ptr<Base>& to initialize the parameter of the thr function.

This is also clearly explained at https://en.cppreference.com/w/cpp/thread/thread/thread#Notes


问:
Unexpected non-equality after assignment
Given the following code:

using System;

class MyClass
{
    public MyClass x;
}

public static class Program
{
    public static void Main()
    {
        var a = new MyClass();
        var b = new MyClass();
        a.x = (a = b);
        Console.WriteLine(a.x == a);
    }
}
```

The first two lines are very obvious, just two different objects.

I assume the third line to do the following:

The part (a = b) assigns b to a and returns b, so now a equals b.

Then, a.x is assigned to b.

That means, a.x equals to b, and also b equals to a. Which implies that a.x equals to a.

However, the code prints False.

What's going on?

答:
In a.x = (a = b), the left hand side a.x is evaluated first to find the assignment target, then the right hand side is evaluated.

This was also surprising to me, because I intuitively think it starts on the rightmost side and evaluates leftward, but this is not the case. (The associativity is right-to-left, meaning the parentheses in this case are not needed.)

Here's the specification calling out the order things happen in, with the relevant bits quoted below:

The run-time processing of a simple assignment of the form x = y consists of the following steps:

If x is classified as a variable:

x is evaluated to produce the variable.

y is evaluated and, if required, converted to the type of x through an implicit conversion.

[...]

The value resulting from the evaluation and conversion of y is stored into the location given by the evaluation of x.

Looking at the IL generated by the sharplab link Pavel posted:

```<code>        // stack is empty []
newobj instance void MyClass::.ctor()
        // new instance of MyClass on the heap, call it $0
        // stack -> [ref($0)]
stloc.0
        // stack -> []
        // local[0] ("a") = ref($0)
newobj instance void MyClass::.ctor()
        // new instance of MyClass on the heap, call it $1
        // stack -> [ref($1)]
stloc.1
        // stack -> []
        // local[1] ("b") = ref($1)
ldloc.0
        // stack -> [ref($0)]
ldloc.1
        // stack -> [ref($1), ref($0)]
dup
        // stack -> [ref($1), ref($1), ref($0)]
stloc.0
        // stack -> [ref($1), ref($0)]
        // local[0] ("a") = ref($1)
stfld class MyClass MyClass::x
        // stack -> []
        // $0.x = ref($1)
</code>```

Body:
Given the following code:

using System;

class MyClass
{
    public MyClass x;
}

public static class Program
{
    public static void Main()
    {
        var a = new MyClass();
        var b = new MyClass();
        a.x = (a = b);
        Console.WriteLine(a.x == a);
    }
}

The first two lines are very obvious, just two different objects.

I assume the third line to do the following:

The part (a = b) assigns b to a and returns b, so now a equals b.

Then, a.x is assigned to b.

That means, a.x equals to b, and also b equals to a. Which implies that a.x equals to a.

However, the code prints False.

What's going on?

Body:
In a.x = (a = b), the left hand side a.x is evaluated first to find the assignment target, then the right hand side is evaluated.

This was also surprising to me, because I intuitively think it starts on the rightmost side and evaluates leftward, but this is not the case. (The associativity is right-to-left, meaning the parentheses in this case are not needed.)

Here's the specification calling out the order things happen in, with the relevant bits quoted below:

The run-time processing of a simple assignment of the form x = y consists of the following steps:

If x is classified as a variable:

x is evaluated to produce the variable.

y is evaluated and, if required, converted to the type of x through an implicit conversion.

[...]

The value resulting from the evaluation and conversion of y is stored into the location given by the evaluation of x.

Looking at the IL generated by the sharplab link Pavel posted:

        // stack is empty []
newobj instance void MyClass::.ctor()
        // new instance of MyClass on the heap, call it $0
        // stack -> [ref($0)]
stloc.0
        // stack -> []
        // local[0] ("a") = ref($0)
newobj instance void MyClass::.ctor()
        // new instance of MyClass on the heap, call it $1
        // stack -> [ref($1)]
stloc.1
        // stack -> []
        // local[1] ("b") = ref($1)
ldloc.0
        // stack -> [ref($0)]
ldloc.1
        // stack -> [ref($1), ref($0)]
dup
        // stack -> [ref($1), ref($1), ref($0)]
stloc.0
        // stack -> [ref($1), ref($0)]
        // local[0] ("a") = ref($1)
stfld class MyClass MyClass::x
        // stack -> []
        // $0.x = ref($1)


问:
generating and mapping two sets of numbers
I have 2 numbers 25798709 and 25716544 representing the minimum and maximum values of some consecutive numbers with each number differing from the preceeding number by one eg. 25798709,25798710, 25798711................25716544  I want a python code that will convert these figures to 1,2,3,4,5,.............. and map the 1,2,3,4,5 to the original figures in two columns:
Like: </p>

```<code>  1     25798709
  2     25798710
  3     25798711
</code>```

答:
Oneliner:

```<code>print(*['{0}\t{1}'.format(*i) for i in enumerate(range(MIN,MAX+1), 1)], sep='\n')
</code>```

For python2.6 or 2.7 just add from __future__ import print_function

Body:
I have 2 numbers 25798709 and 25716544 representing the minimum and maximum values of some consecutive numbers with each number differing from the preceeding number by one eg. 25798709,25798710, 25798711................25716544  I want a python code that will convert these figures to 1,2,3,4,5,.............. and map the 1,2,3,4,5 to the original figures in two columns:
Like:

  1     25798709
  2     25798710
  3     25798711

Body:
Oneliner:

print(*['{0}\t{1}'.format(*i) for i in enumerate(range(MIN,MAX+1), 1)], sep='\n')

For python2.6 or 2.7 just add from __future__ import print_function


问:
How to make sure each character of a command argument is a decimal digit?
We have to make a code to encrypt Caesar's cipher. One of the steps is: instead of printing out the command-line argument provided, your program instead checks to make sure that each character of that command line argument is a decimal digit (i.e., 0, 1, 2, etc.) and, if any of them are not, terminates after printing the message Usage: ./caesar key. But if the argument consists solely of digit characters, you should convert that string (recall that argv is an array of strings, even if those strings happen to look like numbers) to an actual integer, and print out the integer, as via %i with printf.
The code below is what I have, but it returns both Success & Error. How can I fix this so that the program checks that each character of the command line argument is a digit?
Code I have

答:
You can do this thing in an efficient way:

```<code>#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

bool isNumber(char number[])
{
    int i = 0;

    if (strlen(number) == 0) // checks for empty string
        return false;

    if (strlen(number) == 1 && number[0] == '-') // checks for invalid str with negation sign
        return false;

    if (number[0] == '-') // verifies negation sign
        i = 1;

    for (; number[i] != 0; i++)
        if (!isdigit(number[i]))
            return false; // if not a number

    return true; // if number
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: ./caesar key\n");
        return -1;
    }

    if (isNumber(argv[1]))
        printf("%d\n", atoi(argv[1])); // ... statements
    else
        printf("Usage: ./caesar key\n");

    return 0;
}
</code>```

You can safely use atoi() after validating the arguments are correctly given. Consider:

```<code>if (isNumber(argv[1]))
    printf("Go on\n");
else
    printf("Usage: ./caesar key\n");
</code>```

Sample Output

```<code>$ ./caesar
Usage: ./caesar key
$ ./caesar s
Usage: ./caesar key
$ ./caesar 123 // --- right one
123
$ ./caesar s 3 f
Usage: ./caesar key
</code>```

Body:
You can do this thing in an efficient way:

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

bool isNumber(char number[])
{
    int i = 0;

    if (strlen(number) == 0) // checks for empty string
        return false;

    if (strlen(number) == 1 && number[0] == '-') // checks for invalid str with negation sign
        return false;

    if (number[0] == '-') // verifies negation sign
        i = 1;

    for (; number[i] != 0; i++)
        if (!isdigit(number[i]))
            return false; // if not a number

    return true; // if number
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: ./caesar key\n");
        return -1;
    }

    if (isNumber(argv[1]))
        printf("%d\n", atoi(argv[1])); // ... statements
    else
        printf("Usage: ./caesar key\n");

    return 0;
}

You can safely use atoi() after validating the arguments are correctly given. Consider:

if (isNumber(argv[1]))
    printf("Go on\n");
else
    printf("Usage: ./caesar key\n");

Sample Output

$ ./caesar
Usage: ./caesar key
$ ./caesar s
Usage: ./caesar key
$ ./caesar 123 // --- right one
123
$ ./caesar s 3 f
Usage: ./caesar key


答:
It seems you're training on a range of data, technically you don't need the loops.

But, if you want to keep things your way, just try this:

```<code>y_pred_sol = []
for i in range(1, 1001):
    X_train, y_train = dataset.iloc[i:1000+i], target.iloc[i:1000+i]
    X_test, y_test = dataset.iloc[i], target.iloc[i]

    X_test = np.array(X_test).reshape(1, -1)
    print(X_test.shape)

    SupportVectorRefModel = SVR()
    SupportVectorRefModel.fit(X_train, y_train)
    y_pred = SupportVectorRefModel.predict(X_test)
    y_pred_sol.append(y_pred)
</code>```

print(y_pred_sol)

Title: How to store y_pred variable result from “for-lop” values in numpy array or list?

Body:
It seems you're training on a range of data, technically you don't need the loops.

But, if you want to keep things your way, just try this:

y_pred_sol = []
for i in range(1, 1001):
    X_train, y_train = dataset.iloc[i:1000+i], target.iloc[i:1000+i]
    X_test, y_test = dataset.iloc[i], target.iloc[i]

    X_test = np.array(X_test).reshape(1, -1)
    print(X_test.shape)

    SupportVectorRefModel = SVR()
    SupportVectorRefModel.fit(X_train, y_train)
    y_pred = SupportVectorRefModel.predict(X_test)
    y_pred_sol.append(y_pred)

print(y_pred_sol)


问:
Does each conditional statement have to be enclosed in parenthesis in Pandas?
I was writing a program in python using pandas where there were multiple conditional statements.

top_oceania_wines = reviews[(reviews.country == 'Australia'|reviews.country=='New Zealand')& reviews.points>=95]

On running this I got syntax error. I wanted the or operation before the end so I used the parenthesis but what is wrong with the rest of the code?

答:
```<code>top_oceania_wines = reviews[(reviews.country == 'Australia')|(reviews.country=='New Zealand')& (reviews.points>=95)]
</code>```


问:
How do I answer this question correctly using SQL
"The second report presents a complete list of students with the subjects each has undertaken, their result for that subject, and their average mark for the units taken.

The columns required are as follows:

```<code>student ID,
forename,
surname,
subject ID,
result
</code>```

After each student display, the report should also display the average mark obtained by each student for their program.

An overall average mark should be displayed at the end of the report."

I am very new to SQL so any help on the syntax for this question would be greatly appreciated.

At the moment I have gotten as far as displaying all the columns with all the student details using:

```<code>select student.student_ID
     , student.forename
     , student.surname
     , result.subject_ID
     , result.result
  from student
     , result;
</code>```

But it gives me all the results as the same for whatever reason

As I said i'm not very handy with sql so even just a pseudo-syntaz would be great explaining what I have to do to get this done would be great.

It should be simple for someone with basic sql knowledge i'd imagine.

Thanks in advance

Connor

UPDATE: progress pic

However when adding group by. i seem to get the results for only one class? Do I need to group by something else?
One class pic

Thanks guys i've been on discord severs looking for help for hours and this is defo helping me a lot more. cheers

UPDATE2:

I now get this by adding ROLLUP, its looking good but I don't think these averages correspond to each individual student

Sorry for being so bad at this...
 I'm dumb the 4th row down for each student is the average..it is correct...but is it supposed to display like this?

答:
In the query you don't specify the value that links both tables.

Does the result table have a key column to contain the student_ID?

Then the query should at least state that these should be equal

Use your query as is and add a where clause.

select
  student.student_ID,
  student.forename,
  student.surname,
  result.subject_ID,
  result.result
from student, result
where student.student_ID = result.student_ID
```

Body:
"The second report presents a complete list of students with the subjects each has undertaken, their result for that subject, and their average mark for the units taken.

The columns required are as follows:

student ID,
forename,
surname,
subject ID,
result

After each student display, the report should also display the average mark obtained by each student for their program.

An overall average mark should be displayed at the end of the report."

I am very new to SQL so any help on the syntax for this question would be greatly appreciated.

At the moment I have gotten as far as displaying all the columns with all the student details using:

select student.student_ID
     , student.forename
     , student.surname
     , result.subject_ID
     , result.result
  from student
     , result;

But it gives me all the results as the same for whatever reason

As I said i'm not very handy with sql so even just a pseudo-syntaz would be great explaining what I have to do to get this done would be great.

It should be simple for someone with basic sql knowledge i'd imagine.

Thanks in advance

Connor

UPDATE: progress pic

However when adding group by. i seem to get the results for only one class? Do I need to group by something else?
One class pic

Thanks guys i've been on discord severs looking for help for hours and this is defo helping me a lot more. cheers

UPDATE2:

I now get this by adding ROLLUP, its looking good but I don't think these averages correspond to each individual student

Sorry for being so bad at this...
 I'm dumb the 4th row down for each student is the average..it is correct...but is it supposed to display like this?


问:
Adding a sequence
I have a dataframe that (simplified) looks something like this:

```<code>Index     Studio Event
1
2          MovieStart
3
4
5
6
7           MovieEnd
8
9
10          MovieStart
11
12
13
14
15          MovieEnd
</code>```

I would like to create a third column that creates a sequence from 0 and increment of 50 that begins when the StudioEvent = MovieStart and ends when StudioEvent = MovieEnd. So something like this:

```<code>Index     Studio Event    Sequence
1
2          MovieStart      0
3                          50
4                          100
5                          150
6                          200
7           MovieEnd       250
8
9
10          MovieStart     0
11                         50
12                         100
13                         150
14                         200
15          MovieEnd       250
</code>```

Any idea how I can do it? Thank you in advance.

答:
Here is a base R option

```<code>inds <- Map(`:`,which(df$StudioEvent=="MovieStart"),which(df$StudioEvent=="MovieEnd"))
df$Sequence<-as.numeric(replace(df$StudioEvent,unlist(inds),(unlist(Map(seq_along,inds))-1)*50))
</code>```

such that

```<code>> df
   Index StudioEvent Sequence
1      1        <NA>       NA
2      2  MovieStart        0
3      3        <NA>       50
4      4        <NA>      100
5      5        <NA>      150
6      6        <NA>      200
7      7    MovieEnd      250
8      8        <NA>       NA
9      9        <NA>       NA
10    10  MovieStart        0
11    11        <NA>       50
12    12        <NA>      100
13    13        <NA>      150
14    14        <NA>      200
15    15    MovieEnd      250
</code>```

Data

```<code>> dput(df)
structure(list(Index = 1:15, StudioEvent = c(NA, "MovieStart",
NA, NA, NA, NA, "MovieEnd", NA, NA, "MovieStart", NA, NA, NA,
NA, "MovieEnd")), row.names = c(NA, -15L), class = "data.frame")
</code>```

Title: Adding a sequence

Body:
I have a dataframe that (simplified) looks something like this:

Index     Studio Event
1
2          MovieStart
3
4
5
6
7           MovieEnd
8
9
10          MovieStart
11
12
13
14
15          MovieEnd

I would like to create a third column that creates a sequence from 0 and increment of 50 that begins when the StudioEvent = MovieStart and ends when StudioEvent = MovieEnd. So something like this:

Index     Studio Event    Sequence
1
2          MovieStart      0
3                          50
4                          100
5                          150
6                          200
7           MovieEnd       250
8
9
10          MovieStart     0
11                         50
12                         100
13                         150
14                         200
15          MovieEnd       250

Any idea how I can do it? Thank you in advance.

Body:
Here is a base R option

inds <- Map(`:`,which(df$StudioEvent=="MovieStart"),which(df$StudioEvent=="MovieEnd"))
df$Sequence<-as.numeric(replace(df$StudioEvent,unlist(inds),(unlist(Map(seq_along,inds))-1)*50))

such that

> df
   Index StudioEvent Sequence
1      1        <NA>       NA
2      2  MovieStart        0
3      3        <NA>       50
4      4        <NA>      100
5      5        <NA>      150
6      6        <NA>      200
7      7    MovieEnd      250
8      8        <NA>       NA
9      9        <NA>       NA
10    10  MovieStart        0
11    11        <NA>       50
12    12        <NA>      100
13    13        <NA>      150
14    14        <NA>      200
15    15    MovieEnd      250

Data

> dput(df)
structure(list(Index = 1:15, StudioEvent = c(NA, "MovieStart",
NA, NA, NA, NA, "MovieEnd", NA, NA, "MovieStart", NA, NA, NA,
NA, "MovieEnd")), row.names = c(NA, -15L), class = "data.frame")


问:
Apache Superset error -
504 Gateway Time-out
 The server didn't respond in time.
can I increase this 1-minute limit for the queries? It is very annoying.  Every time I run larger queries, it timeout. can anybody help on this?
I have already set SUPERSET_WEBSERVER_TIMEOUT  to 3600. Why this is happening?

答: Please increase the gunicorn timeout. It will help you


问:
Collision Detection between two images in Java
I have two characters displayed in a game I am writing, the player and the enemy. defined as such:

```<code>public void player(Graphics g) {
    g.drawImage(plimg, x, y, this);
}

public void enemy(Graphics g) {
    g.drawImage(enemy, 200, 200, this);
}
</code>```

Then called with:

```<code>player(g);
enemy(g);
</code>```

I am able to move player() around with the keyboard, but I am at a loss when trying to detect a collision between the two. A lot of people have said to use Rectangles, but being a beginner I cannot see how I would link this into my existing code. Can anyone offer some advice for me?

答:
Here's the main class from my collision detection program.

You can see it run at: http://www.youtube.com/watch?v=JIXhCvXgjsQ

```/**
 *
 * @author Tyler Griffin
 */
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.GraphicsDevice.*;
import java.util.ArrayList;
import java.awt.Graphics;
import java.awt.geom.Line2D;

public class collision extends JFrame implements KeyListener, MouseMotionListener, MouseListener
{
    ArrayList everything=new ArrayList<tile>();

    int time=0, x, y, width, height, up=0, down=0, left=0, right=0, mouse1=0, mouse2=0;
    int mouseX, mouseY;

    GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice screen = environment.getDefaultScreenDevice();
    DisplayMode displayMode = screen.getDisplayMode();

    //private BufferStrategy strategy;

    JLayeredPane pane = new JLayeredPane();

     tile Tile;
     circle Circle;
     rectangle Rectangle;

         textPane text;

    public collision()
    {
        setUndecorated(screen.isFullScreenSupported());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setLayout(null);
        setResizable(false);
        screen.setFullScreenWindow(this);

        width=displayMode.getWidth();
        height=displayMode.getHeight();

          Circle=new circle(-(int)Math.round((double)height/7*2),-(int)Math.round((double)height/7*2),(int)Math.round((double)height/7*.85),this);
          Rectangle=new rectangle(-(int)Math.round((double)height/7*1.5),-(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),this);
          Tile=Circle;
          Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
                  text=new textPane(0,0,width,height,this);

          everything.add(new circle((int)Math.round((double)width/100*75),(int)Math.round((double)height/100*15),(int)Math.round((double)width/100*10),this));
                  everything.add(new rectangle((int)Math.round((double)width/100*70),(int)Math.round((double)height/100*60),(int)Math.round((double)width/100*20),(int)Math.round((double)height/100*20),this));
                  //everything.add(new line(750,250,750,750,this));
                  /*everything.add(new line(width/700*419,height/700*68,width/700*495,height/700*345,this));
                  everything.add(new line(width/700*495,height/700*345,width/700*749,height/700*350,this));
                  everything.add(new line(width/700*749,height/700*350,width/700*549,height/700*519,this));
                  everything.add(new line(width/700*549,height/700*519,width/700*624,height/700*800,this));
                  everything.add(new line(width/700*624,height/700*800,width/700*419,height/700*638,this));
                  everything.add(new line(width/700*419,height/700*638,width/700*203,height/700*800,this));
                  everything.add(new line(width/700*203,height/700*800,width/700*279,height/700*519,this));
                  everything.add(new line(width/700*279,height/700*519,width/700*76,height/700*350,this));
                  everything.add(new line(width/700*76,height/700*350,width/700*333,height/700*345,this));
                  everything.add(new line(width/700*333,height/700*345,width/700*419,height/700*68,this));

                  everything.add(new line(width/950*419,height/700*68,width/950*624,height/700*800,this));
                  everything.add(new line(width/950*419,height/700*68,width/950*203,height/700*800,this));
                  everything.add(new line(width/950*76,height/700*350,width/950*624,height/700*800,this));
                  everything.add(new line(width/950*203,height/700*800,width/950*749,height/700*350,this));
                  everything.add(new rectangle(width/950*76,height/700*350,width/950*673,1,this));*/

                  everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),(int)Math.round((double)width/1350*749),(int)Math.round((double)height/1000*350),this));
                  everything.add(new rectangle((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*673),1,this));

        addKeyListener(this);
        addMouseMotionListener(this);
        addMouseListener(this);
    }

    public void keyReleased(KeyEvent e)
    {
        Object source=e.getSource();

        int released=e.getKeyCode();

        if (released==KeyEvent.VK_A){left=0;}
        if (released==KeyEvent.VK_W){up=0;}
        if (released==KeyEvent.VK_D){right=0;}
        if (released==KeyEvent.VK_S){down=0;}
    }//end keyReleased

    public void keyPressed(KeyEvent e)
    {
        Object source=e.getSource();

        int pressed=e.getKeyCode();

        if (pressed==KeyEvent.VK_A){left=1;}
        if (pressed==KeyEvent.VK_W){up=1;}
        if (pressed==KeyEvent.VK_D){right=1;}
        if (pressed==KeyEvent.VK_S){down=1;}

        if (pressed==KeyEvent.VK_PAUSE&&pressed==KeyEvent.VK_P)
        {
            //if (paused==0){paused=1;}
            //else paused=0;
        }
    }//end keyPressed

    public void keyTyped(KeyEvent e){}

//***********************************************************************************************

    public void mouseDragged(MouseEvent e)
    {
        mouseX=(e.getX());
        mouseY=(e.getY());

          //run();
    }

    public void mouseMoved(MouseEvent e)
    {
        mouseX=(e.getX());
        mouseY=(e.getY());

          //run();
    }

//***********************************************************************************************

    public void mousePressed(MouseEvent e)
    {
        if(e.getX()==0 && e.getY()==0){System.exit(0);}

    mouseX=(e.getX()+x);
        mouseY=(e.getY()+y);

        if(Tile instanceof circle)
        {
                Circle.move(0-Circle.width, 0-Circle.height);
                Circle.setBounds(Circle.x, Circle.y, Circle.width, Circle.height);
                Tile=Rectangle;
        }
        else
        {
                Rectangle.move(0-Rectangle.width, 0-Rectangle.height);
                Rectangle.setBounds(Rectangle.x, Rectangle.y, Rectangle.width, Rectangle.height);
                Tile=Circle;
        }

        Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
    }

    public void mouseReleased(MouseEvent e)
    {
         //run();
    }

    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}

    public void mouseClicked(MouseEvent e){}

//***********************************************************************************************

    public void run()//run collision detection
    {
        while (this == this)
        {
            Tile.move(Tile.x + ((mouseX - (Tile.x + (Tile.width / 2))) / 10), Tile.y + ((mouseY - (Tile.y + (Tile.height / 2))) / 10));
            //Tile.move((mouseX - Tile.width / 2), mouseY - (Tile.height / 2));

            for (int i = 0; i < everything.size(); i++)
            {
                tile Temp = (tile) everything.get(i);

                if (Temp.x < (Tile.x + Tile.width) && (Temp.x + Temp.width) > Tile.x && Temp.y < (Tile.y + Tile.height) && (Temp.y + Temp.height) > Tile.y)//rectangles collided
                {
                    if (Temp instanceof rectangle)
                    {
                        if (Tile instanceof rectangle){rectangleRectangle(Temp);}
                        else {circleRectangle(Temp);}//Tile instanceof circle
                    }
                    else
                    {
                        if (Temp instanceof circle)
                        {
                            if (Tile instanceof rectangle) {rectangleCircle(Temp);}
                            else {circleCircle(Temp);}
                        }
                        else//line
                        {
                            if (Tile instanceof rectangle){rectangleLine(Temp);}
                            else{circleLine(Temp);}
                        }
                    }
                }//end if
            }//end for

            try {Thread.sleep(16L);}
            catch (Exception e) {}

            Tile.setBounds(Tile.x, Tile.y, Tile.width, Tile.height);
            //Rectangle.setBounds(x, y, width, height);
            //Circle.setBounds(x, y, width, height);
            repaint();

            text.out=" ";
        }//end while loop
    }//end run

//***************************************special collision detection/handling functions************************************************

    void rectangleRectangle(tile Temp)
    {
        int lapTop, lapBot, lapLeft, lapRight, small, scootX=0, scootY=0;

        lapTop=(Temp.y+Temp.height)-Tile.y;
        lapBot=(Tile.y+Tile.height)-Temp.y;
        lapLeft=(Temp.x+Temp.width)-Tile.x;
        lapRight=(Tile.x+Tile.width)-Temp.x;

        small=999999999;

        if (lapTop<small){small=lapTop; scootX=0; scootY=lapTop;}
        if (lapBot<small){small=lapBot; scootX=0; scootY=lapBot*-1;}
                if (lapLeft<small){small=lapLeft; scootX=lapLeft; scootY=0;}
                if (lapRight<small){small=lapRight; scootX=lapRight*-1; scootY=0;}

        Tile.move(Tile.x+scootX, Tile.y+scootY);text.out="collision detected!";
    }

    void circleRectangle(tile Temp)
    {
        if((Tile.x+Tile.width/2<=Temp.x+Temp.width && Tile.x+Tile.width/2>=Temp.x)||(Tile.y+Tile.height/2>=Temp.y && Tile.y+Tile.height/2<=Temp.y+Temp.height))
        {
            rectangleRectangle(Temp);
        }
        else//push from nearest corner
        {
            int x,y;
            if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2<Temp.y){x=Temp.x+Temp.width; y=Temp.y;}
            else if(Tile.x+Tile.width/2<Temp.x && Tile.y+Tile.height/2<Temp.y){x=Temp.x; y=Temp.y;}
            else if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2>Temp.y+Temp.height){x=Temp.x+Temp.width; y=Temp.y+Temp.height;}
            else {x=Temp.x; y=Temp.y+Temp.height;}

            double distance = Math.sqrt(Math.pow(Tile.x+(Tile.width/2) - x, 2) + Math.pow(Tile.y+(Tile.height/2) - y, 2));

            if((int)Math.round(distance)<Tile.height/2)
            {
                             double normY = ((Tile.y+(Tile.height/2) - y) / distance);
                             double normX = ((Tile.x+(Tile.width/2) - x) / distance);

                            Tile.move(x-Tile.width/2+(int)Math.round(normX*((Tile.width/2))) , y-Tile.height/2+(int)Math.round(normY*((Tile.height/2))));text.out="collision detected!";
            }
        }
    }

    void rectangleCircle(tile Temp)
    {
        if((Temp.x+Temp.width/2<=Tile.x+Tile.width && Temp.x+Temp.width/2>=Tile.x)||(Temp.y+Temp.height/2>=Tile.y && Temp.y+Temp.height/2<=Tile.y+Tile.height))
        {
            rectangleRectangle(Temp);
        }
        else//push from nearest corner
        {
            int x,y;
            if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){x=Tile.x+Tile.width; y=Tile.y;}
            else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){x=Tile.x; y=Tile.y;}
            else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){x=Tile.x+Tile.width; y=Tile.y+Tile.height;}
            else {x=Tile.x; y=Tile.y+Tile.height;}

            double distance = Math.sqrt(Math.pow(Temp.x+(Temp.width/2) - x, 2) + Math.pow(Temp.y+(Temp.height/2) - y, 2));

            if((int)Math.round(distance)<Temp.height/2)
            {
             double normY = ((Temp.y+(Temp.height/2) - y) / distance);
             double normX = ((Temp.x+(Temp.width/2) - x) / distance);

             if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
                else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
                else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
                else {Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
            }
        }
    }

    void circleCircle(tile Temp)
    {
        double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2)),2) + Math.pow((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2)), 2));

        if((int)distance<(Tile.width/2+Temp.width/2))
        {
                        double normX = ((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2))) / distance;
                        double normY = ((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2))) / distance;

            Tile.move((Temp.x+(Temp.width/2))+(int)Math.round(normX*(Tile.width/2+Temp.width/2))-(Tile.width/2) , (Temp.y+(Temp.height/2))+(int)Math.round(normY*(Tile.height/2+Temp.height/2))-(Tile.height/2));text.out="collision detected!";
        }
    }

    void circleLine(tile Temp)
    {
            line Line=(line)Temp;

            if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
            {
                rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
                circleRectangle(rec);
                remove(rec);
            }

            if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
            {
                rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
                circleRectangle(rec);
                remove(rec);
            }

            int x1=0, y1=0, x2=Tile.x+(Tile.width/2), y2=Tile.y+(Tile.height/2);

            x1=Tile.x+(Tile.width/2)-Line.height;//(int)Math.round(Line.xNorm*1000);
            x2=Tile.x+(Tile.width/2)+Line.height;
            if(Line.posSlope)
            {
                y1=Tile.y+(Tile.height/2)-Line.width;
                y2=Tile.y+(Tile.height/2)+Line.width;
            }
            else
            {
                y1=Tile.y+(Tile.height/2)+Line.width;
                y2=Tile.y+(Tile.height/2)-Line.width;
            }

            Point point=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

            if (point.x < (Line.x + Line.width) && point.x > Line.x && point.y < (Line.y + Line.height) && point.y > Line.y)//line intersects within line segment
            {
                //if(point!=null){System.out.println(point.x+","+point.y);}
                double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - point.x,2) + Math.pow((Tile.y+(Tile.width/2)) - point.y, 2));

                if((int)distance<Tile.width/2)
                {
                    //System.out.println("hit");
                    double normX = ((Tile.x+(Tile.width/2)) - point.x) / distance;
                    double normY = ((Tile.y+(Tile.height/2)) - point.y) / distance;

                    Tile.move((point.x)+(int)Math.round(normX*(Tile.width/2))-(Tile.width/2) , (point.y)+(int)Math.round(normY*(Tile.height/2))-(Tile.height/2));text.out="collision detected!";
                    //System.out.println(point.x+","+point.y);
                }
            }

            //new bullet(this, (int)Math.round(tryX), (int)Math.round(tryY));
    }

        void rectangleLine(tile Temp)
    {
            line Line=(line)Temp;
            if(new Line2D.Double(Line.x1,Line.y1,Line.x2,Line.y2).intersects(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height)))
            {
                if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
                {
                    rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
                    rectangleRectangle(rec);
                    remove(rec);
                }

                if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
                {
                    rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
                    rectangleRectangle(rec);
                    remove(rec);
                }

                if(Line.posSlope)//positive sloped line
                {
                    //first we'll do the top left corner
                    int x1=Tile.x-Line.height;
                    int x2=Tile.x+Line.height;
                    int y1=Tile.y-Line.width;
                    int y2=Tile.y+Line.width;
                    Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
                    double topDistance=0, botDistance=0;

                    topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    topDistance = Math.sqrt(Math.pow(Tile.x - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));

                    //new let's do the bottom right corner
                    x1=Tile.x+Tile.width-Line.height;
                    x2=Tile.x+Tile.width+Line.height;
                    y1=Tile.y+Tile.height-Line.width;
                    y2=Tile.y+Tile.height+Line.width;

                    botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    botDistance = Math.sqrt(Math.pow((Tile.x+Tile.width) - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));

                    if(topDistance<botDistance)
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
                        {
                            Tile.move(topPoint.x,topPoint.y);text.out="collision detected!";
                        }
                    }
                    else
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
                        {
                            Tile.move(botPoint.x-Tile.width,botPoint.y-Tile.height);text.out="collision detected!";
                        }
                    }
                }
                else//negative sloped lne
                {
                    //first we'll do the top right corner
                    int x1=Tile.x+Tile.width-Line.height;
                    int x2=Tile.x+Tile.width+Line.height;
                    int y1=Tile.y+Line.width;
                    int y2=Tile.y-Line.width;
                    Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
                    double topDistance=0, botDistance=0;

                    topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    topDistance = Math.sqrt(Math.pow(Tile.x + Tile.width - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));

                    //new let's do the bottom left corner
                    x1=Tile.x-Line.height;
                    x2=Tile.x+Line.height;
                    y1=Tile.y+Tile.height+Line.width;
                    y2=Tile.y+Tile.height-Line.width;

                    botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    botDistance = Math.sqrt(Math.pow(Tile.x - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));

                    if(topDistance<botDistance)
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
                        {
                            Tile.move(topPoint.x-Tile.width,topPoint.y);text.out="collision detected!";
                        }
                    }
                    else
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
                        {
                            Tile.move(botPoint.x,botPoint.y-Tile.height);text.out="collision detected!";
                        }
                    }
                }
            }
    }

       public Point intersection(double x1, double y1, double x2, double y2,double x3, double y3, double x4, double y4)//I didn't write this. got it from http://www.ahristov.com/tutorial/geometry-games/intersection-lines.html (I altered it)
       {
            double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);

            double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
            double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;

            int x=(int)Math.round(xi);
            int y=(int)Math.round(yi);

            return new Point(x, y);
        }

//***************************************************************************************

    public static void main(String[] args)
    {
        final collision Collision=new collision();
          Collision.run();
    }//end main
}//end class
```

OwnerDisplayName: EnderMB

ContentLicense: CC BY-SA 2.5

Body:
I have two characters displayed in a game I am writing, the player and the enemy. defined as such:

public void player(Graphics g) {
    g.drawImage(plimg, x, y, this);
}

public void enemy(Graphics g) {
    g.drawImage(enemy, 200, 200, this);
}

Then called with:

player(g);
enemy(g);

I am able to move player() around with the keyboard, but I am at a loss when trying to detect a collision between the two. A lot of people have said to use Rectangles, but being a beginner I cannot see how I would link this into my existing code. Can anyone offer some advice for me?

Body:
Here's the main class from my collision detection program.

You can see it run at: http://www.youtube.com/watch?v=JIXhCvXgjsQ

/**
 *
 * @author Tyler Griffin
 */
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.GraphicsDevice.*;
import java.util.ArrayList;
import java.awt.Graphics;
import java.awt.geom.Line2D;

public class collision extends JFrame implements KeyListener, MouseMotionListener, MouseListener
{
    ArrayList everything=new ArrayList<tile>();

    int time=0, x, y, width, height, up=0, down=0, left=0, right=0, mouse1=0, mouse2=0;
    int mouseX, mouseY;

    GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice screen = environment.getDefaultScreenDevice();
    DisplayMode displayMode = screen.getDisplayMode();

    //private BufferStrategy strategy;

    JLayeredPane pane = new JLayeredPane();

     tile Tile;
     circle Circle;
     rectangle Rectangle;

         textPane text;

    public collision()
    {
        setUndecorated(screen.isFullScreenSupported());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setLayout(null);
        setResizable(false);
        screen.setFullScreenWindow(this);

        width=displayMode.getWidth();
        height=displayMode.getHeight();

          Circle=new circle(-(int)Math.round((double)height/7*2),-(int)Math.round((double)height/7*2),(int)Math.round((double)height/7*.85),this);
          Rectangle=new rectangle(-(int)Math.round((double)height/7*1.5),-(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),this);
          Tile=Circle;
          Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
                  text=new textPane(0,0,width,height,this);

          everything.add(new circle((int)Math.round((double)width/100*75),(int)Math.round((double)height/100*15),(int)Math.round((double)width/100*10),this));
                  everything.add(new rectangle((int)Math.round((double)width/100*70),(int)Math.round((double)height/100*60),(int)Math.round((double)width/100*20),(int)Math.round((double)height/100*20),this));
                  //everything.add(new line(750,250,750,750,this));
                  /*everything.add(new line(width/700*419,height/700*68,width/700*495,height/700*345,this));
                  everything.add(new line(width/700*495,height/700*345,width/700*749,height/700*350,this));
                  everything.add(new line(width/700*749,height/700*350,width/700*549,height/700*519,this));
                  everything.add(new line(width/700*549,height/700*519,width/700*624,height/700*800,this));
                  everything.add(new line(width/700*624,height/700*800,width/700*419,height/700*638,this));
                  everything.add(new line(width/700*419,height/700*638,width/700*203,height/700*800,this));
                  everything.add(new line(width/700*203,height/700*800,width/700*279,height/700*519,this));
                  everything.add(new line(width/700*279,height/700*519,width/700*76,height/700*350,this));
                  everything.add(new line(width/700*76,height/700*350,width/700*333,height/700*345,this));
                  everything.add(new line(width/700*333,height/700*345,width/700*419,height/700*68,this));

                  everything.add(new line(width/950*419,height/700*68,width/950*624,height/700*800,this));
                  everything.add(new line(width/950*419,height/700*68,width/950*203,height/700*800,this));
                  everything.add(new line(width/950*76,height/700*350,width/950*624,height/700*800,this));
                  everything.add(new line(width/950*203,height/700*800,width/950*749,height/700*350,this));
                  everything.add(new rectangle(width/950*76,height/700*350,width/950*673,1,this));*/

                  everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),(int)Math.round((double)width/1350*749),(int)Math.round((double)height/1000*350),this));
                  everything.add(new rectangle((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*673),1,this));

        addKeyListener(this);
        addMouseMotionListener(this);
        addMouseListener(this);
    }

    public void keyReleased(KeyEvent e)
    {
        Object source=e.getSource();

        int released=e.getKeyCode();

        if (released==KeyEvent.VK_A){left=0;}
        if (released==KeyEvent.VK_W){up=0;}
        if (released==KeyEvent.VK_D){right=0;}
        if (released==KeyEvent.VK_S){down=0;}
    }//end keyReleased

    public void keyPressed(KeyEvent e)
    {
        Object source=e.getSource();

        int pressed=e.getKeyCode();

        if (pressed==KeyEvent.VK_A){left=1;}
        if (pressed==KeyEvent.VK_W){up=1;}
        if (pressed==KeyEvent.VK_D){right=1;}
        if (pressed==KeyEvent.VK_S){down=1;}

        if (pressed==KeyEvent.VK_PAUSE&&pressed==KeyEvent.VK_P)
        {
            //if (paused==0){paused=1;}
            //else paused=0;
        }
    }//end keyPressed

    public void keyTyped(KeyEvent e){}

//***********************************************************************************************

    public void mouseDragged(MouseEvent e)
    {
        mouseX=(e.getX());
        mouseY=(e.getY());

          //run();
    }

    public void mouseMoved(MouseEvent e)
    {
        mouseX=(e.getX());
        mouseY=(e.getY());

          //run();
    }

//***********************************************************************************************

    public void mousePressed(MouseEvent e)
    {
        if(e.getX()==0 && e.getY()==0){System.exit(0);}

    mouseX=(e.getX()+x);
        mouseY=(e.getY()+y);

        if(Tile instanceof circle)
        {
                Circle.move(0-Circle.width, 0-Circle.height);
                Circle.setBounds(Circle.x, Circle.y, Circle.width, Circle.height);
                Tile=Rectangle;
        }
        else
        {
                Rectangle.move(0-Rectangle.width, 0-Rectangle.height);
                Rectangle.setBounds(Rectangle.x, Rectangle.y, Rectangle.width, Rectangle.height);
                Tile=Circle;
        }

        Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
    }

    public void mouseReleased(MouseEvent e)
    {
         //run();
    }

    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}

    public void mouseClicked(MouseEvent e){}

//***********************************************************************************************

    public void run()//run collision detection
    {
        while (this == this)
        {
            Tile.move(Tile.x + ((mouseX - (Tile.x + (Tile.width / 2))) / 10), Tile.y + ((mouseY - (Tile.y + (Tile.height / 2))) / 10));
            //Tile.move((mouseX - Tile.width / 2), mouseY - (Tile.height / 2));

            for (int i = 0; i < everything.size(); i++)
            {
                tile Temp = (tile) everything.get(i);

                if (Temp.x < (Tile.x + Tile.width) && (Temp.x + Temp.width) > Tile.x && Temp.y < (Tile.y + Tile.height) && (Temp.y + Temp.height) > Tile.y)//rectangles collided
                {
                    if (Temp instanceof rectangle)
                    {
                        if (Tile instanceof rectangle){rectangleRectangle(Temp);}
                        else {circleRectangle(Temp);}//Tile instanceof circle
                    }
                    else
                    {
                        if (Temp instanceof circle)
                        {
                            if (Tile instanceof rectangle) {rectangleCircle(Temp);}
                            else {circleCircle(Temp);}
                        }
                        else//line
                        {
                            if (Tile instanceof rectangle){rectangleLine(Temp);}
                            else{circleLine(Temp);}
                        }
                    }
                }//end if
            }//end for

            try {Thread.sleep(16L);}
            catch (Exception e) {}

            Tile.setBounds(Tile.x, Tile.y, Tile.width, Tile.height);
            //Rectangle.setBounds(x, y, width, height);
            //Circle.setBounds(x, y, width, height);
            repaint();

            text.out=" ";
        }//end while loop
    }//end run

//***************************************special collision detection/handling functions************************************************

    void rectangleRectangle(tile Temp)
    {
        int lapTop, lapBot, lapLeft, lapRight, small, scootX=0, scootY=0;

        lapTop=(Temp.y+Temp.height)-Tile.y;
        lapBot=(Tile.y+Tile.height)-Temp.y;
        lapLeft=(Temp.x+Temp.width)-Tile.x;
        lapRight=(Tile.x+Tile.width)-Temp.x;

        small=999999999;

        if (lapTop<small){small=lapTop; scootX=0; scootY=lapTop;}
        if (lapBot<small){small=lapBot; scootX=0; scootY=lapBot*-1;}
                if (lapLeft<small){small=lapLeft; scootX=lapLeft; scootY=0;}
                if (lapRight<small){small=lapRight; scootX=lapRight*-1; scootY=0;}

        Tile.move(Tile.x+scootX, Tile.y+scootY);text.out="collision detected!";
    }

    void circleRectangle(tile Temp)
    {
        if((Tile.x+Tile.width/2<=Temp.x+Temp.width && Tile.x+Tile.width/2>=Temp.x)||(Tile.y+Tile.height/2>=Temp.y && Tile.y+Tile.height/2<=Temp.y+Temp.height))
        {
            rectangleRectangle(Temp);
        }
        else//push from nearest corner
        {
            int x,y;
            if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2<Temp.y){x=Temp.x+Temp.width; y=Temp.y;}
            else if(Tile.x+Tile.width/2<Temp.x && Tile.y+Tile.height/2<Temp.y){x=Temp.x; y=Temp.y;}
            else if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2>Temp.y+Temp.height){x=Temp.x+Temp.width; y=Temp.y+Temp.height;}
            else {x=Temp.x; y=Temp.y+Temp.height;}

            double distance = Math.sqrt(Math.pow(Tile.x+(Tile.width/2) - x, 2) + Math.pow(Tile.y+(Tile.height/2) - y, 2));

            if((int)Math.round(distance)<Tile.height/2)
            {
                             double normY = ((Tile.y+(Tile.height/2) - y) / distance);
                             double normX = ((Tile.x+(Tile.width/2) - x) / distance);

                            Tile.move(x-Tile.width/2+(int)Math.round(normX*((Tile.width/2))) , y-Tile.height/2+(int)Math.round(normY*((Tile.height/2))));text.out="collision detected!";
            }
        }
    }

    void rectangleCircle(tile Temp)
    {
        if((Temp.x+Temp.width/2<=Tile.x+Tile.width && Temp.x+Temp.width/2>=Tile.x)||(Temp.y+Temp.height/2>=Tile.y && Temp.y+Temp.height/2<=Tile.y+Tile.height))
        {
            rectangleRectangle(Temp);
        }
        else//push from nearest corner
        {
            int x,y;
            if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){x=Tile.x+Tile.width; y=Tile.y;}
            else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){x=Tile.x; y=Tile.y;}
            else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){x=Tile.x+Tile.width; y=Tile.y+Tile.height;}
            else {x=Tile.x; y=Tile.y+Tile.height;}

            double distance = Math.sqrt(Math.pow(Temp.x+(Temp.width/2) - x, 2) + Math.pow(Temp.y+(Temp.height/2) - y, 2));

            if((int)Math.round(distance)<Temp.height/2)
            {
             double normY = ((Temp.y+(Temp.height/2) - y) / distance);
             double normX = ((Temp.x+(Temp.width/2) - x) / distance);

             if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
                else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
                else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
                else {Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
            }
        }
    }

    void circleCircle(tile Temp)
    {
        double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2)),2) + Math.pow((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2)), 2));

        if((int)distance<(Tile.width/2+Temp.width/2))
        {
                        double normX = ((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2))) / distance;
                        double normY = ((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2))) / distance;

            Tile.move((Temp.x+(Temp.width/2))+(int)Math.round(normX*(Tile.width/2+Temp.width/2))-(Tile.width/2) , (Temp.y+(Temp.height/2))+(int)Math.round(normY*(Tile.height/2+Temp.height/2))-(Tile.height/2));text.out="collision detected!";
        }
    }

    void circleLine(tile Temp)
    {
            line Line=(line)Temp;

            if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
            {
                rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
                circleRectangle(rec);
                remove(rec);
            }

            if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
            {
                rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
                circleRectangle(rec);
                remove(rec);
            }

            int x1=0, y1=0, x2=Tile.x+(Tile.width/2), y2=Tile.y+(Tile.height/2);

            x1=Tile.x+(Tile.width/2)-Line.height;//(int)Math.round(Line.xNorm*1000);
            x2=Tile.x+(Tile.width/2)+Line.height;
            if(Line.posSlope)
            {
                y1=Tile.y+(Tile.height/2)-Line.width;
                y2=Tile.y+(Tile.height/2)+Line.width;
            }
            else
            {
                y1=Tile.y+(Tile.height/2)+Line.width;
                y2=Tile.y+(Tile.height/2)-Line.width;
            }

            Point point=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

            if (point.x < (Line.x + Line.width) && point.x > Line.x && point.y < (Line.y + Line.height) && point.y > Line.y)//line intersects within line segment
            {
                //if(point!=null){System.out.println(point.x+","+point.y);}
                double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - point.x,2) + Math.pow((Tile.y+(Tile.width/2)) - point.y, 2));

                if((int)distance<Tile.width/2)
                {
                    //System.out.println("hit");
                    double normX = ((Tile.x+(Tile.width/2)) - point.x) / distance;
                    double normY = ((Tile.y+(Tile.height/2)) - point.y) / distance;

                    Tile.move((point.x)+(int)Math.round(normX*(Tile.width/2))-(Tile.width/2) , (point.y)+(int)Math.round(normY*(Tile.height/2))-(Tile.height/2));text.out="collision detected!";
                    //System.out.println(point.x+","+point.y);
                }
            }

            //new bullet(this, (int)Math.round(tryX), (int)Math.round(tryY));
    }

        void rectangleLine(tile Temp)
    {
            line Line=(line)Temp;
            if(new Line2D.Double(Line.x1,Line.y1,Line.x2,Line.y2).intersects(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height)))
            {
                if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
                {
                    rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
                    rectangleRectangle(rec);
                    remove(rec);
                }

                if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
                {
                    rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
                    rectangleRectangle(rec);
                    remove(rec);
                }

                if(Line.posSlope)//positive sloped line
                {
                    //first we'll do the top left corner
                    int x1=Tile.x-Line.height;
                    int x2=Tile.x+Line.height;
                    int y1=Tile.y-Line.width;
                    int y2=Tile.y+Line.width;
                    Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
                    double topDistance=0, botDistance=0;

                    topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    topDistance = Math.sqrt(Math.pow(Tile.x - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));

                    //new let's do the bottom right corner
                    x1=Tile.x+Tile.width-Line.height;
                    x2=Tile.x+Tile.width+Line.height;
                    y1=Tile.y+Tile.height-Line.width;
                    y2=Tile.y+Tile.height+Line.width;

                    botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    botDistance = Math.sqrt(Math.pow((Tile.x+Tile.width) - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));

                    if(topDistance<botDistance)
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
                        {
                            Tile.move(topPoint.x,topPoint.y);text.out="collision detected!";
                        }
                    }
                    else
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
                        {
                            Tile.move(botPoint.x-Tile.width,botPoint.y-Tile.height);text.out="collision detected!";
                        }
                    }
                }
                else//negative sloped lne
                {
                    //first we'll do the top right corner
                    int x1=Tile.x+Tile.width-Line.height;
                    int x2=Tile.x+Tile.width+Line.height;
                    int y1=Tile.y+Line.width;
                    int y2=Tile.y-Line.width;
                    Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
                    double topDistance=0, botDistance=0;

                    topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    topDistance = Math.sqrt(Math.pow(Tile.x + Tile.width - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));

                    //new let's do the bottom left corner
                    x1=Tile.x-Line.height;
                    x2=Tile.x+Line.height;
                    y1=Tile.y+Tile.height+Line.width;
                    y2=Tile.y+Tile.height-Line.width;

                    botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    botDistance = Math.sqrt(Math.pow(Tile.x - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));

                    if(topDistance<botDistance)
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
                        {
                            Tile.move(topPoint.x-Tile.width,topPoint.y);text.out="collision detected!";
                        }
                    }
                    else
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
                        {
                            Tile.move(botPoint.x,botPoint.y-Tile.height);text.out="collision detected!";
                        }
                    }
                }
            }
    }

       public Point intersection(double x1, double y1, double x2, double y2,double x3, double y3, double x4, double y4)//I didn't write this. got it from http://www.ahristov.com/tutorial/geometry-games/intersection-lines.html (I altered it)
       {
            double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);

            double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
            double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;

            int x=(int)Math.round(xi);
            int y=(int)Math.round(yi);

            return new Point(x, y);
        }

//***************************************************************************************

    public static void main(String[] args)
    {
        final collision Collision=new collision();
          Collision.run();
    }//end main
}//end class


答:
Try this:

```<code>top_oceania_wines = reviews[((reviews.country=='Australia') | (reviews.country=='New Zealand')) & (reviews.points>=95)]
</code>```

or

```<code>top_oceania_wines = reviews[(reviews.country=='Australia') | ((reviews.country=='New Zealand') & (reviews.points>=95))]
</code>```

Title: Does each conditional statement have to be enclosed in parenthesis in Pandas?

Body:
I was writing a program in python using pandas where there were multiple conditional statements.

top_oceania_wines = reviews[(reviews.country == 'Australia'|reviews.country=='New Zealand')& reviews.points>=95]

On running this I got syntax error. I wanted the or operation before the end so I used the parenthesis but what is wrong with the rest of the code?

Body:
Try this:

top_oceania_wines = reviews[((reviews.country=='Australia') | (reviews.country=='New Zealand')) & (reviews.points>=95)]

or

top_oceania_wines = reviews[(reviews.country=='Australia') | ((reviews.country=='New Zealand') & (reviews.points>=95))]


问:
What are source and resource root in pycharm?
I'm developing a project about NLP. I have a large corpus and some code. I want to separate them in my project but I'm wondering what is the correct names to choose,

data vs code like in data segment and code segment in assembly, or

source and resource as one of my friends insists is the correct term.

I also saw something in pycharm menus as mark as source, mark as resource which I supposed is explained in here but I still can't understand what are these source and resource root things and when should I use them. I used to think of resource as time, energy, computational power etc.

答:
"Resource" is a more general term than "data". By "data" one usually means the input to a program, something that will influence its output and which can be different in each execution.

But there are other types of files that have a more permanent function, for example the icon images used by a program's graphical interface. This type of file would also be placed in a resource directory because it needs to be accessed during execution to assemble the interface. Another example of resources could be translation files (each translation file containing the translated messages used by the program in a specific language).

By those definitions, your text corpuses can be seen as "data" since you might want to apply your program to different corpuses in the future, or as a "resource" if they are more fixed and used as a sort of reference for the program to solve queries based on other user input.

Naturally we can also see things like icon image files as "data" if we plan to change them often and regard them as the input to our program, but that would be atypical.

Overall the boundary between "data" and "resources" are kind of blurry but that would be the overall idea.


问:
recreate_versions! doesn't work with fog/s3 when version already exists
I've got a mounted uploader FileUploader which has a number of versions. A number of TIFF images have been uploaded, and the present versions haven't been correctly converted to JPEG/PNG, though their filenames are correct.

Having updated the FileUploader to correctly convert to JPEG/PNG, recreating versions works flawlessly on the local filesystem. When using the remote images on S3, even using the guide (https://github.com/carrierwaveuploader/carrierwave/wiki/How-to%3A-Recreate-and-reprocess-your-files-stored-on-fog), any images that already exist don't get updated, though their timestamps do. If the versions stored on S3 are deleted, then the versions are created correctly.

答:
I ran into this today and the link you referenced was updated 2 years ago with this:

with carrierwave_backgrounder you need to set process_#{uploader}_upload flag to true, otherwise it won't generate versions.

So, it would be:

```<code>YourModel.find_each do |ym|
  begin
    ym.process_your_uploader_upload = true # if you use carrierwave_backgrounder
    ym.your_uploader.cache_stored_file!
    ym.your_uploader.retrieve_from_cache!(ym.your_uploader.cache_name)
    ym.your_uploader.recreate_versions!(:version1, :version2)
    ym.save!
  rescue => e
    puts  "ERROR: YourModel: #{ym.id} -> #{e.to_s}"
  end
end
</code>```

I just tested this and can confirm that even if the versions exist on your FOG storage (in my case S3), it will create new versions and overwrite them.

Body:
I ran into this today and the link you referenced was updated 2 years ago with this:

with carrierwave_backgrounder you need to set process_#{uploader}_upload flag to true, otherwise it won't generate versions.

So, it would be:

YourModel.find_each do |ym|
  begin
    ym.process_your_uploader_upload = true # if you use carrierwave_backgrounder
    ym.your_uploader.cache_stored_file!
    ym.your_uploader.retrieve_from_cache!(ym.your_uploader.cache_name)
    ym.your_uploader.recreate_versions!(:version1, :version2)
    ym.save!
  rescue => e
    puts  "ERROR: YourModel: #{ym.id} -> #{e.to_s}"
  end
end

I just tested this and can confirm that even if the versions exist on your FOG storage (in my case S3), it will create new versions and overwrite them.