问:
Maven error "Cannot resolve project dependencies:" -- "org.eclipse.jst.web_sdk.feature.feature.group"
I was following the instructions at Import into Eclipse and Set up Development Environment when I got to the step that says

Run the setup.sh script if you havn't created the target platform: sh setup.sh.

It is to be run in terminal on macOS.

I received the following error messages:

[ERROR] Cannot resolve project dependencies:

[ERROR]   Software being installed: com.amazonaws.eclipse.devide raw:1.0.0.'SNAPSHOT'/format(n[.n=0;[.n=0;[-S]]]):1.0.0-SNAPSHOT

[ERROR]   Missing requirement: com.amazonaws.eclipse.devide raw:1.0.0.'SNAPSHOT'/format(n[.n=0;[.n=0;[-S]]]):1.0.0-SNAPSHOT requires 'org.eclipse.jst.web_sdk.feature.feature.group 0.0.0' but it could not be found

[ERROR]

[ERROR] See http://wiki.eclipse.org/Tycho/Dependency_Resolution_Troubleshooting for help.

[ERROR] Cannot resolve dependencies of MavenProject: com.amazonaws.eclipse:com.amazonaws.eclipse.devide:1.0.0-SNAPSHOT @ /Users/shinehah/git/aws-toolkit-eclipse-java-ee-and-report/releng/com.amazonaws.eclipse.devide/pom.xml: See log for details -> [Help 1]

[ERROR]

[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR]

[ERROR] For more information about the errors and possible solutions, please read the following articles:

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MavenExecutionException

It looks like I need to add "org.eclipse.jst.web_sdk.feature.feature.group" as a dependency, but I'm not able to find that module to download.

This is what is in the pom.xml file originally:

```<code><project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.amazonaws.eclipse</groupId>
    <artifactId>com.amazonaws.eclipse.releng</artifactId>
    <version>1.0.0-SNAPSHOT</version>
  </parent>
  <artifactId>com.amazonaws.eclipse.devide</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>eclipse-repository</packaging>

  <build>
    <plugins>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-p2-repository-plugin</artifactId>
        <version>${tycho.version}</version>
        <configuration>
          <includeAllDependencies>true</includeAllDependencies>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
</code>```

This is the pom.xml file after I added content to it:

```<code><project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.amazonaws.eclipse</groupId>
    <artifactId>com.amazonaws.eclipse.releng</artifactId>
    <version>1.0.0-SNAPSHOT</version>
  </parent>
  <artifactId>com.amazonaws.eclipse.devide</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>eclipse-repository</packaging>

  <dependencies>
    <dependency>
      <groupId>com.amazonaws.eclipse</groupId>
      <artifactId>org.eclipse.jst.web_sdk.feature.feature.group</artifactId>
      <version>1.0.0</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-p2-repository-plugin</artifactId>
        <version>${tycho.version}</version>
        <configuration>
          <includeAllDependencies>true</includeAllDependencies>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
</code>```

This is a screenshot of the Project Explorer in Eclipse. I don't have any projects, just this workspace.

This is the pane titled "Markers" at the bottom of the Eclipse IDE:

What do I need to do to successfully run "sh setup.sh" as the step instructs?

答:
This project is different from other project. it is an eclipse plugin project. First of all, after cloning this project, go to command prompt pointing to the directory of this plugin project and run the following command.

mvn clean package.

Once the build is successful, import as plugin project in eclipse. This is the normal way of importing eclipse plugin project. It is recommended to go through the ReadMe.md file in the github link. https://github.com/aws/aws-toolkit-eclipse

I will suggest, first go through the following helpful links about tycho and how to configure and develop eclipse plugin.

https://wiki.eclipse.org/Developing_Tycho
https://www.vogella.com/tutorials/EclipseTycho/article.html

You can also refer to the following stackoverflow link.

Dependencies from pom.xml not considered by Eclipse in Tycho Project

Body:
I was following the instructions at Import into Eclipse and Set up Development Environment when I got to the step that says

Run the setup.sh script if you havn't created the target platform: sh setup.sh.

It is to be run in terminal on macOS.

I received the following error messages:

[ERROR] Cannot resolve project dependencies:

[ERROR]   Software being installed: com.amazonaws.eclipse.devide raw:1.0.0.'SNAPSHOT'/format(n[.n=0;[.n=0;[-S]]]):1.0.0-SNAPSHOT

[ERROR]   Missing requirement: com.amazonaws.eclipse.devide raw:1.0.0.'SNAPSHOT'/format(n[.n=0;[.n=0;[-S]]]):1.0.0-SNAPSHOT requires 'org.eclipse.jst.web_sdk.feature.feature.group 0.0.0' but it could not be found

[ERROR]

[ERROR] See http://wiki.eclipse.org/Tycho/Dependency_Resolution_Troubleshooting for help.

[ERROR] Cannot resolve dependencies of MavenProject: com.amazonaws.eclipse:com.amazonaws.eclipse.devide:1.0.0-SNAPSHOT @ /Users/shinehah/git/aws-toolkit-eclipse-java-ee-and-report/releng/com.amazonaws.eclipse.devide/pom.xml: See log for details -> [Help 1]

[ERROR]

[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR]

[ERROR] For more information about the errors and possible solutions, please read the following articles:

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MavenExecutionException

It looks like I need to add "org.eclipse.jst.web_sdk.feature.feature.group" as a dependency, but I'm not able to find that module to download.

This is what is in the pom.xml file originally:

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.amazonaws.eclipse</groupId>
    <artifactId>com.amazonaws.eclipse.releng</artifactId>
    <version>1.0.0-SNAPSHOT</version>
  </parent>
  <artifactId>com.amazonaws.eclipse.devide</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>eclipse-repository</packaging>

  <build>
    <plugins>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-p2-repository-plugin</artifactId>
        <version>${tycho.version}</version>
        <configuration>
          <includeAllDependencies>true</includeAllDependencies>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

This is the pom.xml file after I added content to it:

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.amazonaws.eclipse</groupId>
    <artifactId>com.amazonaws.eclipse.releng</artifactId>
    <version>1.0.0-SNAPSHOT</version>
  </parent>
  <artifactId>com.amazonaws.eclipse.devide</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>eclipse-repository</packaging>

  <dependencies>
    <dependency>
      <groupId>com.amazonaws.eclipse</groupId>
      <artifactId>org.eclipse.jst.web_sdk.feature.feature.group</artifactId>
      <version>1.0.0</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-p2-repository-plugin</artifactId>
        <version>${tycho.version}</version>
        <configuration>
          <includeAllDependencies>true</includeAllDependencies>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

This is a screenshot of the Project Explorer in Eclipse. I don't have any projects, just this workspace.

This is the pane titled "Markers" at the bottom of the Eclipse IDE:

What do I need to do to successfully run "sh setup.sh" as the step instructs?


来源: stackexchange

问:
Comparing a datetime dataframe with a period dataframe
I have been stuck with a simple pandas dataframe problem and maybe someone faced this situation before...

Thank you in advance :)

Hi have two dataframes, df1 and df2:

df1

```<code>unique_id    timestamp
1            2019-01-21
2            2019-02-01
3            2019-04-05
4            2019-05-01
5            2019-05-12
...          ...
</code>```

df2

```<code>classification     from            to
A                  2019-01-05      2019-02-02
B                  2019-02-03      2019-02-28
C                  2019-03-01      2019-04-05
D                  2019-04-06      2019-05-03
E                  2019-05-04      2019-05-31
...                ...             ...
</code>```

My goal is to compare each timestamp in df1 with each from to date interval in df2 and be able to classify every unique_id of df1 with the correspondent classification of df2

I was trying something like this:

```<code>df1.loc[(df1['timestamp'] > df2['from]) & (df1['timestamp'] < df2['to']), 'class'] = df2['classification']´
</code>```

always get a ValueError: Can only compare identically-labeled Series objects despite both datetime dtypes are the exact same, datetime64[ns]...

Expected Output:

```<code>unique_id         timestamp        classification
1                 2019-01-21       A
2                 2019-02-01       A
3                 2019-04-05       C
4                 2019-05-01       D
5                 2019-05-12       E
...               ...              ...
</code>```

答:
You are mixing the index of the both dataframe. With this syntax you're suggesting, comparison is done row by row. You can just see it if we condisere the following dataframes (with different size):

```<code>df1 = pd.DataFrame(
    [[1, "2019-01-21"],
    [2, "2019-02-01"],
    [3, "2019-04-05"],
    [4, "2019-04-05"],
    [5, "2019-04-05"],
    [6, "2019-04-05"],
    [7, "2019-05-01"],
    [8, "2019-05-12"]],
    columns=["unique_id", "timestamp"])

df2 = pd.DataFrame([
    ["A", "2019-01-05", "2019-02-02"],
    ["D", "2019-04-06", "2019-05-03"],
    ["C", "2019-03-01", "2019-04-05"],
    ["B", "2019-02-03", "2019-02-28"],
    ["E", "2019-05-04", "2019-05-31"],],
    columns=["classification", "from", "to"])

# Comparaison of different dataframes
print((df1['timestamp'] > df2['from']))
</code>```

Error raised:

ValueError: Can only compare identically-labeled Series objects

Here, you want to compare according the matching datetime interval. So you need to distinguish the both dataframe. To convert string data to date, pandas.to_datetime do the job (doc)

Here is one way to do:

```<code># import modules
import pandas as pd

df1 = pd.DataFrame(
    [[1, "2019-01-21"],
    [2, "2019-02-01"],
    [3, "2019-04-05"],
    [4, "2019-04-05"],
    [5, "2019-04-05"],
    [6, "2019-04-05"],
    [7, "2019-05-01"],
    [8, "2019-05-12"]],
    columns=["unique_id", "timestamp"])

df2 = pd.DataFrame([
    ["A", "2019-01-05", "2019-02-02"],
    ["D", "2019-04-06", "2019-05-03"],
    ["C", "2019-03-01", "2019-04-05"],
    ["B", "2019-02-03", "2019-02-28"],
    ["E", "2019-05-04", "2019-05-31"],],
    columns=["classification", "from", "to"])

# convert to datetime
df1["timestamp"] = pd.to_datetime(df1["timestamp"], format="%Y-%m-%d")
df2[["from", "to"]] = df2[["from", "to"]].apply(pd.to_datetime, format="%Y-%m-%d")

# Try to compare 2 different dataframes
# print((df1['timestamp'] > df2['from']))

class_column = []
for index, row in df1.iterrows():
    class_fd2 = df2[(df2["from"] <= row["timestamp"]) & (df2["to"] >= row["timestamp"])]["classification"].values[0]
    class_column.append(class_fd2)
df1["class1"] = class_column
print(df1)
#    unique_id  timestamp class1
# 0          1 2019-01-21      A
# 1          2 2019-02-01      A
# 2          3 2019-04-05      C
# 3          4 2019-04-05      C
# 4          5 2019-04-05      C
# 5          6 2019-04-05      C
# 6          7 2019-05-01      D
# 7          8 2019-05-12      E
</code>```

You can also do it in a function to apply to df1:

```<code>def set_class(row):
    return df2[(df2["from"] <= row["timestamp"]) & (
        df2["to"] >= row["timestamp"])]["classification"].values[0]
# Process
df1["class2"] = df1.apply(set_class, axis=1)
print(df1)
#    unique_id  timestamp class1 class2
# 0          1 2019-01-21      A      A
# 1          2 2019-02-01      A      A
# 2          3 2019-04-05      C      C
# 3          4 2019-04-05      C      C
# 4          5 2019-04-05      C      C
# 5          6 2019-04-05      C      C
# 6          7 2019-05-01      D      D
# 7          8 2019-05-12      E      E
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have been stuck with a simple pandas dataframe problem and maybe someone faced this situation before...

Thank you in advance :)

Hi have two dataframes, df1 and df2:

df1

unique_id    timestamp
1            2019-01-21
2            2019-02-01
3            2019-04-05
4            2019-05-01
5            2019-05-12
...          ...

df2

classification     from            to
A                  2019-01-05      2019-02-02
B                  2019-02-03      2019-02-28
C                  2019-03-01      2019-04-05
D                  2019-04-06      2019-05-03
E                  2019-05-04      2019-05-31
...                ...             ...

My goal is to compare each timestamp in df1 with each from to date interval in df2 and be able to classify every unique_id of df1 with the correspondent classification of df2

I was trying something like this:

df1.loc[(df1['timestamp'] > df2['from]) & (df1['timestamp'] < df2['to']), 'class'] = df2['classification']´

always get a ValueError: Can only compare identically-labeled Series objects despite both datetime dtypes are the exact same, datetime64[ns]...

Expected Output:

unique_id         timestamp        classification
1                 2019-01-21       A
2                 2019-02-01       A
3                 2019-04-05       C
4                 2019-05-01       D
5                 2019-05-12       E
...               ...              ...

Body:
You are mixing the index of the both dataframe. With this syntax you're suggesting, comparison is done row by row. You can just see it if we condisere the following dataframes (with different size):

df1 = pd.DataFrame(
    [[1, "2019-01-21"],
    [2, "2019-02-01"],
    [3, "2019-04-05"],
    [4, "2019-04-05"],
    [5, "2019-04-05"],
    [6, "2019-04-05"],
    [7, "2019-05-01"],
    [8, "2019-05-12"]],
    columns=["unique_id", "timestamp"])

df2 = pd.DataFrame([
    ["A", "2019-01-05", "2019-02-02"],
    ["D", "2019-04-06", "2019-05-03"],
    ["C", "2019-03-01", "2019-04-05"],
    ["B", "2019-02-03", "2019-02-28"],
    ["E", "2019-05-04", "2019-05-31"],],
    columns=["classification", "from", "to"])

# Comparaison of different dataframes
print((df1['timestamp'] > df2['from']))

Error raised:

ValueError: Can only compare identically-labeled Series objects

Here, you want to compare according the matching datetime interval. So you need to distinguish the both dataframe. To convert string data to date, pandas.to_datetime do the job (doc)

Here is one way to do:

# import modules
import pandas as pd

df1 = pd.DataFrame(
    [[1, "2019-01-21"],
    [2, "2019-02-01"],
    [3, "2019-04-05"],
    [4, "2019-04-05"],
    [5, "2019-04-05"],
    [6, "2019-04-05"],
    [7, "2019-05-01"],
    [8, "2019-05-12"]],
    columns=["unique_id", "timestamp"])

df2 = pd.DataFrame([
    ["A", "2019-01-05", "2019-02-02"],
    ["D", "2019-04-06", "2019-05-03"],
    ["C", "2019-03-01", "2019-04-05"],
    ["B", "2019-02-03", "2019-02-28"],
    ["E", "2019-05-04", "2019-05-31"],],
    columns=["classification", "from", "to"])

# convert to datetime
df1["timestamp"] = pd.to_datetime(df1["timestamp"], format="%Y-%m-%d")
df2[["from", "to"]] = df2[["from", "to"]].apply(pd.to_datetime, format="%Y-%m-%d")

# Try to compare 2 different dataframes
# print((df1['timestamp'] > df2['from']))

class_column = []
for index, row in df1.iterrows():
    class_fd2 = df2[(df2["from"] <= row["timestamp"]) & (df2["to"] >= row["timestamp"])]["classification"].values[0]
    class_column.append(class_fd2)
df1["class1"] = class_column
print(df1)
#    unique_id  timestamp class1
# 0          1 2019-01-21      A
# 1          2 2019-02-01      A
# 2          3 2019-04-05      C
# 3          4 2019-04-05      C
# 4          5 2019-04-05      C
# 5          6 2019-04-05      C
# 6          7 2019-05-01      D
# 7          8 2019-05-12      E

You can also do it in a function to apply to df1:

def set_class(row):
    return df2[(df2["from"] <= row["timestamp"]) & (
        df2["to"] >= row["timestamp"])]["classification"].values[0]
# Process
df1["class2"] = df1.apply(set_class, axis=1)
print(df1)
#    unique_id  timestamp class1 class2
# 0          1 2019-01-21      A      A
# 1          2 2019-02-01      A      A
# 2          3 2019-04-05      C      C
# 3          4 2019-04-05      C      C
# 4          5 2019-04-05      C      C
# 5          6 2019-04-05      C      C
# 6          7 2019-05-01      D      D
# 7          8 2019-05-12      E      E


问:
Can you filter querysets by user in models?
I suppose the proper way to filter objects by user is done in views because you can easily require login and you have access to request.user. But I have a view that invokes the object's classmethod, which can't be combined with a filter because it converts the queryset to a list object- so I'm thinking if there's a way to filter the queryset by user directly in models, then when I invoke the classmethod in views the objects will already be filtered.

Here's my view:

```<code>def leads_by_city(request):
    # Invoke Lead classmethod to get the data
    data = Lead.objects.get_leads_per_city()

    return JsonResponse(data, safe=False)
</code>```

Model with custom Manager:

```<code>class Lead(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    source = models.ForeignKey(LeadSource, on_delete=models.CASCADE)
    city = models.CharField(max_length=100)
    objects = LeadManager()

class LeadManager(models.Manager):

    def get_leads_per_city(self):
        queryset = self.values('city').annotate(Count('id')).order_by('city')
        data = list(queryset.values('city', 'id__count'))

        return data
</code>```

Is there a way to filter by user in the classmethod? Maybe like:

```<code>class LeadManager(models.Manager):

    def get_leads_per_city(self,user):
        queryset = self.filter(user=Lead.user).values('city').annotate(Count('id')).order_by('city')
        data = list(queryset.values('city', 'id__count'))

        return data
</code>```

答:
Yes, although your filtering is a bit off, you can simply set .filter(user=user):

```<code>class LeadManager(models.Manager):

    def get_leads_per_city(self, user):
        queryset = self.filter(
            <b>user=user</b>
        ).values('city').annotate(Count('id')).order_by('city')
        return list(queryset.values('city', 'id__count'))</code>```

The user=user parameter name does not refer to the user parameter of the function. The Django ORM will look for a field with that name, and we pass it the user of the parameter call.

In your view, you can then call this with:

```<code>def leads_by_city(request):
    # Invoke Lead classmethod to get the data
    data = Lead.objects.get_leads_per_city(<b>request.user</b>)
    return JsonResponse(data, safe=False)</code>```

That being said, you here use Django's QuerySet mechanism to generate dictionaries. That is typically not advisable. You might want to use a Serializer, as is offered by the Django REST Framework [drf-doc].

Furthermore it also is not a good idea to pass a list as a JSON response. There have been JSON exploits with that, you better wrap this in a dictionary.

Since you require the logged in user, it might also be better to add the @login_required decorator [Django-doc] here, which will return a HTTP redirect response, given the user has not been logged in:

```<code>from django.contrib.auth.decorators import <b>login_required</b>

<b>@login_required</b>
def leads_by_city(request):
    # Invoke Lead classmethod to get the data
    data = Lead.objects.get_leads_per_city(request.user)
    return JsonResponse(<b>{'data'</b>: data<b>}</b>)</code>```

Body:
I suppose the proper way to filter objects by user is done in views because you can easily require login and you have access to request.user. But I have a view that invokes the object's classmethod, which can't be combined with a filter because it converts the queryset to a list object- so I'm thinking if there's a way to filter the queryset by user directly in models, then when I invoke the classmethod in views the objects will already be filtered.

Here's my view:

def leads_by_city(request):
    # Invoke Lead classmethod to get the data
    data = Lead.objects.get_leads_per_city()

    return JsonResponse(data, safe=False)

Model with custom Manager:

class Lead(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    source = models.ForeignKey(LeadSource, on_delete=models.CASCADE)
    city = models.CharField(max_length=100)
    objects = LeadManager()

class LeadManager(models.Manager):

    def get_leads_per_city(self):
        queryset = self.values('city').annotate(Count('id')).order_by('city')
        data = list(queryset.values('city', 'id__count'))

        return data

Is there a way to filter by user in the classmethod? Maybe like:

class LeadManager(models.Manager):

    def get_leads_per_city(self,user):
        queryset = self.filter(user=Lead.user).values('city').annotate(Count('id')).order_by('city')
        data = list(queryset.values('city', 'id__count'))

        return data

Body:
Yes, although your filtering is a bit off, you can simply set .filter(user=user):

class LeadManager(models.Manager):

    def get_leads_per_city(self, user):
        queryset = self.filter(
            user=user
        ).values('city').annotate(Count('id')).order_by('city')
        return list(queryset.values('city', 'id__count'))

The user=user parameter name does not refer to the user parameter of the function. The Django ORM will look for a field with that name, and we pass it the user of the parameter call.

In your view, you can then call this with:

def leads_by_city(request):
    # Invoke Lead classmethod to get the data
    data = Lead.objects.get_leads_per_city(request.user)
    return JsonResponse(data, safe=False)

That being said, you here use Django's QuerySet mechanism to generate dictionaries. That is typically not advisable. You might want to use a Serializer, as is offered by the Django REST Framework [drf-doc].

Furthermore it also is not a good idea to pass a list as a JSON response. There have been JSON exploits with that, you better wrap this in a dictionary.

Since you require the logged in user, it might also be better to add the @login_required decorator [Django-doc] here, which will return a HTTP redirect response, given the user has not been logged in:

from django.contrib.auth.decorators import login_required

@login_required
def leads_by_city(request):
    # Invoke Lead classmethod to get the data
    data = Lead.objects.get_leads_per_city(request.user)
    return JsonResponse({'data': data})


问:
How do you extract IP addresses from a line matching a string from a file in bash?
Example:

I have a file name example.txt and inside it this text:

```<code>some text here INFO    200     cv 58687 http://saomesitehoere.com live connect ASDFG 61.215.80.6 07:16

some text here INFO    100     fv 582702687 http://saomesitehoere.org live connect 31.15.80.1 07:16:33

some text here INFO    00     ov 587 http://saomesitehoere.uk live connect ASGGGGFG 91.211.80.6 09:16

some text here INFO    800    kcv 277 http://saomesitehoere.za live connect AFG 71.215.81.5 09:14
</code>```

I want to extract the IP-address from the line which contain the string name "ASDFG", meaning 61.215.80.6

Anyone can help ?

ContentLicense: CC BY-SA 3.0

Body:
Example:

I have a file name example.txt and inside it this text:

some text here INFO    200     cv 58687 http://saomesitehoere.com live connect ASDFG 61.215.80.6 07:16

some text here INFO    100     fv 582702687 http://saomesitehoere.org live connect 31.15.80.1 07:16:33

some text here INFO    00     ov 587 http://saomesitehoere.uk live connect ASGGGGFG 91.211.80.6 09:16

some text here INFO    800    kcv 277 http://saomesitehoere.za live connect AFG 71.215.81.5 09:14

I want to extract the IP-address from the line which contain the string name "ASDFG", meaning 61.215.80.6

Anyone can help ?

Body:
you can use :

grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'


问:
How do I force drop and re-create a selected table in code-first migration?
I want to drop a table with a thousand columns and let migration re-create it.
I can issue a

```<code>    DropTable("MyTableWithManyColumns");
</code>```

But the problem is I would do a manual create table like this

```<code>    CreateTable(
            "dbo.MyTable",
            c => new
                {
                    RowId = c.Int(nullable: false, identity: true),
                    // many columns follow...
                })
            .PrimaryKey(t => t.RowId);
</code>```

The easier way to do this is use SSMS and right click Drop Create Table to new window and execute from there.

But is there is there an easy way using code migration?

答:
No programmatic way that I've determined.  Not from lack of trying though.

Here's my success though:

In SQL Management Studio I generated scripts for the entire database (or tables you know are related).  I found any foreign key (FK) constraints, indexes, etc. related to MyTable.  Also generate sql insert statements for MyTable.  Drop the constraints, drop the table, create the table (obviously with the appropriate field order), insert data, re-create FK constraints.

Just to test the db I tried making a database change.

```<code>ADD-MIGRATION XYZ
UPDATE-DATABASE -VERBOSE
</code>```

Everything was working.

Body:
I want to drop a table with a thousand columns and let migration re-create it.
I can issue a

    DropTable("MyTableWithManyColumns");

But the problem is I would do a manual create table like this

    CreateTable(
            "dbo.MyTable",
            c => new
                {
                    RowId = c.Int(nullable: false, identity: true),
                    // many columns follow...
                })
            .PrimaryKey(t => t.RowId);

The easier way to do this is use SSMS and right click Drop Create Table to new window and execute from there.

But is there is there an easy way using code migration?

Body:
No programmatic way that I've determined.  Not from lack of trying though.

Here's my success though:

In SQL Management Studio I generated scripts for the entire database (or tables you know are related).  I found any foreign key (FK) constraints, indexes, etc. related to MyTable.  Also generate sql insert statements for MyTable.  Drop the constraints, drop the table, create the table (obviously with the appropriate field order), insert data, re-create FK constraints.

Just to test the db I tried making a database change.

ADD-MIGRATION XYZ
UPDATE-DATABASE -VERBOSE

Everything was working.


问:
Why comparing Strings in MySQL query is not working
I am running a very simple SELECT query in MySQL and it's not working.

```<code>SELECT string_name FROM table_name;
</code>```

This is giving me required output. Like

This is string one.

This is string two.

This is string three.

and so on...

But if I am running a query like this

```<code>SELECT * FROM table_name WHERE string_name='This is string one'
</code>```

It's not giving any output. I even tried TRIM function.

```<code>SELECT * FROM table_name WHERE TRIM(string_name)=TRIM('This is string one')
</code>```

But it's still not giving any output.

Please suggest what I am missing here. Is it because of some formatting or am I doing any silly mistake. By the way, Strings are saved as VARCHAR in the database.

答:
Have you tried using LIKE for debugging purposes?

SELECT * FROM table_name WHERE string_name LIKE 'This is string one'

/!\ Don't just switch from = to LIKE, read about why here

TLDR:

= is apparently 30x faster.

Use = wherever you can and LIKE wherever you must.

Body:
I am running a very simple SELECT query in MySQL and it's not working.

SELECT string_name FROM table_name;

This is giving me required output. Like

This is string one.

This is string two.

This is string three.

and so on...

But if I am running a query like this

SELECT * FROM table_name WHERE string_name='This is string one'

It's not giving any output. I even tried TRIM function.

SELECT * FROM table_name WHERE TRIM(string_name)=TRIM('This is string one')

But it's still not giving any output.

Please suggest what I am missing here. Is it because of some formatting or am I doing any silly mistake. By the way, Strings are saved as VARCHAR in the database.


问:
One-line "for" loop using list comprehension
Someone has challenged me to create a program that sorts their pictures into folders based on the month they were taken, and I want to do it in one line (I know, it's inefficient and unreadable, but I still want to do it because one-liners are cool)

I needed a for loop to accomplish this, but the only way I know of to use a for loop in one line is list comprehension, so that's what I did, but it creates an empty list, and doesn't print anything from the list or anything.

What I'm doing is renaming the file to be the month created + original filename (ex: bacon.jpg --> May\bacon.jpg)

Here is my code (Python 3.7.3):

import time
import os.path
[os.rename(str(os.fspath(f)), str(time.ctime(os.path.getctime(str(os.fspath(f))))).split()[1] + '\\' + str(os.fspath(f))) for f in os.listdir() if f.endswith('.jpg')]
```

<p>and the more readable, non-list-comprehension version:</p>

<pre class="lang-py prettyprint-override"><code>import time
import os.path
for f in os.listdir():
    fn = str(os.fspath(f))
    dateCreated = str(time.ctime(os.path.getctime(fn)))
    monthCreated = dateCreated.split()[1]
    os.rename(fn, monthCreated + '\\' + fn)
</code>```

Is list comprehension a bad way to do it? Also, is there a reason why, if I print the list it's [] instead of [None, None, None, None, None, (continuing "None"s for every image moved)]?

Please note: I understand that it's inefficient and bad practice. If I were doing this for purposes other than just for fun to see if I could do it, I would obviously not try to do it in one line.

答:
Is list comprehension a bad way to do it?

YES. But if you want to do it in one line, it is either that or using ";". For instance:

```<code> for x in range(5): print(x);print(x+2)
</code>```

And, by the way, just renaming a file including a slash will not create a folder. You have to use os.mkdir('foldername').

In the end, if you really want to do that, I would just recommend doing it normally in many lines and then separating it with semicolons in a single line.

Body:
Someone has challenged me to create a program that sorts their pictures into folders based on the month they were taken, and I want to do it in one line (I know, it's inefficient and unreadable, but I still want to do it because one-liners are cool)

I needed a for loop to accomplish this, but the only way I know of to use a for loop in one line is list comprehension, so that's what I did, but it creates an empty list, and doesn't print anything from the list or anything.

What I'm doing is renaming the file to be the month created + original filename (ex: bacon.jpg --> May\bacon.jpg)

Here is my code (Python 3.7.3):

import time
import os.path
[os.rename(str(os.fspath(f)), str(time.ctime(os.path.getctime(str(os.fspath(f))))).split()[1] + '\\' + str(os.fspath(f))) for f in os.listdir() if f.endswith('.jpg')]

and the more readable, non-list-comprehension version:

import time
import os.path
for f in os.listdir():
    fn = str(os.fspath(f))
    dateCreated = str(time.ctime(os.path.getctime(fn)))
    monthCreated = dateCreated.split()[1]
    os.rename(fn, monthCreated + '\\' + fn)

Is list comprehension a bad way to do it? Also, is there a reason why, if I print the list it's [] instead of [None, None, None, None, None, (continuing "None"s for every image moved)]?

Please note: I understand that it's inefficient and bad practice. If I were doing this for purposes other than just for fun to see if I could do it, I would obviously not try to do it in one line.

Body:
Is list comprehension a bad way to do it?

YES. But if you want to do it in one line, it is either that or using ";". For instance:

 for x in range(5): print(x);print(x+2)

And, by the way, just renaming a file including a slash will not create a folder. You have to use os.mkdir('foldername').

In the end, if you really want to do that, I would just recommend doing it normally in many lines and then separating it with semicolons in a single line.


问:
How to avoid no data exception?
I am working on a project and I have a database schema written in Oracle db for a library. I have some issues when trying to build a function which should provide some recommendations for the user.

The recommendations should be given based on the last books genres some user had borrowed in the past month and the most read books of all users. Every time I try to run the function I get a no data error even if I have values in the tables.

```<code>    CREATE OR REPLACE FUNCTION getGenre(bookISBN IN VARCHAR2) RETURN VARCHAR2
    AS
      v_bookGenre VARCHAR2(100);
    BEGIN
      select genre into v_bookGenre from (select genre from books where bookISBN=isbn);
      return v_bookGenre;
    END getGenre;
    /
    CREATE OR REPLACE TYPE t IS TABLE OF varchar2(200);
    /
    create or replace type typeRecom is VARRAY(200) of VARCHAR2(200);
    /
    CREATE OR REPLACE FUNCTION topRecommandations(idUser IN VARCHAR2)
    RETURN typeRecom
    AS

      lastGenres t :=t();
      readedBooks t:=t();
      topTen typeRecom;

      v_i NUMBER := 1;
      v_j NUMBER := 1;

      verifDateBook NUMBER:=0;
      verifDateLoan NUMBER:=0;

    BEGIN
      select count(*) into verifDateBook from books;
      if(verifDateBook = 0) then
        raise no_data_found;
      end if;

      select count(*) into verifDateLoan from loans;
      if(verifDateLoan = 0) then
        raise no_data_found;
      end if;

      lastGenres.extend();
      for i in (select genre from books join loans on books.isbn=loans.bookId where loanDate>add_months(sysdate,-1) and idUser=loans.regNo order by genre desc) loop
        DBMS_OUTPUT.PUT_LINE(i.genre);
        lastGenres.extend();
        lastGenres(lastGenres.count) := i.genre;
      end loop;
      /*select title into bookTitles from book join loan on book.isbn=loan.regNo;*/
       readedBooks.extend();
       for i in (select bookId from loans group by bookId order by count(bookId) desc) loop
        readedBooks.extend();
        readedBooks(readedBooks.count) := i.bookId;
      end loop;
      --select bookId into readedBooks from loan order by count(bookId) desc;

      for v_i IN 1..50 LOOP
        for v_j in 1..50 LOOP
          DBMS_OUTPUT.PUT_LINE(lastGenres(v_j));
          DBMS_OUTPUT.PUT_LINE(getGenre(readedBooks(v_i)));
          if(lastGenres(v_j)=getGenre(readedBooks(v_i))) then
            topTen(v_i) := getGenre(readedBooks(v_j));
          end if;
        EXIT WHEN topTen.count=10;
        END LOOP;
      EXIT WHEN topTen.count=10;
      end LOOP;
      for v_cont in 1..10 LOOP
            --if(topTen.count <= 10) then
            DBMS_OUTPUT.PUT_LINE(topTen(v_cont));
          --end if;
      end loop;
      return topTen;
      EXCEPTION
      WHEN no_data_found THEN
        DBMS_OUTPUT.PUT_LINE('Nu exista valori.');

    END topRecommandations;
</code>```

Expected result: a list with 10 recommended books.
Actual result: no data found error.

答:
Unless I'm wrong, the only place that might return NO_DATA_FOUND is the getGenre function, as it has a SELECT some value into a variable, and no exceptions are handled. Other SELECTs use aggregates (which will return 0 if there's nothing there).

Therefore, fix that function, e.g.

```<code>CREATE OR REPLACE FUNCTION getGenre(bookISBN IN VARCHAR2)
  RETURN VARCHAR2
AS
  v_bookGenre VARCHAR2(100);
BEGIN
  select genre
    into v_bookGenre
    from books where bookISBN = isbn;

  return v_bookGenre;

EXCEPTION
  when no_data_found then
    return null;
END getGenre;
</code>```

By the way, why did you use an inline view in that function? Why didn't you simply return genre from the table itself (like I did)?

Title: How to avoid no data exception?

Body:
I am working on a project and I have a database schema written in Oracle db for a library. I have some issues when trying to build a function which should provide some recommendations for the user.

The recommendations should be given based on the last books genres some user had borrowed in the past month and the most read books of all users. Every time I try to run the function I get a no data error even if I have values in the tables.

    CREATE OR REPLACE FUNCTION getGenre(bookISBN IN VARCHAR2) RETURN VARCHAR2
    AS
      v_bookGenre VARCHAR2(100);
    BEGIN
      select genre into v_bookGenre from (select genre from books where bookISBN=isbn);
      return v_bookGenre;
    END getGenre;
    /
    CREATE OR REPLACE TYPE t IS TABLE OF varchar2(200);
    /
    create or replace type typeRecom is VARRAY(200) of VARCHAR2(200);
    /
    CREATE OR REPLACE FUNCTION topRecommandations(idUser IN VARCHAR2)
    RETURN typeRecom
    AS

      lastGenres t :=t();
      readedBooks t:=t();
      topTen typeRecom;

      v_i NUMBER := 1;
      v_j NUMBER := 1;

      verifDateBook NUMBER:=0;
      verifDateLoan NUMBER:=0;

    BEGIN
      select count(*) into verifDateBook from books;
      if(verifDateBook = 0) then
        raise no_data_found;
      end if;

      select count(*) into verifDateLoan from loans;
      if(verifDateLoan = 0) then
        raise no_data_found;
      end if;

      lastGenres.extend();
      for i in (select genre from books join loans on books.isbn=loans.bookId where loanDate>add_months(sysdate,-1) and idUser=loans.regNo order by genre desc) loop
        DBMS_OUTPUT.PUT_LINE(i.genre);
        lastGenres.extend();
        lastGenres(lastGenres.count) := i.genre;
      end loop;
      /*select title into bookTitles from book join loan on book.isbn=loan.regNo;*/
       readedBooks.extend();
       for i in (select bookId from loans group by bookId order by count(bookId) desc) loop
        readedBooks.extend();
        readedBooks(readedBooks.count) := i.bookId;
      end loop;
      --select bookId into readedBooks from loan order by count(bookId) desc;

      for v_i IN 1..50 LOOP
        for v_j in 1..50 LOOP
          DBMS_OUTPUT.PUT_LINE(lastGenres(v_j));
          DBMS_OUTPUT.PUT_LINE(getGenre(readedBooks(v_i)));
          if(lastGenres(v_j)=getGenre(readedBooks(v_i))) then
            topTen(v_i) := getGenre(readedBooks(v_j));
          end if;
        EXIT WHEN topTen.count=10;
        END LOOP;
      EXIT WHEN topTen.count=10;
      end LOOP;
      for v_cont in 1..10 LOOP
            --if(topTen.count <= 10) then
            DBMS_OUTPUT.PUT_LINE(topTen(v_cont));
          --end if;
      end loop;
      return topTen;
      EXCEPTION
      WHEN no_data_found THEN
        DBMS_OUTPUT.PUT_LINE('Nu exista valori.');

    END topRecommandations;

Expected result: a list with 10 recommended books.
Actual result: no data found error.

Body:
Unless I'm wrong, the only place that might return NO_DATA_FOUND is the getGenre function, as it has a SELECT some value into a variable, and no exceptions are handled. Other SELECTs use aggregates (which will return 0 if there's nothing there).

Therefore, fix that function, e.g.

CREATE OR REPLACE FUNCTION getGenre(bookISBN IN VARCHAR2)
  RETURN VARCHAR2
AS
  v_bookGenre VARCHAR2(100);
BEGIN
  select genre
    into v_bookGenre
    from books where bookISBN = isbn;

  return v_bookGenre;

EXCEPTION
  when no_data_found then
    return null;
END getGenre;

By the way, why did you use an inline view in that function? Why didn't you simply return genre from the table itself (like I did)?


问:
How to rotate arbitrary degree an image
I want to rotate an image N degree
I write this code but it does not work what should I do?

```<code>var N=20
    function rotateImage() {
        var img = document.getElementById('myimage');
        img.style.transform = 'rotate(Ndeg)';

    }
</code>```

and

```<code>img.style.transform = 'rotate(${N}deg)';
</code>```

does not work but
    img.style.transform = 'rotate(20deg)';
works

答:
Try this

var N=100;
    function rotate () {
        var img = document.getElementById('myimage');
        img.style.transform = 'rotate( '+N+'deg)';
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://i.stack.imgur.com/zbLrE.png" i id="myimage" onclick="rotate ();" /></code>```

Title: How to rotate arbitrary degree an image

Body:
I want to rotate an image N degree
I write this code but it does not work what should I do?

var N=20
    function rotateImage() {
        var img = document.getElementById('myimage');
        img.style.transform = 'rotate(Ndeg)';

    }

and

img.style.transform = 'rotate(${N}deg)';

does not work but
    img.style.transform = 'rotate(20deg)';
works

Body:
Try this

var N=100;
    function rotate () {
        var img = document.getElementById('myimage');
        img.style.transform = 'rotate( '+N+'deg)';
    }

<img src="http://i.stack.imgur.com/zbLrE.png" i id="myimage" onclick="rotate ();" />


问:
autocomplete text search
can any body tell me steps to use it, where i can get simple example for this </p>

答:
yes, please follow the following steps

Download jquery.ui library from here. jquery comes with it.

link jquery library

link <link href="jquery.ui.someversion.css" rel="stylesheet"/>

link jquery ui libarary

rest of the code is given here. just click View Source link and you will find it.

View source

From some url

```<code> $('#autocomplete').autocomplete({
        source        : 'someurl.php'
    });
</code>```

and on some URL, you can query your database with the parameter and print auto-complete data that will be displayed in your auto-complete.

Title: autocomplete text search

Body:
yes, please follow the following steps

Download jquery.ui library from here. jquery comes with it.

link jquery library <script src="jquery-someversion.js"></script>

link <link href="jquery.ui.someversion.css" rel="stylesheet"/>

link jquery ui libarary <script src="jquery.ui.someversion.js"></script>

rest of the code is given here. just click View Source link and you will find it.

View source

From some url

 $('#autocomplete').autocomplete({
        source        : 'someurl.php'
    });

and on some URL, you can query your database with the parameter and print auto-complete data that will be displayed in your auto-complete.