问:
Length after decimal point
Below code gives error if I enter more than 3 values after decimal. But I want to increase the length after decimal from 2 to 3.

I have increased precisionValue.length()>2 to precisionValue.length()>3. but the error remains same

```<code>       if (str != null && str.length() > 0) {
        boolean month2 = validator.validateDecimal(str.trim());
        if (!month2) {
            errors.rejectValue(MONTH2, "10005");
        }
        if(str.contains(".")){
            String decValue = str.substring(0, str.indexOf("."));
            String precisionValue = str.substring(str.indexOf(".")+1);
            if(decValue.length()>9) {
                errors.rejectValue(MONTH2, "10035");
            }
            if(precisionValue.length()>2) {
                errors.rejectValue(MONTH2, "10038");
            }
        }
        else if(str.length()>9) {
            errors.rejectValue(MONTH2, "10035");
        }
             }
</code>```

答:
I have assumed that it is in C# and corrected the syntax. You can do in reverse to achieve your programming language. If I choose a number in string format having more than 3 digits after decimal, it should go in  errors.rejectValue(month2, "10038"); line of code and it is working in expected way. I cannot understand your problem completely.</p>

```<code>            string str = "1.2345";
            if (str != null && str.Length > 0)
            {
                bool month2 = validator.validateDecimal(str.Trim());
                if (!month2)
                {
                    errors.rejectValue(month2, "10005");
                }
                if (str.Contains("."))
                {
                    String decValue = str.Substring(0, str.IndexOf("."));
                    String precisionValue = str.Substring(str.IndexOf(".") + 1);
                    if (decValue.Length > 9)
                    {
                        errors.rejectValue(month2, "10035");
                    }
                    if (precisionValue.Length > 3)
                    {
                        errors.rejectValue(month2, "10038");
                    }
                }
                else if (str.Length > 9)
                {
                    errors.rejectValue(month2, "10035");
                }
            }
</code>```

Title: Length after decimal point

Body:
Below code gives error if I enter more than 3 values after decimal. But I want to increase the length after decimal from 2 to 3.

I have increased precisionValue.length()>2 to precisionValue.length()>3. but the error remains same

       if (str != null && str.length() > 0) {
        boolean month2 = validator.validateDecimal(str.trim());
        if (!month2) {
            errors.rejectValue(MONTH2, "10005");
        }
        if(str.contains(".")){
            String decValue = str.substring(0, str.indexOf("."));
            String precisionValue = str.substring(str.indexOf(".")+1);
            if(decValue.length()>9) {
                errors.rejectValue(MONTH2, "10035");
            }
            if(precisionValue.length()>2) {
                errors.rejectValue(MONTH2, "10038");
            }
        }
        else if(str.length()>9) {
            errors.rejectValue(MONTH2, "10035");
        }
             }

Body:
I have assumed that it is in C# and corrected the syntax. You can do in reverse to achieve your programming language. If I choose a number in string format having more than 3 digits after decimal, it should go in  errors.rejectValue(month2, "10038"); line of code and it is working in expected way. I cannot understand your problem completely.

            string str = "1.2345";
            if (str != null && str.Length > 0)
            {
                bool month2 = validator.validateDecimal(str.Trim());
                if (!month2)
                {
                    errors.rejectValue(month2, "10005");
                }
                if (str.Contains("."))
                {
                    String decValue = str.Substring(0, str.IndexOf("."));
                    String precisionValue = str.Substring(str.IndexOf(".") + 1);
                    if (decValue.Length > 9)
                    {
                        errors.rejectValue(month2, "10035");
                    }
                    if (precisionValue.Length > 3)
                    {
                        errors.rejectValue(month2, "10038");
                    }
                }
                else if (str.Length > 9)
                {
                    errors.rejectValue(month2, "10035");
                }
            }


来源: stackexchange

问:
Call a class method as soon as an object it extends is created
Assume we have the following class (simplified):

```<code>class SuperConfig {
    public $mainDir;

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}
</code>```

This class is supposed to be extended in EVERY other class in the project, and I do need the setDir() function of the parent to be executed. Obviously, I could do it like this:

```<code>class A extends SuperConfig() {
    public function __construct() {
        parent::setDir();
    }
    // ... other stuff is about to be done ...
}
</code>```

and I could access the properties in the child class like this:

```<code>class A extends SuperConfig {
    public function doSomething() {
        SuperConfig::mainDir;
    }
}
</code>```

This is a viable solution, but I got multiple hundreds of classes and doing this in every single one seems tedious. So, is there a way to do something like this:

```<code>class SuperConfig {
    public $mainDir;

    public function __extend() {
        $this->setDir();
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}
</code>```

__extend() obviously doesn't work like that, but I'm wondering is there is a trick how I could make this work.

答:
Put the constructor in the class that is being extended.

```<code>class SuperConfig {
    public $mainDir;

    public function __construct() {
        $this->setDir();
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}
</code>```

In any class that extends SuperConfig, if they have a constructor also, be sure to include parent::__construct(); so that setDir is called.

ContentLicense: CC BY-SA 3.0

Body:
Assume we have the following class (simplified):

class SuperConfig {
    public $mainDir;

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

This class is supposed to be extended in EVERY other class in the project, and I do need the setDir() function of the parent to be executed. Obviously, I could do it like this:

class A extends SuperConfig() {
    public function __construct() {
        parent::setDir();
    }
    // ... other stuff is about to be done ...
}

and I could access the properties in the child class like this:

class A extends SuperConfig {
    public function doSomething() {
        SuperConfig::mainDir;
    }
}

This is a viable solution, but I got multiple hundreds of classes and doing this in every single one seems tedious. So, is there a way to do something like this:

class SuperConfig {
    public $mainDir;

    public function __extend() {
        $this->setDir();
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

__extend() obviously doesn't work like that, but I'm wondering is there is a trick how I could make this work.

Body:
Put the constructor in the class that is being extended.

class SuperConfig {
    public $mainDir;

    public function __construct() {
        $this->setDir();
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

In any class that extends SuperConfig, if they have a constructor also, be sure to include parent::__construct(); so that setDir is called.


问:
PHP Timezone Name to Offset
How would I go about converting a timezone name ("Asia/Dubai", "Europe/Andorra", etc) to a GMT offset in hours (or even seconds, since I can convert it from there).

Most people ask for the reverse, but I need to get a timezone offset from the timezone name provided by GeoNames.

答:
you can use the following</p>

```<code><?php

$timezone = 'Pacific/Nauru';
$time = new \DateTime('now', new DateTimeZone($timezone));
$timezoneOffset = $time->format('P');
?>
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP Timezone Name to Offset

Body:
you can use the following

<?php

$timezone = 'Pacific/Nauru';
$time = new \DateTime('now', new DateTimeZone($timezone));
$timezoneOffset = $time->format('P');
?>


问:
Value Objects holding Entities
In the book, Eric Evans shows an example where an VALUE OBJECT holds ENTITIES. VALUE OBJECTS are immutable, ENTITIES not.

The question is: If an ENTITY that
is referenced from an VALUE OBJECT change its state, was the immutability been broken?

In my opinion it doesn't break the immutability, because the "value" of the
object lies on the ENTITIES array, not on their states.

What do you guys think?

答:
It depends if you can mutate the entities directly through the VO or not.

Imagine a VO instance that can be shared between multiple objects. If the VO contains a mutable entity and exposes it as a public member, multiple clients may update the entity concurrently. This leads to problems you would expect not to happen with actual immutability.

If the VO only holds the ID of the referenced entity on the other hand, you would have to fetch a brand new instance from a Repository before changing it, avoiding the shared mutable state issue.

Title: Value Objects holding Entities


问:
How create Key event and pass it to document?
I'd like to test key event handler.
I searched and found the result that uses 'createEvent', 'dispatchEvent'.

```<code>var e = document.createEvent('HTMLEvents');
e.keyCode = 83;
e.initEvent(onkeydown, false, true);
document.dispathEvent(e);
</code>```

I did like above but not working.
Could you somebody give me a sample or link?

答:
document.addEventListener('onkeydown', function (e) {
      console.log("onkeydown event raised");
    console.log(e);
 });
 var e = document.createEvent('HTMLEvents');
 e.keyCode = 83;
 e.initEvent('onkeydown', true, true);
 document.dispatchEvent(e);```

You may go through this

Body:
I'd like to test key event handler.
I searched and found the result that uses 'createEvent', 'dispatchEvent'.

var e = document.createEvent('HTMLEvents');
e.keyCode = 83;
e.initEvent(onkeydown, false, true);
document.dispathEvent(e);

I did like above but not working.
Could you somebody give me a sample or link?

Body:
document.addEventListener('onkeydown', function (e) {
      console.log("onkeydown event raised");
    console.log(e);
 });
 var e = document.createEvent('HTMLEvents');
 e.keyCode = 83;
 e.initEvent('onkeydown', true, true);
 document.dispatchEvent(e);

You may go through this


问:
Django: sqlite3.OperationalError: no such table in python shell
I'm following a django blog tutorial. When I used python manage.py shell and tried following commands in shell

```<code>from mainsite.models import Category, Tag
c = Category(name='category test')
c.save()
</code>```

this error occured:

```<code>sqlite3.OperationalError: no such table: mainsite_category
</code>```

This is my model.py in mainsite folder, which I think is correct:

```<code>from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
    name = models.CharField(max_length=100)

def __str__(self):
    return self.name
</code>```

I have tried manage.py makemigrations, manage.py migrate and can successfully use manage.py runserver to see the website. So what is wrong here?

Edit: this is my INSTALLED APP in settings.py

```<code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mainsite',
]
</code>```

And my project structure

```<code>|____djangoBlog
| |______init__.py
| |____settings.py
| |____urls.py
| |____wsgi.py
|____mainsite
| |______init__.py
| |____admin.py
| |____apps.py
| |____models.py
| |____tests.py
| |____urls.py
| |____views.py
|____manage.py
|____README.md
|____requirements.txt
|____templates
| |____blog
| | |____index.html
</code>```

Edit: When I run python manage.py makemigrations and python manage.py migrate, the output is as follows:

```<code>No changes detected

Operations to perform:
    Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
    No migrations to apply.
</code>```

答:
@Owen,
According to vishes_shell's answer, you'll have to do :

```<code>python manage.py makemigrations mainsite
</code>```

the first time in order to generate a folder migrations that will contain your migrations, then you can just do

```<code>python manage.py makemigrations
</code>```

In the futur if you add a new app, don't forget to make again the first command (changing the "mainsite" by the name of your app) before using the second one.

Body:
I'm following a django blog tutorial. When I used python manage.py shell and tried following commands in shell

from mainsite.models import Category, Tag
c = Category(name='category test')
c.save()

this error occured:

sqlite3.OperationalError: no such table: mainsite_category

This is my model.py in mainsite folder, which I think is correct:

from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
    name = models.CharField(max_length=100)

def __str__(self):
    return self.name

I have tried manage.py makemigrations, manage.py migrate and can successfully use manage.py runserver to see the website. So what is wrong here?

Edit: this is my INSTALLED APP in settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mainsite',
]

And my project structure

|____djangoBlog
| |______init__.py
| |____settings.py
| |____urls.py
| |____wsgi.py
|____mainsite
| |______init__.py
| |____admin.py
| |____apps.py
| |____models.py
| |____tests.py
| |____urls.py
| |____views.py
|____manage.py
|____README.md
|____requirements.txt
|____templates
| |____blog
| | |____index.html

Edit: When I run python manage.py makemigrations and python manage.py migrate, the output is as follows:

No changes detected

Operations to perform:
    Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
    No migrations to apply.

Body:
@Owen,
According to vishes_shell's answer, you'll have to do :

python manage.py makemigrations mainsite

the first time in order to generate a folder migrations that will contain your migrations, then you can just do

python manage.py makemigrations

In the futur if you add a new app, don't forget to make again the first command (changing the "mainsite" by the name of your app) before using the second one.


问:
How to check if relativedelta object is negative
I have some problem with using relativedelta objects - cannot determine if "delta is negative". What I'm trying is:

```<code>from dateutil.relativedelta import relativedelta
print relativedelta(seconds=-5) > 0
</code>```

that gives me True which is counter intuitive.

```<code>print relativedelta(seconds=5) > 0
</code>```

also return True. Is there a way to check if "delta" represented by relativedata object is negative?

I'm currently using a workaround in the form of separate function to check if delta is negative but I expected that there is more elegant solution. Here is code I'm using:

```<code>def is_relativedelta_positive(rel_delta):
    is_positive = True
    is_positive &= rel_delta.microseconds >= 0
    is_positive &= rel_delta.seconds >= 0
    is_positive &= rel_delta.minutes >= 0
    is_positive &= rel_delta.hours >= 0
    is_positive &= rel_delta.days >= 0
    return is_positive
</code>```

答:
relativedelta() objects do not implement the necessary comparison methods. In Python 2 that means that they are thus compared by their type name, and numbers are always sorted before any other objects; this makes these objects larger than integer values whatever their values. In Python 3 you'd get a TypeError instead.

Your work-around doesn't account for an absolute positive value, relativedelta(years=1, seconds=-5) would move your datetime by almost a whole year forward, so it could hardly be named a negative delta.

You'd have to compare individual attributes instead (so years, months, days, hours, minutes, seconds and microseconds). Depending on your use-case, you may have to convert those to a total number of seconds:

```<code>def total_seconds(rd, _yeardays=365.2425, _monthdays=365.2425/12):
    """approximation of the number of seconds in a relative delta"""
    # year and month durations are averages, taking into account leap years
    total_days = rd.years * _yeardays + (rd.months * _monthdays) + rd.days
    total_hours = total_days * 24 + rd.hours
    total_minutes = total_hours * 60 + rd.minutes
    return total_minutes * 60 + rd.seconds + (rd.microseconds / 1000000)
</code>```

then use this to do your comparisons:

```<code>if total_seconds(relativedelta(seconds=-5)) > 0:
</code>```

The total_seconds() function produces an approximation; relative deltas handle leap years and the right number of days per month, so their actual effect on a datetime object will vary depending on that datetime value. However, the above should be good enough for the majority of cases. It does completely ignore the absolute components of the relative delta (hour, year, the singular names, that state a fixed value rather than a delta).

Body:
I have some problem with using relativedelta objects - cannot determine if "delta is negative". What I'm trying is:

from dateutil.relativedelta import relativedelta
print relativedelta(seconds=-5) > 0

that gives me True which is counter intuitive.

print relativedelta(seconds=5) > 0

also return True. Is there a way to check if "delta" represented by relativedata object is negative?

I'm currently using a workaround in the form of separate function to check if delta is negative but I expected that there is more elegant solution. Here is code I'm using:

def is_relativedelta_positive(rel_delta):
    is_positive = True
    is_positive &= rel_delta.microseconds >= 0
    is_positive &= rel_delta.seconds >= 0
    is_positive &= rel_delta.minutes >= 0
    is_positive &= rel_delta.hours >= 0
    is_positive &= rel_delta.days >= 0
    return is_positive

Body:
relativedelta() objects do not implement the necessary comparison methods. In Python 2 that means that they are thus compared by their type name, and numbers are always sorted before any other objects; this makes these objects larger than integer values whatever their values. In Python 3 you'd get a TypeError instead.

Your work-around doesn't account for an absolute positive value, relativedelta(years=1, seconds=-5) would move your datetime by almost a whole year forward, so it could hardly be named a negative delta.

You'd have to compare individual attributes instead (so years, months, days, hours, minutes, seconds and microseconds). Depending on your use-case, you may have to convert those to a total number of seconds:

def total_seconds(rd, _yeardays=365.2425, _monthdays=365.2425/12):
    """approximation of the number of seconds in a relative delta"""
    # year and month durations are averages, taking into account leap years
    total_days = rd.years * _yeardays + (rd.months * _monthdays) + rd.days
    total_hours = total_days * 24 + rd.hours
    total_minutes = total_hours * 60 + rd.minutes
    return total_minutes * 60 + rd.seconds + (rd.microseconds / 1000000)

then use this to do your comparisons:

if total_seconds(relativedelta(seconds=-5)) > 0:

The total_seconds() function produces an approximation; relative deltas handle leap years and the right number of days per month, so their actual effect on a datetime object will vary depending on that datetime value. However, the above should be good enough for the majority of cases. It does completely ignore the absolute components of the relative delta (hour, year, the singular names, that state a fixed value rather than a delta).


问:
How to force a refresh on the Project Explorer view?
I created a Wizard that when finished, adds two files at the Project Explorer.
One of them should be hidden, but when I press the Finish button at my wizard, Eclipse doesn't refresh the view automatically and it keeps showing the file. It just hide it when I press F5.
There's a way to force it to refresh the Project Explorer, right after I finish the wizard?</p>

答:
It sounds like you aren't using Eclipse resources API to make file system changes. You have two options:

The best option is to use Eclipse resource API instead of java.io when working with contents of Eclipse projects. See org.eclipse.resources plugin. Start with ResourcesPlugin.getWorkspace().getRoot().getProject( "name" ). Use IProject, IFile and IFolder API.

Alternatively, especially if your wizard is invoking code that isn't eclipse-aware, you need to invoke refresh after you are sure that all java.io based file system operations have been completed. Use refreshLocal() method, which is available on IProject, IFile and IFolder classes. For instance, the following snippet refreshes all contents of a given project. This is typically an overkill, so you will want to narrow down the scope as much as possible before invoking refresh.

ResourcesPlugin.getWorkspace().getRoot().getProject( "proj" ).refreshLocal( IResource.DEPTH_INFINITE, new NullProgressMonitor() );


问:
How to check two parameter($other and $user) of function in laravel repository?
How to check two parameter($other and $user) of function in laravel repository

I have this query:

```<code> public function GetFriend($other,$user)
 {
  $list = $this->makeModel()
        ->where(function ($query) {
            $query->where('otheruser',$other)
                  ->orWhere('user_id',$user);
        })
        ->get();
        return $list;
 }
</code>```

i have user table(MongoDB):

```<code>{
   _id : 59db41e78ed7bc5c0d000029,
   is_active : true
},
{
   _id : 59db41e78ed7bc5c0d000031,
   is_active : true
}
</code>```

I have friend table(MongoDB):

```<code>{
    _id : 1234567890,
    otheruser : 59db41e78ed7bc5c0d000031,
    user_id : 59db41e78ed7bc5c0d000029,
    is_friend : true
}
</code>```

答:
You forgot to pass the variables to the closure via use method.</p>

```<code>public function GetFriend($other,$user)
 {
  $list = $this->makeModel()
        ->where(function ($query) use ($other, $user) {
            $query->where('otheruser',$other)
                  ->orWhere('user_id',$user);
        })
        ->get();
        return $list;
 }
</code>```

Body:
How to check two parameter($other and $user) of function in laravel repository

I have this query:

 public function GetFriend($other,$user)
 {
  $list = $this->makeModel()
        ->where(function ($query) {
            $query->where('otheruser',$other)
                  ->orWhere('user_id',$user);
        })
        ->get();
        return $list;
 }

i have user table(MongoDB):

{
   _id : 59db41e78ed7bc5c0d000029,
   is_active : true
},
{
   _id : 59db41e78ed7bc5c0d000031,
   is_active : true
}

I have friend table(MongoDB):

{
    _id : 1234567890,
    otheruser : 59db41e78ed7bc5c0d000031,
    user_id : 59db41e78ed7bc5c0d000029,
    is_friend : true
}

Body:
You forgot to pass the variables to the closure via use method.

public function GetFriend($other,$user)
 {
  $list = $this->makeModel()
        ->where(function ($query) use ($other, $user) {
            $query->where('otheruser',$other)
                  ->orWhere('user_id',$user);
        })
        ->get();
        return $list;
 }


问:
Create CloudWatch Alarm to notify about setting a S3 object to public
I want to create on CloudWatch a metric filter and an alarm based on it to notify me about S3 events, specially when a file or a bucket is set to public. This is the metric filter I used to create the metric:

{ ($.eventSource = s3.amazonaws.com) && (($.eventName = PutBucketAcl)
  || ($.eventName = PutObjectAcl)) &&
  (($.requestParameters.AccessControlPolicy.AccessControlList.Grant.Grantee.type
  = Group ))}

I tested this pattern by putting the following Custom log data :

```<code>{
    "Records": [
    {
        "eventVersion": "1.03",
        "userIdentity": {
            "type": "IAMUser",
            "principalId": "111122223333",
            "arn": "arn:aws:iam::111122223333:user/myUserName",
            "accountId": "111122223333",
            "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
            "userName": "myUserName"
        },
        "eventTime": "2015-08-26T20:46:31Z",
        "eventSource": "s3.amazonaws.com",
        "eventName": "DeleteBucketPolicy",
        "awsRegion": "us-west-2",
        "sourceIPAddress": "127.0.0.1",
        "userAgent": "[]",
        "requestParameters": {
            "bucketName": "myawsbucket"
        },
        "responseElements": null,
        "requestID": "47B8E8D397DCE7A6",
        "eventID": "cdc4b7ed-e171-4cef-975a-ad829d4123e8",
        "eventType": "AwsApiCall",
        "recipientAccountId": "111122223333"
    },
    {
       "eventVersion": "1.03",
       "userIdentity": {
            "type": "IAMUser",
            "principalId": "111122223333",
            "arn": "arn:aws:iam::111122223333:user/myUserName",
            "accountId": "111122223333",
            "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
            "userName": "myUserName"
        },
      "eventTime": "2015-08-26T20:46:31Z",
      "eventSource": "s3.amazonaws.com",
      "eventName": "PutBucketAcl",
      "awsRegion": "us-west-2",
      "sourceIPAddress": "",
      "userAgent": "[]",
      "requestParameters": {
          "bucketName": "",
          "AccessControlPolicy": {
              "AccessControlList": {
                  "Grant": {
                      "Grantee": {
                          "xsi:type": "Group",
                          "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
                          "ID": "d25639fbe9c19cd30a4c0f43fbf00e2d3f96400a9aa8dabfbbebe1906Example"
                       },
                      "Permission": "FULL_CONTROL"
                   }
              },
              "xmlns": "http://s3.amazonaws.com/doc/2006-03-01/",
              "Owner": {
                  "ID": "d25639fbe9c19cd30a4c0f43fbf00e2d3f96400a9aa8dabfbbebe1906Example"
              }
          }
      },
      "responseElements": null,
      "requestID": "BD8798EACDD16751",
      "eventID": "607b9532-1423-41c7-b048-ec2641693c47",
      "eventType": "AwsApiCall",
      "recipientAccountId": "111122223333"
    },
    {
      "eventVersion": "1.03",
      "userIdentity": {
          "type": "IAMUser",
          "principalId": "111122223333",
          "arn": "arn:aws:iam::111122223333:user/myUserName",
          "accountId": "111122223333",
          "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
          "userName": "myUserName"
        },
      "eventTime": "2015-08-26T20:46:31Z",
      "eventSource": "s3.amazonaws.com",
      "eventName": "GetBucketVersioning",
      "awsRegion": "us-west-2",
      "sourceIPAddress": "",
      "userAgent": "[]",
      "requestParameters": {
          "bucketName": "myawsbucket"
      },
      "responseElements": null,
      "requestID": "07D681279BD94AED",
      "eventID": "f2b287f3-0df1-4961-a2f4-c4bdfed47657",
      "eventType": "AwsApiCall",
      "recipientAccountId": "111122223333"
    }
  ]
}
</code>```

I clicked Test Pattern and I get this message:

Results Found 0 matches out of 50 event(s) in the sample log.

Is the metric filter proper and correct ? I'm supposed to have one result but it is not coming up.

答:
Calculating whether a policy is providing open access is quite complex, due to the many ways that rules can be specified in the Bucket Policy (for example, wildcards can provide access).

An easier approach would be to use the Amazon S3 Bucket Permissions check in Trusted Advisor:

Checks buckets in Amazon Simple Storage Service (Amazon S3) that have open access permissions or allow access to any authenticated AWS user.

You can then Monitor Trusted Advisor Check Results with Amazon CloudWatch Events.

However, that particular check is not included in the Free Tier for Trusted Advisor. You would need to be on a Support Plan for that check to operate.

The Amazon S3 console was also recently updated -- it now clearly shows any buckets with public permissions.

Body:
I want to create on CloudWatch a metric filter and an alarm based on it to notify me about S3 events, specially when a file or a bucket is set to public. This is the metric filter I used to create the metric:

{ ($.eventSource = s3.amazonaws.com) && (($.eventName = PutBucketAcl)
  || ($.eventName = PutObjectAcl)) &&
  (($.requestParameters.AccessControlPolicy.AccessControlList.Grant.Grantee.type
  = Group ))}

I tested this pattern by putting the following Custom log data :

{
    "Records": [
    {
        "eventVersion": "1.03",
        "userIdentity": {
            "type": "IAMUser",
            "principalId": "111122223333",
            "arn": "arn:aws:iam::111122223333:user/myUserName",
            "accountId": "111122223333",
            "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
            "userName": "myUserName"
        },
        "eventTime": "2015-08-26T20:46:31Z",
        "eventSource": "s3.amazonaws.com",
        "eventName": "DeleteBucketPolicy",
        "awsRegion": "us-west-2",
        "sourceIPAddress": "127.0.0.1",
        "userAgent": "[]",
        "requestParameters": {
            "bucketName": "myawsbucket"
        },
        "responseElements": null,
        "requestID": "47B8E8D397DCE7A6",
        "eventID": "cdc4b7ed-e171-4cef-975a-ad829d4123e8",
        "eventType": "AwsApiCall",
        "recipientAccountId": "111122223333"
    },
    {
       "eventVersion": "1.03",
       "userIdentity": {
            "type": "IAMUser",
            "principalId": "111122223333",
            "arn": "arn:aws:iam::111122223333:user/myUserName",
            "accountId": "111122223333",
            "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
            "userName": "myUserName"
        },
      "eventTime": "2015-08-26T20:46:31Z",
      "eventSource": "s3.amazonaws.com",
      "eventName": "PutBucketAcl",
      "awsRegion": "us-west-2",
      "sourceIPAddress": "",
      "userAgent": "[]",
      "requestParameters": {
          "bucketName": "",
          "AccessControlPolicy": {
              "AccessControlList": {
                  "Grant": {
                      "Grantee": {
                          "xsi:type": "Group",
                          "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
                          "ID": "d25639fbe9c19cd30a4c0f43fbf00e2d3f96400a9aa8dabfbbebe1906Example"
                       },
                      "Permission": "FULL_CONTROL"
                   }
              },
              "xmlns": "http://s3.amazonaws.com/doc/2006-03-01/",
              "Owner": {
                  "ID": "d25639fbe9c19cd30a4c0f43fbf00e2d3f96400a9aa8dabfbbebe1906Example"
              }
          }
      },
      "responseElements": null,
      "requestID": "BD8798EACDD16751",
      "eventID": "607b9532-1423-41c7-b048-ec2641693c47",
      "eventType": "AwsApiCall",
      "recipientAccountId": "111122223333"
    },
    {
      "eventVersion": "1.03",
      "userIdentity": {
          "type": "IAMUser",
          "principalId": "111122223333",
          "arn": "arn:aws:iam::111122223333:user/myUserName",
          "accountId": "111122223333",
          "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
          "userName": "myUserName"
        },
      "eventTime": "2015-08-26T20:46:31Z",
      "eventSource": "s3.amazonaws.com",
      "eventName": "GetBucketVersioning",
      "awsRegion": "us-west-2",
      "sourceIPAddress": "",
      "userAgent": "[]",
      "requestParameters": {
          "bucketName": "myawsbucket"
      },
      "responseElements": null,
      "requestID": "07D681279BD94AED",
      "eventID": "f2b287f3-0df1-4961-a2f4-c4bdfed47657",
      "eventType": "AwsApiCall",
      "recipientAccountId": "111122223333"
    }
  ]
}

I clicked Test Pattern and I get this message:

Results Found 0 matches out of 50 event(s) in the sample log.

Is the metric filter proper and correct ? I'm supposed to have one result but it is not coming up.


问:
Why a struct declared by let can be changed?
In the following code, 'ptr' is a struct declared by let, but its member variable 'pointee' could be changed, Why?

    let ptr = UnsafeMutablePointer<Int>.allocate(capacity:1)
    ptr.pointee = 1

答:
In case of a Pointer, you cannot change the memory address it is pointing to, but you can change the data stored at that memory address.
The Pointer is only storing a reference to a memory address, so as long as that address is constant, the Pointer didn't change its value.</p>


问:
how to retrieve player names who never scored a century?
My Data is like this. So, I want to see the list of Players who never scored a Century in their entire career.
Sample Data

答:
Try Group by.. Having clause with MAX() to find out players name who never scored century

```<code>SELECT NAME FROM table
GROUP BY NAME
HAVING MAX(SCORE) < 100;
</code>```

Body:
Try Group by.. Having clause with MAX() to find out players name who never scored century

SELECT NAME FROM table
GROUP BY NAME
HAVING MAX(SCORE) < 100;


答:
```<code>;WITH cte
AS(
    SELECT 'Sachin' [NAME], 123 [Score]
    UNION ALL
    SELECT 'Sachin' [NAME], 44 [Score]
    UNION ALL
    SELECT 'Kumble' [NAME], 22 [Score]
    UNION ALL
    SELECT 'Kumble' [NAME], 77 [Score]
)
SELECT
    X.NAME
    ,MAX(X.Score)
FROM cte X
GROUP BY
    X.NAME
HAVING
    MAX(X.Score) < 100
</code>```

Title: how to retrieve player names who never scored a century?

Body:
My Data is like this. So, I want to see the list of Players who never scored a Century in their entire career.
Sample Data


问:
Am I using Javascript call-backs appropriately (object-oriented style)?
I have the following code example to use an object that receives the action from the callback.  Doesn't seem like this is a good design pattern.  Or is it?

When setTimeOut() fires on the function after 1 second, it uses the objInstance global variable (DOM scope) to access the ClassExample object instance.  Can someone recommend a better way to utilize callbacks within an object oriented design?

The whole idea is so I can use the callback to update data within my object instance (increment a variable for example).

```<code>function ClassExample{
    this.initiate = function() {
        setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();
</code>```

答:
This is how I'd do it to allow timer reuse and minimize the number of closures:

```<code>function Timer(timeout, callback) {
    this.timeout = timeout;
    this.callback = callback;
}

Timer.prototype.run = function(thisArg /*, args... */) {
    var argArray = Array.prototype.slice.call(arguments, 1);
    var timer = this;

    setTimeout(function() {
        timer.callback.apply(thisArg, argArray);
    }, timer.timeout);
};

var timer = new Timer(1000, alert);
timer.run(null, 'timer fired!');
</code>```

And just for fun, a golfed version which is functionally equivalent, but replaces the object with a closure:

```<code>function delay(func, timeout) {
    return function() {
        var self = this, args = arguments;
        setTimeout(function() { func.apply(self, args); }, timeout);
    };
}

delay(alert, 1000).call(null, 'timer fired!');
</code>```

Body:
I have the following code example to use an object that receives the action from the callback.  Doesn't seem like this is a good design pattern.  Or is it?

When setTimeOut() fires on the function after 1 second, it uses the objInstance global variable (DOM scope) to access the ClassExample object instance.  Can someone recommend a better way to utilize callbacks within an object oriented design?

The whole idea is so I can use the callback to update data within my object instance (increment a variable for example).

function ClassExample{
    this.initiate = function() {
        setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();

Body:
This is how I'd do it to allow timer reuse and minimize the number of closures:

function Timer(timeout, callback) {
    this.timeout = timeout;
    this.callback = callback;
}

Timer.prototype.run = function(thisArg /*, args... */) {
    var argArray = Array.prototype.slice.call(arguments, 1);
    var timer = this;

    setTimeout(function() {
        timer.callback.apply(thisArg, argArray);
    }, timer.timeout);
};

var timer = new Timer(1000, alert);
timer.run(null, 'timer fired!');

And just for fun, a golfed version which is functionally equivalent, but replaces the object with a closure:

function delay(func, timeout) {
    return function() {
        var self = this, args = arguments;
        setTimeout(function() { func.apply(self, args); }, timeout);
    };
}

delay(alert, 1000).call(null, 'timer fired!');


问:
DRY Then and Always in jQuery Promise
I have the following example JS code:

```<code>function loadData(url, data) {
    return $.get(url, data ? data : {});
}

function example1() {

    showSpinner();

    $.when(loadData('/example1', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}

function example2() {

    showSpinner();

    $.when(loadData('/example2', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .then(function () {
            // do something else
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}
</code>```

Both example1() and example2() use the same promise logic and will do something different with the returned data and then always hide the spinner and handle the failures the same (if any). The issue is that I may want to do different things after the data is loaded in each example and have multiple then's follow.

However I am having to repeat the always and fail code. How can I make them more DRY so they are only written once but used in both scenarios (and other examples if need be). So I can't just move the when into a method and pass a callback as there maybe more than one and in different then`s. So this wouldn't work:

```<code>function customPromise(load, callback) {

    showSpinner();

    $.when(load)
    .then(function (resp) {
        callback(resp);
    })
    .always(function(){
        hideSpinner();
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        handleError(jqXHR);
    });

}

function example3() {
    customPromise(loadData('/example2', { hello: 'world' }));
}
</code>```

答:
If you have successive and unknown number of callbacks, I suggest you move the whole processing to the created function:

```<code>function handleRequest(url, data, errorCallback) {
    // create promise
    let promise = $.get(url, data ? data : {});

    // if callback functions provided as args, chain them in `then()` calls
    if (arguments.length > 3) {
        let callbacks = Array.slice.call(arguments, 3);
        let fn = (results) => (results);
        let callback;
        for (let i = 0; i < callbacks.length; i++) {
            callback = callbacks[i] instanceof Function ? callbacks[i] : fn;
            promise.then(callback);
        }
    }

    // handle static behavior
    promise.always(() => {
        hideSpinner();
    })
    .fail(errorCallback);

    // return the created promise
    return promise;
}
</code>```

You can now use this function as follows:

```<code>handleRequest(
    '/example',
    {},
    (jqXHR, textStatus, errorThrown) => {
        handleError(jqXHR);
    },
    (resp) => {
        // do something with the data
    },
    () => {
        // do something else
    }
);
</code>```

Title: DRY Then and Always in jQuery Promise

Body:
I have the following example JS code:

function loadData(url, data) {
    return $.get(url, data ? data : {});
}

function example1() {

    showSpinner();

    $.when(loadData('/example1', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}

function example2() {

    showSpinner();

    $.when(loadData('/example2', { hello: 'world' }))
        .then(function (resp) {
            // do something with the data
        })
        .then(function () {
            // do something else
        })
        .always(function(){
            hideSpinner();
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            handleError(jqXHR);
        });
}

Both example1() and example2() use the same promise logic and will do something different with the returned data and then always hide the spinner and handle the failures the same (if any). The issue is that I may want to do different things after the data is loaded in each example and have multiple then's follow.

However I am having to repeat the always and fail code. How can I make them more DRY so they are only written once but used in both scenarios (and other examples if need be). So I can't just move the when into a method and pass a callback as there maybe more than one and in different then`s. So this wouldn't work:

function customPromise(load, callback) {

    showSpinner();

    $.when(load)
    .then(function (resp) {
        callback(resp);
    })
    .always(function(){
        hideSpinner();
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        handleError(jqXHR);
    });

}

function example3() {
    customPromise(loadData('/example2', { hello: 'world' }));
}

Body:
If you have successive and unknown number of callbacks, I suggest you move the whole processing to the created function:

function handleRequest(url, data, errorCallback) {
    // create promise
    let promise = $.get(url, data ? data : {});

    // if callback functions provided as args, chain them in `then()` calls
    if (arguments.length > 3) {
        let callbacks = Array.slice.call(arguments, 3);
        let fn = (results) => (results);
        let callback;
        for (let i = 0; i < callbacks.length; i++) {
            callback = callbacks[i] instanceof Function ? callbacks[i] : fn;
            promise.then(callback);
        }
    }

    // handle static behavior
    promise.always(() => {
        hideSpinner();
    })
    .fail(errorCallback);

    // return the created promise
    return promise;
}

You can now use this function as follows:

handleRequest(
    '/example',
    {},
    (jqXHR, textStatus, errorThrown) => {
        handleError(jqXHR);
    },
    (resp) => {
        // do something with the data
    },
    () => {
        // do something else
    }
);


问:
Composer: can I ask for requirement alternatives?
With Composer, I can display an error before the installation if all the requirements are not met.

But can I tell it to chose between two alternatives ?

For instance, I want to use image manipulation on my project. I have to check whether gd2 or imageMagick are present. But if I list them both in my require key, an error will be thrown if I don't have both of them.

```<code>{
  "require": {
    "php": ">=7.0",
    "ext-gd": "*",
    "ext-imagick": "*"
  },
}
</code>```

How can I tell Composer it may use gd OR imagick ?

答: That's not possible. See https://github.com/composer/composer/issues/751 and https://github.com/composer/composer/issues/2940 for some more information.</p>

Body:
With Composer, I can display an error before the installation if all the requirements are not met.

But can I tell it to chose between two alternatives ?

For instance, I want to use image manipulation on my project. I have to check whether gd2 or imageMagick are present. But if I list them both in my require key, an error will be thrown if I don't have both of them.

{
  "require": {
    "php": ">=7.0",
    "ext-gd": "*",
    "ext-imagick": "*"
  },
}

How can I tell Composer it may use gd OR imagick ?


问:
how to make the background image in a canvas expand with the window?
I am trying to set the background image of weather app I tried to use canvas for that but the image doesn't expand as the window and it expands only when I click search to see the results , the labels come out messy as although I used grid

can someone help me to fix this please

here is the code

```<code>import requests
import pandas as pd
import json
import requests
import tkinter as tk
from PIL import Image, ImageTk
root=tk.Tk()
root.minsize(width=1025, height=522)
def get_entry(*args):
    api_address='http://api.openweathermap.org/data/2.5/weathe?appid=4f825a5771554e0c8fcccb7be76aab11&q='
    city=entry_1.get()
    url = api_address + city
    json_data = requests.get(url).json()
    format_add = json_data['weather'][0]['description']
    temp=json_data['main']['temp']
    press=json_data['main']['pressure']
    wind=json_data['wind']['speed']
</code>```

displaying results through labels:

```<code>    label_2=tk.Label(canvas, text='the weather in '+city+' : '+format_add)
    label_3=tk.Label(canvas, text='the temperature :' +str(temp))
    label_4=tk.Label(canvas, text='the pressure:' +str(press))
    label_5=tk.Label(canvas, text='the wind speed:' +str(wind))
    label_2.grid(row=5,column=0,sticky='e',padx=20,pady=20)
    label_3.grid(row=6,column=0,sticky='e',padx=20,pady=20)
    label_4.grid(row=7,column=0,sticky='e',padx=20,pady=20)
    label_5.grid(row=8,column=0,sticky='e',padx=20,pady=20)
    Label = tk.Label(canvas, text =str(city), font = ('Comic Sans MS',30),
     fg = 'blue')
    Label.grid(row=4,column=630,sticky='n')
    rain_Frame=(root)
    rain_Frame.grid()
</code>```

here is the code to set the background image

```<code>    background_image=Image.open('rain.jpg')
    canvas = tk.Canvas(rain_Frame, width=1025, height=522)
    canvas.grid()
    image1=ImageTk.PhotoImage(background_image)
    canvas.create_image(0,0, image=image1, anchor='center')
    label1=tk.Label(canvas,text='search by country/city')
    label1.grid(row=0,column=0)
    entry_1=tk.Entry(canvas)
    label_1.grid(row=0,column=0)
    entry_1.grid(row=0,column=20)
    search_button=tk.Button(canvas,text="search",
                      command=get_entry,
                width = 10, activebackground = "#33B5E5")

   search_button.grid(row=0,column=35,padx=10,pady=1,sticky='e')

   root.resizable(width=False, height=False)

   root.mainloop()
</code>```

here is what the outcome looks like
 Tkinter weather app

答:
Hmmm... why not use a bigger image? :D

Or stop the window resizing?

```<code>root = Tk()
root.resizable(0,0)
</code>```

For the labels, you could use a grid... or you could just place them somewhere and leave them?

```<code>label.place(x=20, y=380)
</code>```

Body:
I am trying to set the background image of weather app I tried to use canvas for that but the image doesn't expand as the window and it expands only when I click search to see the results , the labels come out messy as although I used grid

can someone help me to fix this please

here is the code

import requests
import pandas as pd
import json
import requests
import tkinter as tk
from PIL import Image, ImageTk
root=tk.Tk()
root.minsize(width=1025, height=522)
def get_entry(*args):
    api_address='http://api.openweathermap.org/data/2.5/weathe?appid=4f825a5771554e0c8fcccb7be76aab11&q='
    city=entry_1.get()
    url = api_address + city
    json_data = requests.get(url).json()
    format_add = json_data['weather'][0]['description']
    temp=json_data['main']['temp']
    press=json_data['main']['pressure']
    wind=json_data['wind']['speed']

displaying results through labels:

    label_2=tk.Label(canvas, text='the weather in '+city+' : '+format_add)
    label_3=tk.Label(canvas, text='the temperature :' +str(temp))
    label_4=tk.Label(canvas, text='the pressure:' +str(press))
    label_5=tk.Label(canvas, text='the wind speed:' +str(wind))
    label_2.grid(row=5,column=0,sticky='e',padx=20,pady=20)
    label_3.grid(row=6,column=0,sticky='e',padx=20,pady=20)
    label_4.grid(row=7,column=0,sticky='e',padx=20,pady=20)
    label_5.grid(row=8,column=0,sticky='e',padx=20,pady=20)
    Label = tk.Label(canvas, text =str(city), font = ('Comic Sans MS',30),
     fg = 'blue')
    Label.grid(row=4,column=630,sticky='n')
    rain_Frame=(root)
    rain_Frame.grid()

here is the code to set the background image

    background_image=Image.open('rain.jpg')
    canvas = tk.Canvas(rain_Frame, width=1025, height=522)
    canvas.grid()
    image1=ImageTk.PhotoImage(background_image)
    canvas.create_image(0,0, image=image1, anchor='center')
    label1=tk.Label(canvas,text='search by country/city')
    label1.grid(row=0,column=0)
    entry_1=tk.Entry(canvas)
    label_1.grid(row=0,column=0)
    entry_1.grid(row=0,column=20)
    search_button=tk.Button(canvas,text="search",
                      command=get_entry,
                width = 10, activebackground = "#33B5E5")

   search_button.grid(row=0,column=35,padx=10,pady=1,sticky='e')

   root.resizable(width=False, height=False)

   root.mainloop()

here is what the outcome looks like
 Tkinter weather app

Body:
Hmmm... why not use a bigger image? :D

Or stop the window resizing?

root = Tk()
root.resizable(0,0)

For the labels, you could use a grid... or you could just place them somewhere and leave them?

label.place(x=20, y=380)


问:
Fill requirements.txt from PyCharm virtual environment
I am trying to fill a requirements.txt for my PyCharm Django project that has a virtual environment. I am using the following when my virtual environment has been started:

```<code>pip freeze > requirements.txt
</code>```

This creates lots of entries as shown here but does not have entries for packages I have added such as djangorestframework, Django-crispy-forms etc.

What do I have to do to get all my packages listed? None of the packages installed within the virtual environment venv/lib/python 3.6/site-packages are listed in the requirements.txt

At the moment my requirements.txt looks like this:

altgraph==0.10.2
amqp==2.1.4
appdirs==1.4.3
awsebcli==3.10.0
backports.ssl-match-hostname==3.5.0.1
bdist-mpkg==0.5.0
billiard==3.5.0.2
blessed==1.14.1
bonjour-py==0.3
botocore==1.5.26
cement==2.8.2
click==6.7
colorama==0.3.7
coreapi==2.3.0
coreschema==0.0.4
defusedxml==0.4.1
django-appconf==1.0.2
dockerpty==0.4.1
funcsigs==1.0.2
futures==3.1.1
itypes==1.1.0
Jinja2==2.9.6
jmespath==0.9.2
kombu==4.0.2
macholib==1.5.1
MarkupSafe==1.0
matplotlib==1.3.1
modulegraph==0.10.4
numpy==1.8.0rc1
oauthlib==2.0.1
olefile==0.44
openapi-codec==1.3.1
packaging==16.8
pathspec==0.5.0
pbr==3.0.1
progressbar2==3.20.0
psycopg2==2.7.3.2
py2app==0.7.3
PyJWT==1.5.0
pyobjc-core==2.5.1
pyobjc-framework-Accounts==2.5.1
pyobjc-framework-AddressBook==2.5.1
pyobjc-framework-AppleScriptKit==2.5.1
pyobjc-framework-AppleScriptObjC==2.5.1
pyobjc-framework-Automator==2.5.1
pyobjc-framework-CFNetwork==2.5.1
pyobjc-framework-Cocoa==2.5.1
pyobjc-framework-Collaboration==2.5.1
pyobjc-framework-CoreData==2.5.1
pyobjc-framework-CoreLocation==2.5.1
pyobjc-framework-CoreText==2.5.1
pyobjc-framework-DictionaryServices==2.5.1
pyobjc-framework-EventKit==2.5.1
pyobjc-framework-ExceptionHandling==2.5.1
pyobjc-framework-FSEvents==2.5.1
pyobjc-framework-InputMethodKit==2.5.1
pyobjc-framework-InstallerPlugins==2.5.1
pyobjc-framework-InstantMessage==2.5.1
pyobjc-framework-LatentSemanticMapping==2.5.1
pyobjc-framework-LaunchServices==2.5.1
pyobjc-framework-Message==2.5.1
pyobjc-framework-OpenDirectory==2.5.1
pyobjc-framework-PreferencePanes==2.5.1
pyobjc-framework-PubSub==2.5.1
pyobjc-framework-QTKit==2.5.1
pyobjc-framework-Quartz==2.5.1
pyobjc-framework-ScreenSaver==2.5.1
pyobjc-framework-ScriptingBridge==2.5.1
pyobjc-framework-SearchKit==2.5.1
pyobjc-framework-ServiceManagement==2.5.1
pyobjc-framework-Social==2.5.1
pyobjc-framework-SyncServices==2.5.1
pyobjc-framework-SystemConfiguration==2.5.1
pyobjc-framework-WebKit==2.5.1
pyOpenSSL==0.13.1
pyparsing==2.2.0
python-dateutil==1.5
python-openid==2.2.5
pytz==2013.7
PyYAML==3.12
requests-oauthlib==0.8.0
scipy==0.13.0b1
semantic-version==2.5.0
simplejson==3.10.0
six==1.10.0
social-auth-app-django==1.2.0
social-auth-core==1.3.0
sqlparse==0.2.3
tabulate==0.7.5
termcolor==1.1.0
uritemplate==3.0.0
vboxapi==1.0
vine==1.1.3
virtualenv==15.1.0
wcwidth==0.1.7
websocket-client==0.40.0
xattr==0.6.4
zope.interface==4.1.1```

答:
EDIT:

Since the follow up in the comments, we have reached the conclusion that the virtual environment that @BillNoble created didn't have pip installed in it and that was what caused the problem.

By following this post: virtualenv does not include pip he was able to solve it.

I will leave my previous answer here because it is the answer to the initial phrasing of the question.

Pycharm Version 2017.2:

Go to: File > Settings > Project:  > Project interpreter

In there, hit the button with the cog symbol.

If you have a virtual environment, choose "add local" (3).

If you don't have a virtual environment, choose "create VirtualEnv" (4).

Add local: Navigate to your virtual environments folder and find your existing one. Then choose: path/to/venv /my_venv/bin/pythonX.X

Create VirtualEnv: Just give it a name and select the python version you want.

Go to Pycharm terminal and activate your virtual env (or restart pycharm).

(EDIT: added after Pycharm update) Pycharm Version 2017.3.3:

Go to: File > Settings > Project:  > Project interpreter

In there, hit the button with the cog symbol and choose "Add Local":

If you have a virtual environment, choose "Existing environment" (3).

If you don't have a virtual environment, choose "New environment" (4).

Existing environment: In the "Interpreter" tab, navigate to your virtual environments folder and find your existing one. Then choose: path/to/venv /my_venv/bin/pythonX.X

New environment: Define the location of the virtual environment in the "Location" tab (usually home/username/.virtualenvs/your_venv) and choose the base interpreter from the drop-down menu.

Go to Pycharm terminal and activate your virtual env (or restart pycharm).

Now install anything you need and when you do a pip freeze > requirements.txt you will get everything installed inside your virtual env.

Keep in mind that you don't need everything from your venv inside your requirement.txt. Most of the modules in there are dependencies of other modules (like Django) and the correct version of them will get installed if you try to install the depended package.

Body:
I am trying to fill a requirements.txt for my PyCharm Django project that has a virtual environment. I am using the following when my virtual environment has been started:

pip freeze > requirements.txt

This creates lots of entries as shown here but does not have entries for packages I have added such as djangorestframework, Django-crispy-forms etc.

What do I have to do to get all my packages listed? None of the packages installed within the virtual environment venv/lib/python 3.6/site-packages are listed in the requirements.txt

At the moment my requirements.txt looks like this:

altgraph==0.10.2
amqp==2.1.4
appdirs==1.4.3
awsebcli==3.10.0
backports.ssl-match-hostname==3.5.0.1
bdist-mpkg==0.5.0
billiard==3.5.0.2
blessed==1.14.1
bonjour-py==0.3
botocore==1.5.26
cement==2.8.2
click==6.7
colorama==0.3.7
coreapi==2.3.0
coreschema==0.0.4
defusedxml==0.4.1
django-appconf==1.0.2
dockerpty==0.4.1
funcsigs==1.0.2
futures==3.1.1
itypes==1.1.0
Jinja2==2.9.6
jmespath==0.9.2
kombu==4.0.2
macholib==1.5.1
MarkupSafe==1.0
matplotlib==1.3.1
modulegraph==0.10.4
numpy==1.8.0rc1
oauthlib==2.0.1
olefile==0.44
openapi-codec==1.3.1
packaging==16.8
pathspec==0.5.0
pbr==3.0.1
progressbar2==3.20.0
psycopg2==2.7.3.2
py2app==0.7.3
PyJWT==1.5.0
pyobjc-core==2.5.1
pyobjc-framework-Accounts==2.5.1
pyobjc-framework-AddressBook==2.5.1
pyobjc-framework-AppleScriptKit==2.5.1
pyobjc-framework-AppleScriptObjC==2.5.1
pyobjc-framework-Automator==2.5.1
pyobjc-framework-CFNetwork==2.5.1
pyobjc-framework-Cocoa==2.5.1
pyobjc-framework-Collaboration==2.5.1
pyobjc-framework-CoreData==2.5.1
pyobjc-framework-CoreLocation==2.5.1
pyobjc-framework-CoreText==2.5.1
pyobjc-framework-DictionaryServices==2.5.1
pyobjc-framework-EventKit==2.5.1
pyobjc-framework-ExceptionHandling==2.5.1
pyobjc-framework-FSEvents==2.5.1
pyobjc-framework-InputMethodKit==2.5.1
pyobjc-framework-InstallerPlugins==2.5.1
pyobjc-framework-InstantMessage==2.5.1
pyobjc-framework-LatentSemanticMapping==2.5.1
pyobjc-framework-LaunchServices==2.5.1
pyobjc-framework-Message==2.5.1
pyobjc-framework-OpenDirectory==2.5.1
pyobjc-framework-PreferencePanes==2.5.1
pyobjc-framework-PubSub==2.5.1
pyobjc-framework-QTKit==2.5.1
pyobjc-framework-Quartz==2.5.1
pyobjc-framework-ScreenSaver==2.5.1
pyobjc-framework-ScriptingBridge==2.5.1
pyobjc-framework-SearchKit==2.5.1
pyobjc-framework-ServiceManagement==2.5.1
pyobjc-framework-Social==2.5.1
pyobjc-framework-SyncServices==2.5.1
pyobjc-framework-SystemConfiguration==2.5.1
pyobjc-framework-WebKit==2.5.1
pyOpenSSL==0.13.1
pyparsing==2.2.0
python-dateutil==1.5
python-openid==2.2.5
pytz==2013.7
PyYAML==3.12
requests-oauthlib==0.8.0
scipy==0.13.0b1
semantic-version==2.5.0
simplejson==3.10.0
six==1.10.0
social-auth-app-django==1.2.0
social-auth-core==1.3.0
sqlparse==0.2.3
tabulate==0.7.5
termcolor==1.1.0
uritemplate==3.0.0
vboxapi==1.0
vine==1.1.3
virtualenv==15.1.0
wcwidth==0.1.7
websocket-client==0.40.0
xattr==0.6.4
zope.interface==4.1.1


问:
setLayoutParams overriding setGravity for layout
I have this section in my layout file:

```<code><RelativeLayout>
    <LinearLayout android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <TextView></TextView>
        <TextView></TextView>
    </LinearLayout>
</RelativeLayout>
</code>```

My objective is to set the gravity of the items inside the linearLayout and then to add a margin to the whole LinearLayout programmatically.

This is what I have:

```<code>linearLayout_textBackground.setGravity(gravity); //where gravity is the int of the desired gravity

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                   RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
linearLayout_textBackground.setLayoutParams(layoutParams);
linearLayout_textBackground.requestLayout();
</code>```

I would like to set the margin in using layoutParams but when I run the above code, I notice that my gravity value had been reset. However, if I comment out linearLayout_textBackground.setLayoutParams(layoutParams);, my gravity value are set correctly.

Why is the gravity resetting after I setLayoutParams to my layout?

答:
Thanks to @M.Saad Lakhan's answer, I noticed that I was creating a new reference of the parameters. So what I ended up doing is getting the actual params of the layout:

```<code>RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
                    linearLayout_textBackground.getLayoutParams();
</code>```

This fixed the problem.

Body:
I have this section in my layout file:

<RelativeLayout>
    <LinearLayout android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <TextView></TextView>
        <TextView></TextView>
    </LinearLayout>
</RelativeLayout>

My objective is to set the gravity of the items inside the linearLayout and then to add a margin to the whole LinearLayout programmatically.

This is what I have:

linearLayout_textBackground.setGravity(gravity); //where gravity is the int of the desired gravity

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                   RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
linearLayout_textBackground.setLayoutParams(layoutParams);
linearLayout_textBackground.requestLayout();

I would like to set the margin in using layoutParams but when I run the above code, I notice that my gravity value had been reset. However, if I comment out linearLayout_textBackground.setLayoutParams(layoutParams);, my gravity value are set correctly.

Why is the gravity resetting after I setLayoutParams to my layout?

Body:
Thanks to @M.Saad Lakhan's answer, I noticed that I was creating a new reference of the parameters. So what I ended up doing is getting the actual params of the layout:

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
                    linearLayout_textBackground.getLayoutParams();

This fixed the problem.


问:
Looks for patterns across different lines
I have a file like this (test.txt):

```<code>abc
12
34
def
56
abc
ghi
78
def
90
</code>```

And I would like to search the 78 which is enclosed by "abc\nghi" and "def". Currently, I know I can do this by:

```<code>cat test.txt | awk '/abc/,/def/' | awk '/ghi/,'/def/'
</code>```

Is there any better way?

答:
awk solution:

```<code>awk '/ghi/ && r=="abc"{ f=1; n=NR+1 }f && NR==n{ v=$0 }v && NR==n+1{ print v }{ r=$0 }' file
</code>```

The output:

```<code>78
</code>```

Bonus GNU awk approach:

```<code>awk -v RS= 'match($0,/\nabc\nghi\n(.+)\ndef/,a){ print a[1] }' file
</code>```

Body:
I have a file like this (test.txt):

abc
12
34
def
56
abc
ghi
78
def
90

And I would like to search the 78 which is enclosed by "abc\nghi" and "def". Currently, I know I can do this by:

cat test.txt | awk '/abc/,/def/' | awk '/ghi/,'/def/'

Is there any better way?

Body:
awk solution:

awk '/ghi/ && r=="abc"{ f=1; n=NR+1 }f && NR==n{ v=$0 }v && NR==n+1{ print v }{ r=$0 }' file

The output:

78

Bonus GNU awk approach:

awk -v RS= 'match($0,/\nabc\nghi\n(.+)\ndef/,a){ print a[1] }' file


答:
use GROUP BY ... HAVING

```<code>SELECT name
FROM table1
GROUP BY name
HAVING MAX(score) < 100
</code>```

Body:
use GROUP BY ... HAVING

SELECT name
FROM table1
GROUP BY name
HAVING MAX(score) < 100


问:
Value of tuple type '(key: String, value: AnyObject)' has no member 'subscript'
I get an error like this : Value of tuple type '(key: String, value: AnyObject)' has no member 'subscript'

I tried to search online but I don't understand, it always says something about changing it to an array of dictionaries but when I parse the data as [[String:AnyObject]] it gives me an error.

Error Screenshot

Here is my code for context

```<code>`//
//  MapViewViewController.swift
//  On the Map!
//
//  Created by Belal Elsiesy on 11/13/17.
//  Copyright © 2017 Elsiesy Industries. All rights reserved.
//

import UIKit

import MapKit

class MapViewViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var MapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        getLocations()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        let locations  = appDelegate.locationData
        var annotations = [MKPointAnnotation]()

        // When the array is complete, we add the annotations to the map.

        for location  in locations! {

            // Notice that the float values are being used to create CLLocationDegree values.
            // This is a version of the Double type.
            let lat = CLLocationDegrees(location["latitude"] as! Double)
            let long = CLLocationDegrees(location["longitude"] as! Double)

            // The lat and long are used to create a CLLocationCoordinates2D instance.
            let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)

            let first = location["firstName"] as! String
            let last = location["lastName"] as! String
            let mediaURL = location["mediaURL"] as! String

            // Here we create the annotation and set its coordiate, title, and subtitle properties
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate
            annotation.title = "\(first) \(last)"
            annotation.subtitle = mediaURL

            // Finally we place the annotation in an array of annotations.
            annotations.append(annotation)
        }
        // When the array is complete, we add the annotations to the map.
        self.MapView.addAnnotations(annotations)
    }
}

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
func getLocations() {

        var request = URLRequest(url: URL(string: "https://parse.udacity.com/parse/classes/StudentLocation")!)
        request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id")
        request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key")
        let session = URLSession.shared
        let task = session.dataTask(with: request) { data, response, error in
            if error != nil { // Handle error...
                ////////////////////////DO THIS LATER
            }
            print(String(data: data!, encoding: .utf8)!)
        let parsedResult: [String:AnyObject]!
            do {
                parsedResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as!  [String : AnyObject]

                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                appDelegate.locationData = parsedResult
            } catch {
                print("Could not parse the data as JSON: '\(data)'")

            }

        }
        task.resume()
    }

`
</code>```

答:
From Apple Documentation: You can iterate over the key-value pairs in a dictionary with a for-in loop. Each item in the dictionary is returned as a (key, value) tuple, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:

```<code>for (key, value) in dictionary {
    print(key)
    print(value)
}
</code>```

And pay attention to another issue with your code:
1) There is async code in function getLocation() and when you assign in viewDidLoad()

```<code>let locations  = appDelegate.locationData
</code>```

locations equal nil.

2) Swift 4 have useful features for parse JSON, research this. Now you get dictionary with only one key-value pair with key equal "result"

Body:
I get an error like this : Value of tuple type '(key: String, value: AnyObject)' has no member 'subscript'

I tried to search online but I don't understand, it always says something about changing it to an array of dictionaries but when I parse the data as [[String:AnyObject]] it gives me an error.

Error Screenshot

Here is my code for context

`//
//  MapViewViewController.swift
//  On the Map!
//
//  Created by Belal Elsiesy on 11/13/17.
//  Copyright © 2017 Elsiesy Industries. All rights reserved.
//

import UIKit

import MapKit

class MapViewViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var MapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        getLocations()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        let locations  = appDelegate.locationData
        var annotations = [MKPointAnnotation]()

        // When the array is complete, we add the annotations to the map.

        for location  in locations! {

            // Notice that the float values are being used to create CLLocationDegree values.
            // This is a version of the Double type.
            let lat = CLLocationDegrees(location["latitude"] as! Double)
            let long = CLLocationDegrees(location["longitude"] as! Double)

            // The lat and long are used to create a CLLocationCoordinates2D instance.
            let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)

            let first = location["firstName"] as! String
            let last = location["lastName"] as! String
            let mediaURL = location["mediaURL"] as! String

            // Here we create the annotation and set its coordiate, title, and subtitle properties
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate
            annotation.title = "\(first) \(last)"
            annotation.subtitle = mediaURL

            // Finally we place the annotation in an array of annotations.
            annotations.append(annotation)
        }
        // When the array is complete, we add the annotations to the map.
        self.MapView.addAnnotations(annotations)
    }
}

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
func getLocations() {

        var request = URLRequest(url: URL(string: "https://parse.udacity.com/parse/classes/StudentLocation")!)
        request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id")
        request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key")
        let session = URLSession.shared
        let task = session.dataTask(with: request) { data, response, error in
            if error != nil { // Handle error...
                ////////////////////////DO THIS LATER
            }
            print(String(data: data!, encoding: .utf8)!)
        let parsedResult: [String:AnyObject]!
            do {
                parsedResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as!  [String : AnyObject]

                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                appDelegate.locationData = parsedResult
            } catch {
                print("Could not parse the data as JSON: '\(data)'")

            }

        }
        task.resume()
    }

`

Body:
From Apple Documentation: You can iterate over the key-value pairs in a dictionary with a for-in loop. Each item in the dictionary is returned as a (key, value) tuple, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:

for (key, value) in dictionary {
    print(key)
    print(value)
}

And pay attention to another issue with your code:
1) There is async code in function getLocation() and when you assign in viewDidLoad()

let locations  = appDelegate.locationData

locations equal nil.

2) Swift 4 have useful features for parse JSON, research this. Now you get dictionary with only one key-value pair with key equal "result"


问:
file_get_content() : "No such file or directory" behind a proxy
I'm trying to fetch data from the Internet using PHP. Being at work, I'm behind a password protected proxy which seems to cause trouble.

I have consulted many posts on StackOverflow and several other platforms, each one giving me a different solution, none of which could fill my needs.

```<code>var_dump(stream_get_wrappers());

$opts = array("http" => ['proxy'=>'user:password@webproxy.xxx.intra:####',
                        'request_fulluri' => True]
        );

stream_context_set_default($opts);

$homepage = file_get_contents("www.google.com");
echo $homepage;
</code>```

I've added var_dump(stream_get_wrappers()); as advised in one of the posts I've previously read, returning : [https, ftps, compress.zlib, compress.bzip2, php, file, glob, data, http, ftp, phar, zip]

And the warning I get is the following :

PHP Warning: file_get_contents(www.google.com): failed to open stream: No such file
  or directory in /home/user/project/app/connector.php on line 15

Line 15 being $homepage = file_get_contents("www.google.com");

I've been stuck there for way too long, and any help is greatly appreciated.

Thank you.

EDIT : I have added "http://" to the beginning of the address, giving me this error :

PHP Warning: file_get_contents(google.com): failed to open stream:
  php_network_getaddresses: getaddrinfo failed: Name or service not
  known in /home/user/project/app/connector.php on line 15

For some reason this error got displayed twice, the second one being almost the same with less information.

答:
After searching even more, here is what I have come up with :

```<code>$auth = base64_encode('login:password');

$opts = array(
    'http' => array(
        'proxy' => 'tcp://proxy_host:proxy_port',
        'request_fulluri' => true,
        'header' => "Proxy-Authorization: Basic $auth",
    ),
);
$context = stream_context_create($opts);

$file = file_get_contents("http://www.google.com", False, $context);
echo $file;
</code>```

This seems to work fine.
Thanks for your help and advices.

Body:
I'm trying to fetch data from the Internet using PHP. Being at work, I'm behind a password protected proxy which seems to cause trouble.

I have consulted many posts on StackOverflow and several other platforms, each one giving me a different solution, none of which could fill my needs.

var_dump(stream_get_wrappers());

$opts = array("http" => ['proxy'=>'user:password@webproxy.xxx.intra:####',
                        'request_fulluri' => True]
        );

stream_context_set_default($opts);

$homepage = file_get_contents("www.google.com");
echo $homepage;

I've added var_dump(stream_get_wrappers()); as advised in one of the posts I've previously read, returning : [https, ftps, compress.zlib, compress.bzip2, php, file, glob, data, http, ftp, phar, zip]

And the warning I get is the following :

PHP Warning: file_get_contents(www.google.com): failed to open stream: No such file
  or directory in /home/user/project/app/connector.php on line 15

Line 15 being $homepage = file_get_contents("www.google.com");

I've been stuck there for way too long, and any help is greatly appreciated.

Thank you.

EDIT : I have added "http://" to the beginning of the address, giving me this error :

PHP Warning: file_get_contents(google.com): failed to open stream:
  php_network_getaddresses: getaddrinfo failed: Name or service not
  known in /home/user/project/app/connector.php on line 15

For some reason this error got displayed twice, the second one being almost the same with less information.

Body:
After searching even more, here is what I have come up with :

$auth = base64_encode('login:password');

$opts = array(
    'http' => array(
        'proxy' => 'tcp://proxy_host:proxy_port',
        'request_fulluri' => true,
        'header' => "Proxy-Authorization: Basic $auth",
    ),
);
$context = stream_context_create($opts);

$file = file_get_contents("http://www.google.com", False, $context);
echo $file;

This seems to work fine.
Thanks for your help and advices.


问:
Cassandra: Error: code=2200 [Invalid query] message="PRIMARY KEY column cannot be restricted as preceding column
Table Schema:

```<code>CREATE TABLE com (
    receiverid text,
    senderid text,
    commatriid text,
    comtype tinyint,
    comid text,
    displaystatus tinyint,
    comdate timestamp,
    cominfoid bigint,
    comstatus tinyint,
    dateactioned timestamp,
    datedeleted timestamp,
    dateread timestamp,
    dateupdated timestamp,
    disclosedmatriid tinyint,
    filteredmsg tinyint,
    message text,
    recentstatus tinyint,
    regionallang tinyint,
    transmsg text,
    PRIMARY KEY (receiverid, senderid, commatriid, comtype, comid, displaystatus, comdate)
) WITH CLUSTERING ORDER BY (senderid ASC, commatriid ASC, comtype ASC, comid ASC, displaystatus ASC, comdate ASC);
</code>```

Select query with where clause:

```<code>SELECT ComInfoId,ComId,ComType,SenderId,ReceiverId,ComMatriId,ComDate,ComStatus FROM com WHERE ComMatriId='M1'AND SenderId='M79984222' and ReceiverId='M2' and ComDate <= '2017-11-14 09:20:05+0000';
</code>```

ERROR:

InvalidRequest: Error from server: code=2200 [Invalid query]
  message="PRIMARY KEY column "comdate" cannot be restricted as
  preceding column "comtype" is not restricted"

what is primary key column restricted as proceding column?
if remove the comDate date in where clause ,i m able to retrive the data

答:
In C* the order of the primary key columns matter, and the data is stored in disk in a manner that only allows data be selected if the key before is also specified.

```<code>PRIMARY KEY (receiverid, senderid, commatriid,
             comtype, comid, displaystatus, comdate)
</code>```

The error you received means that if you want to query by comdate then you need to also query by ALL of the previous keys: receiverid, senderid, commatriid, comtype, comid, displaystatus.

If you want to query by comtype, then you need to specify ``receiverid, senderid, commatriid, comtype`.

Why do I have to specify the other keys?

This comes down to the way Cassandra was designed and it is like this for performance. Everything is stored in partitions and is stored in order on disk so that the database has to do minimal work. The downside is that you need to know what queries you will want to run when you design your schema.

Visualise the data on disk as an array (please excuse all of the columns equaling ints):

```<code>data =
receiverid(1)
    senderid(1)
        commatriid(1)
            comtype(1)
                comid(1)
                    displaystatus(1)
                        comdate(1)
                        comdate(2)
                        comdate(3)
    senderid(2)
        commatriid(1)
            comtype(1)
                comid(1)
                    displaystatus(1)
                        comdate(1)
                        comdate(2)
                        comdate(3)
</code>```

Take the following queries and my examples of accessing the data like Cassandra would.

WHERE receiverid IN (1, 2)

result = (data[1], data[2])

WHERE receiverid IN (1) AND senderid = 1

result = data[1][1]

WHERE receiverid IN (1) AND senderid = 1 AND comtype = 1

result = data[1][1][????][1]

This is where it gets interesting. I have deliberately missed out the commatriid field in my where clause. Now C* can narrow the results down to data[1][1] but which commatriid index should it look in to return the data? It doesn't know because I haven't specified it.

WHERE receiverid IN (1) AND senderid = 1 AND comtype = 1 AND commatriid = 1

result = data[1][1][1][1]

Now we have included commatriid we know which index to access for the data.

Body:
Table Schema:

CREATE TABLE com (
    receiverid text,
    senderid text,
    commatriid text,
    comtype tinyint,
    comid text,
    displaystatus tinyint,
    comdate timestamp,
    cominfoid bigint,
    comstatus tinyint,
    dateactioned timestamp,
    datedeleted timestamp,
    dateread timestamp,
    dateupdated timestamp,
    disclosedmatriid tinyint,
    filteredmsg tinyint,
    message text,
    recentstatus tinyint,
    regionallang tinyint,
    transmsg text,
    PRIMARY KEY (receiverid, senderid, commatriid, comtype, comid, displaystatus, comdate)
) WITH CLUSTERING ORDER BY (senderid ASC, commatriid ASC, comtype ASC, comid ASC, displaystatus ASC, comdate ASC);

Select query with where clause:

SELECT ComInfoId,ComId,ComType,SenderId,ReceiverId,ComMatriId,ComDate,ComStatus FROM com WHERE ComMatriId='M1'AND SenderId='M79984222' and ReceiverId='M2' and ComDate <= '2017-11-14 09:20:05+0000';

ERROR:

InvalidRequest: Error from server: code=2200 [Invalid query]
  message="PRIMARY KEY column "comdate" cannot be restricted as
  preceding column "comtype" is not restricted"

what is primary key column restricted as proceding column?
if remove the comDate date in where clause ,i m able to retrive the data

Body:
In C* the order of the primary key columns matter, and the data is stored in disk in a manner that only allows data be selected if the key before is also specified.

PRIMARY KEY (receiverid, senderid, commatriid,
             comtype, comid, displaystatus, comdate)

The error you received means that if you want to query by comdate then you need to also query by ALL of the previous keys: receiverid, senderid, commatriid, comtype, comid, displaystatus.

If you want to query by comtype, then you need to specify ``receiverid, senderid, commatriid, comtype`.

Why do I have to specify the other keys?

This comes down to the way Cassandra was designed and it is like this for performance. Everything is stored in partitions and is stored in order on disk so that the database has to do minimal work. The downside is that you need to know what queries you will want to run when you design your schema.

Visualise the data on disk as an array (please excuse all of the columns equaling ints):

data =
receiverid(1)
    senderid(1)
        commatriid(1)
            comtype(1)
                comid(1)
                    displaystatus(1)
                        comdate(1)
                        comdate(2)
                        comdate(3)
    senderid(2)
        commatriid(1)
            comtype(1)
                comid(1)
                    displaystatus(1)
                        comdate(1)
                        comdate(2)
                        comdate(3)

Take the following queries and my examples of accessing the data like Cassandra would.

WHERE receiverid IN (1, 2)

result = (data[1], data[2])

WHERE receiverid IN (1) AND senderid = 1

result = data[1][1]

WHERE receiverid IN (1) AND senderid = 1 AND comtype = 1

result = data[1][1][????][1]

This is where it gets interesting. I have deliberately missed out the commatriid field in my where clause. Now C* can narrow the results down to data[1][1] but which commatriid index should it look in to return the data? It doesn't know because I haven't specified it.

WHERE receiverid IN (1) AND senderid = 1 AND comtype = 1 AND commatriid = 1

result = data[1][1][1][1]

Now we have included commatriid we know which index to access for the data.


问:
Static data memory limit in C++ application
Someone has written function in our C++ application and is already in the production and I don't know why it's not crashing the application yet. Below is the code.

```<code>char *str_Modify()
{
    char buffer[70000] = { 0 };
    char targetString[70000] = { 0 };

    memset(targetString, '\0', sizeof(targetString));

    ...
    ...
    ...
    return targetString;
}
</code>```

As you can see, the function is returning the address of a local variable and the allocated memory will be released once the function returns.
My question

Wanted to know what is the static data memory limit?

What can be the quick fix for this code? Is it a good practice to make the variable targetString static?

答:
(Note that your call to memset has no effect, all the elements are zero-initialised prior to the call.)

It's not crashing the application since one manifestation of the undefined behaviour of your code (returning back a pointer to a now out-of-scope variable with automatic storage duration) is not crashing the application.

Yes, making it static does validate the pointer, but can create other issues centred around concurrent access.

And pick your language: In C++ there are other techniques.

Body:
Someone has written function in our C++ application and is already in the production and I don't know why it's not crashing the application yet. Below is the code.

char *str_Modify()
{
    char buffer[70000] = { 0 };
    char targetString[70000] = { 0 };

    memset(targetString, '\0', sizeof(targetString));

    ...
    ...
    ...
    return targetString;
}

As you can see, the function is returning the address of a local variable and the allocated memory will be released once the function returns.
My question

Wanted to know what is the static data memory limit?

What can be the quick fix for this code? Is it a good practice to make the variable targetString static?


问:
Access to separate pixel of JPEG image in Android
In my android project I need to get access for each separate pixel of JPEG image. Image created by built-in photo application. I try to convert JPEG into Bitmap class instance, but OutOfMemoryException was thrown. After searching info about this problem I have found the following solution: resize image! But quality of image is important in my project, and i can't resize it. Is there any way to get each-pixel access?

答:
The nature of jpeg makes it very hard to get the value of a single pixel. The main reason is that the data is not byte aligned, another is that everything is encoded in blocks that can be of sizes 8x16, 16x8 and 8x8. Also, you need to handle subsampling of chroma values.

If the image contains restart markers, maybe you can skip into the image so you don't have to decode the whole image before getting the pixel value.


问:
Angular 2 webpack bundle size
I am trying to reduce the size of my webpack bundles. The project is built around angular 2 & webpack.

Back in a day when I was using angular 2.0.0 ,the bundle size was about 2mb, which is fine.

But now, after updates to v4 and v5, bundle sizes are skyrocketed to >15mb.Even after Uglify/Babili-minify/Closure Compiler

Could anyone spot anything obvious or suggest ways to improve bundle size? (apart of mentioned glify/Babili-minify/Closure Compiler,because they are reducing the size only by 2-3mb...out of 20mb)

Webpack configs:
https://github.com/mcgri/NgMultiApp/blob/master/NgMultiApp/webpack.common.js
https://github.com/mcgri/NgMultiApp/blob/master/NgMultiApp/webpack.dev.js

Package.json
https://github.com/mcgri/NgMultiApp/blob/master/NgMultiApp/package.json

tsconfig:
https://github.com/mcgri/NgMultiApp/blob/master/NgMultiApp/tsconfig.json

thank you for your help

Update:
The webpack 2.3 used to generate large source maps and the main js files was about 3-4 mb. I wonder  if it because of webpack 3.8

答:
The problem was in --d option of webpack, which prevents sourcemaps generation.
After as I removed it, the source maps was generated and the bundle sizes was reduces from 20 mb to 3mb!

--d is a shortcut for:

```<code>--debug --devtool cheap-module-eval-source-map --output-pathinfo
</code>```

Title: Angular 2 webpack bundle size

Body:
The problem was in --d option of webpack, which prevents sourcemaps generation.
After as I removed it, the source maps was generated and the bundle sizes was reduces from 20 mb to 3mb!

--d is a shortcut for:

--debug --devtool cheap-module-eval-source-map --output-pathinfo


问:
VBA for Excel sheets
I have an excel sheet in which records of employee's and their various earnings and deductions like below:

```<code>Emp Name    Earning Code    Earning    Deduction Code    Deductions
John        Regular         5000       PF                500
John        Overtime        750        income Tax        250
John        Bonus           750        Loan 1            250
John                                   Loan 2            250
Peter       Regular         6000       PF                600
Peter       Overtime        850        income Tax        250
Peter       Bonus           650        Loan 1            250
Peter                                  Loan 2            250
</code>```

I need to make another sheet in the same Excel with following format:

```<code>Employee Name    Total Earning    Total Deduction    Net Income
John             6500             1250               5250
Peter            7500             1350               6150
</code>```

I am not that strong in Excel, so I am seeking any kind of help in achieving this objective. Any help would be highly appreciated!!

Thanks!

答:
For a pure excel solution you can use Subtotal in Data Tab.

Select all your data. Go to Data Tab and click on subtotal.

Select your earning and Deduction column from checkbox like this

To copy only the subtotals collapse the level 2 on clicking

Select the data. Press F5 select Visible cells only from the dialog.

Press Ctrl+C

Go to your target to paste and do Ctrl+V in new sheet in your case.

Title: VBA for Excel sheets

Body:
I have an excel sheet in which records of employee's and their various earnings and deductions like below:

Emp Name    Earning Code    Earning    Deduction Code    Deductions
John        Regular         5000       PF                500
John        Overtime        750        income Tax        250
John        Bonus           750        Loan 1            250
John                                   Loan 2            250
Peter       Regular         6000       PF                600
Peter       Overtime        850        income Tax        250
Peter       Bonus           650        Loan 1            250
Peter                                  Loan 2            250

I need to make another sheet in the same Excel with following format:

Employee Name    Total Earning    Total Deduction    Net Income
John             6500             1250               5250
Peter            7500             1350               6150

I am not that strong in Excel, so I am seeking any kind of help in achieving this objective. Any help would be highly appreciated!!

Thanks!


问:
array of DBObject with same keys each element
I am trying to create an array of DBObject, all of the elements have the same key with different values.
what is the problem with this implementation ? </p>

```<code> DBObject[] Out = new BasicDBObject[2];

 out[0].put("VALUE","1");
 out[0].put("PROPERTY","1");

 out[1].put("VALUE","2");
 out[1].put("PROPERTY","2");
</code>```

答:
You are only creating array of references. You need to create objects for it before assigning values.</p>

```<code>DBObject[] Out = new BasicDBObject[2];

// instantiating objects for the array
for(int i=0 ; i < Out.length ; i++){
    Out[i] = new BasicDBObject();
}

Out[0].put("VALUE","1");
Out[0].put("PROPERTY","1");
Out[1].put("VALUE","2");
Out[1].put("PROPERTY","2");
</code>```

Body:
I am trying to create an array of DBObject, all of the elements have the same key with different values.
what is the problem with this implementation ?

 DBObject[] Out = new BasicDBObject[2];

 out[0].put("VALUE","1");
 out[0].put("PROPERTY","1");

 out[1].put("VALUE","2");
 out[1].put("PROPERTY","2");

Body:
You are only creating array of references. You need to create objects for it before assigning values.

DBObject[] Out = new BasicDBObject[2];

// instantiating objects for the array
for(int i=0 ; i < Out.length ; i++){
    Out[i] = new BasicDBObject();
}

Out[0].put("VALUE","1");
Out[0].put("PROPERTY","1");
Out[1].put("VALUE","2");
Out[1].put("PROPERTY","2");


答:
Try This, here the table name is tblScore

```<code>select name,max(score) max_score from tblScore group by name
having max(score)<100
</code>```

The result is

```<code>|name   | max_score|
....................
|kumble | 77
|prasad | 12
</code>```

Body:
My Data is like this. So, I want to see the list of Players who never scored a Century in their entire career.
Sample Data

Body:
Try This, here the table name is tblScore

select name,max(score) max_score from tblScore group by name
having max(score)<100

The result is

|name   | max_score|
....................
|kumble | 77
|prasad | 12


问:
how to clear console data without refreshing the page in chrome
I am reading an ebook, which is about ReactJs,I want to run commands in the same page console but if redeclare the same variable it showing me variable has already been declared

for ex:-

```<code>var pizza = true
pizza = false
console.log(pizza)
</code>```

when i declarce const it show's me

```<code>const pizza = true
pizza = false
</code>```

error:-

Uncaught SyntaxError: Identifier 'pizza' has already been declared

I searched and used these commands but it is not working

```<code>CLTRL + L
</code>```

console.clear();

```<code>window.clear = clear

clear()
</code>```

Can anyone can tell me how to refresh console without refreshing the page

答:
Constants are read-only, therefore the value of a constant cannot change through re-assignment, and it can't be redeclared.

For more details refer this link

Body:
I am reading an ebook, which is about ReactJs,I want to run commands in the same page console but if redeclare the same variable it showing me variable has already been declared

for ex:-

var pizza = true
pizza = false
console.log(pizza)

when i declarce const it show's me

const pizza = true
pizza = false

error:-

Uncaught SyntaxError: Identifier 'pizza' has already been declared

I searched and used these commands but it is not working

CLTRL + L

console.clear();

window.clear = clear

clear()

Can anyone can tell me how to refresh console without refreshing the page


问:
Need help on volume mount issue with kubernetes
I have RBAC enabled kubernetes cluster created using
kops version 1.8.0-beta.1, I am trying to run a nginx pod which should attach pre-created EBS volume and pod should start. But getting issue as not authorized even though i am a admin user. Any help would be highly appreciated.

```<code>kubectl version Client Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-09T07:27:47Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-08T18:27:48Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}

namespace:default
</code>```

cat test-ebs.yml

```<code>apiVersion: v1
kind: Pod
metadata:
  name: test-ebs
spec:
  containers:
  - image: nginx
    name: nginx
    volumeMounts:
    - mountPath: /test-ebs
      name: test-volume
  volumes:
  - name: test-volume
    awsElasticBlockStore:
      volumeID: <vol-IDhere>
      fsType: ext4
</code>```

I am getting the below error:

```<code>Warning  FailedMount            8m               attachdetach                                        AttachVolume.Attach failed for volume "test-volume" : Error attaching EBS volume "<vol-ID>" to instance "<i-instanceID>": "UnauthorizedOperation: You are not authorized to perform this operation
</code>```

答: Issue is because of kops1.8 version. Rolled back to kops version v1.7.1. its working now.</p>

Body:
I have RBAC enabled kubernetes cluster created using
kops version 1.8.0-beta.1, I am trying to run a nginx pod which should attach pre-created EBS volume and pod should start. But getting issue as not authorized even though i am a admin user. Any help would be highly appreciated.

kubectl version Client Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-09T07:27:47Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-08T18:27:48Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}

namespace:default

cat test-ebs.yml

apiVersion: v1
kind: Pod
metadata:
  name: test-ebs
spec:
  containers:
  - image: nginx
    name: nginx
    volumeMounts:
    - mountPath: /test-ebs
      name: test-volume
  volumes:
  - name: test-volume
    awsElasticBlockStore:
      volumeID: <vol-IDhere>
      fsType: ext4

I am getting the below error:

Warning  FailedMount            8m               attachdetach                                        AttachVolume.Attach failed for volume "test-volume" : Error attaching EBS volume "<vol-ID>" to instance "": "UnauthorizedOperation: You are not authorized to perform this operation


问:
How to get a folder's creator in SharePoint 2010 programmatically
I'm building a web part for SharePoint 2010 and I would like to know how to get the user that created a certain folder (SPFolder). I was able to get the doc libs creator, web, etc, but I had no luck with folders.

Any help will be appreciated.

答:
Try the Item property.</p>

```<code>SPFieldUserValue createdBy =
    new SPFieldUserValue(web, folder.Item[SPBuiltInFieldId.Author].ToString());
</code>```

Body:
Try the Item property.

SPFieldUserValue createdBy =
    new SPFieldUserValue(web, folder.Item[SPBuiltInFieldId.Author].ToString());