问:
Can't login through Django's Admin page
I have already created a custom user model for profiling and Authentication, however it doesn't seem to authenticate the password. I tried numerous times on changing it and even confirmed it on shell but it still doesn't go through on Django Admin.

Here is my models.py:

```<code>from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

# Create your models here.

class UserManager(BaseUserManager):
    def create_user(self, email, password=None, user_type=None, is_superuser=False, is_pqa=False, is_staff=False, is_admin=False, is_test_lead=False, is_test_manager=False, is_active=True):
        if not email:
            raise ValueError("User must have an email address!")
        if not password:
            raise ValueError("User must have a password!")
        user_obj = self.model(
            email=self.normalize_email(email)
        )
        user_obj.set_password(password)
        user_obj.user_type = user_type
        user_obj.ad = is_admin
        user_obj.superuser = is_superuser
        user_obj.tm = is_test_manager
        user_obj.pqa = is_pqa
        user_obj.tl = is_test_lead
        user_obj.active = is_active
        user_obj.save(using=self._db)
        return user_obj

    def create_pqa(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_pqa=True,
            is_staff=True,
            user_type=1
        )
        return user

    def create_staff(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_staff=True,
            user_type=2
        )
        return user

    def create_test_lead(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_test_lead=True,
            is_staff=True,
            user_type=3
        )
        return user

    def create_test_manager(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_test_manager=True,
            is_staff=True,
            user_type=4
        )
        return user

    def create_superuser(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_admin=True,
            is_superuser=True,
            is_staff=True,
            user_type=5
        )
        return user

class User(AbstractBaseUser):
    USER_TYPE_CHOICES = (
        (1, 'pqa'),
        (2, 'tester'),
        (3, 'test_lead'),
        (4, 'test_manager'),
        (5, 'admin'),
    )
    email = models.EmailField(max_length=255, unique=True)
    full_name = models.CharField(max_length=255, blank=True, null=True)
    active = models.BooleanField(default=True)
    birth_date = models.DateField(null=True, blank=True)
    hire_date = models.DateField(null=True, blank=True)
    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)
    ad = models.BooleanField(default=False)  # superuser/admin
    # non-superuser but with Team Manager Privilages
    tm = models.BooleanField(default=False)
    # non-superuser but with PQA Privilages
    pqa = models.BooleanField(default=False)
    ts = models.BooleanField(default=False)  # non-superuser
    # non-superuser but with TL Privilages
    tl = models.BooleanField(default=False)
    superuser = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.full_name

    def get_full_name(self):
        return self.full_name

    def get_short_name(self):
        return self.full_name

    @property
    def is_pqa(self):
        return self.pqa

    @property
    def is_staff(self):
        return self.ts

    @property
    def is_test_lead(self):
        return self.tl

    @property
    def is_test_manager(self):
        return self.tm

    @property
    def is_admin(self):
        return self.ad

    @property
    def is_active(self):
        return self.active

    @property
    def is_superuser(self):
        return self.superuser
</code>```

And here is my settings.py:

```<code>"""
Django settings for ceres project.

Generated by 'django-admin startproject' using Django 3.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@3xm&$=ky!sq2_i$-9cd%48ork1l$1y-+e__g_4d!+3*2ssli-'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'profiles.apps.ProfilesConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

AUTH_USER_MODEL = 'profiles.User'  # Custom model

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ceres.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ceres.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
</code>```

I really would appreciate if someone would point me at the right direction for this, since I'm at a loss. Thanks in advance!

答:
Welcome to StackOverFlow!

Possible Steps:

1) Check your superuser from command line. Mozilla MDN Docs are an incredible resource: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Admin_site (Go to "Creating a SuperUser" heading)

2) Maybe it's a configuration thing?

Check out this article by testdriven.io. They do go over creating a custom User Model from the beginning but I think you'll find it helpful even though they're working with email and usernames as they go through all the necessary configurations to get the customizations to show correctly (their "Conclusion" part looks amazing!).

You might find it more helpful to skip to "User Model" since it talks about the AbstractUser right after.

3) Again, Django docs are great! https://docs.djangoproject.com/en/3.0/topics/auth/customizing/

Title: Can't login through Django's Admin page

Body:
I have already created a custom user model for profiling and Authentication, however it doesn't seem to authenticate the password. I tried numerous times on changing it and even confirmed it on shell but it still doesn't go through on Django Admin.

Here is my models.py:

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

# Create your models here.

class UserManager(BaseUserManager):
    def create_user(self, email, password=None, user_type=None, is_superuser=False, is_pqa=False, is_staff=False, is_admin=False, is_test_lead=False, is_test_manager=False, is_active=True):
        if not email:
            raise ValueError("User must have an email address!")
        if not password:
            raise ValueError("User must have a password!")
        user_obj = self.model(
            email=self.normalize_email(email)
        )
        user_obj.set_password(password)
        user_obj.user_type = user_type
        user_obj.ad = is_admin
        user_obj.superuser = is_superuser
        user_obj.tm = is_test_manager
        user_obj.pqa = is_pqa
        user_obj.tl = is_test_lead
        user_obj.active = is_active
        user_obj.save(using=self._db)
        return user_obj

    def create_pqa(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_pqa=True,
            is_staff=True,
            user_type=1
        )
        return user

    def create_staff(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_staff=True,
            user_type=2
        )
        return user

    def create_test_lead(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_test_lead=True,
            is_staff=True,
            user_type=3
        )
        return user

    def create_test_manager(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_test_manager=True,
            is_staff=True,
            user_type=4
        )
        return user

    def create_superuser(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_admin=True,
            is_superuser=True,
            is_staff=True,
            user_type=5
        )
        return user

class User(AbstractBaseUser):
    USER_TYPE_CHOICES = (
        (1, 'pqa'),
        (2, 'tester'),
        (3, 'test_lead'),
        (4, 'test_manager'),
        (5, 'admin'),
    )
    email = models.EmailField(max_length=255, unique=True)
    full_name = models.CharField(max_length=255, blank=True, null=True)
    active = models.BooleanField(default=True)
    birth_date = models.DateField(null=True, blank=True)
    hire_date = models.DateField(null=True, blank=True)
    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)
    ad = models.BooleanField(default=False)  # superuser/admin
    # non-superuser but with Team Manager Privilages
    tm = models.BooleanField(default=False)
    # non-superuser but with PQA Privilages
    pqa = models.BooleanField(default=False)
    ts = models.BooleanField(default=False)  # non-superuser
    # non-superuser but with TL Privilages
    tl = models.BooleanField(default=False)
    superuser = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.full_name

    def get_full_name(self):
        return self.full_name

    def get_short_name(self):
        return self.full_name

    @property
    def is_pqa(self):
        return self.pqa

    @property
    def is_staff(self):
        return self.ts

    @property
    def is_test_lead(self):
        return self.tl

    @property
    def is_test_manager(self):
        return self.tm

    @property
    def is_admin(self):
        return self.ad

    @property
    def is_active(self):
        return self.active

    @property
    def is_superuser(self):
        return self.superuser

And here is my settings.py:

"""
Django settings for ceres project.

Generated by 'django-admin startproject' using Django 3.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@3xm&$=ky!sq2_i$-9cd%48ork1l$1y-+e__g_4d!+3*2ssli-'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'profiles.apps.ProfilesConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

AUTH_USER_MODEL = 'profiles.User'  # Custom model

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ceres.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ceres.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

I really would appreciate if someone would point me at the right direction for this, since I'm at a loss. Thanks in advance!


来源: stackexchange

问:
Update field in SQL on particular line matching search syntax
I have a table in SQLite3 called MachineData with the following headers:

ResourceId (Primary Key)

MachineName

PrimaryUser

The table has the ResourceId populated and I need to do a lookup against the ResourceId and inject data along the row.

I have tried the following statements, but it doesn't like my syntax. Any help would be appreciated?

INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE ResourceId LIKE '1001'
```

<p>and also</p>

```INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE (SELECT ResourceId FROM MachineData LIKE '1001')
```

<p>and also</p>

```INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE ResourceId EQUALS '1001'
```

<p>None of these have decided to play nice, always giving me logic error.</p>

<p>The table looks like this:</p>

<p><code>TABLENAME: MachineData</code></p>

```| ResourceId | MachineName | PrimaryUser |
|============|=============|=============|
| 1001       |             |             |
| 1002       |             |             |
| 1003       |             |             |
```

<p>I want to make it look like this:</p>

```| ResourceId | MachineName  | PrimaryUser  |
|============|==============|==============|
| 1001       |              | Mickey Mouse |
| 1002       |              |              |
| 1003       |              |              |
```

答:
What you have tried was to insert a line which is already in the table. That's why you are getting the error. If the primary key already exists in the given table, you cant use INSERT keyword. Use UPDATE query as below.

```<code>UPDATE MachineData SET PrimaryUser = 'Mickey Mouse' WHERE ResourceId LIKE '1001'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a table in SQLite3 called MachineData with the following headers:

ResourceId (Primary Key)

MachineName

PrimaryUser

The table has the ResourceId populated and I need to do a lookup against the ResourceId and inject data along the row.

I have tried the following statements, but it doesn't like my syntax. Any help would be appreciated?

INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE ResourceId LIKE '1001'

and also

INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE (SELECT ResourceId FROM MachineData LIKE '1001')

and also

INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE ResourceId EQUALS '1001'

None of these have decided to play nice, always giving me logic error.

The table looks like this:

TABLENAME: MachineData

| ResourceId | MachineName | PrimaryUser |
|============|=============|=============|
| 1001       |             |             |
| 1002       |             |             |
| 1003       |             |             |

I want to make it look like this:

| ResourceId | MachineName  | PrimaryUser  |
|============|==============|==============|
| 1001       |              | Mickey Mouse |
| 1002       |              |              |
| 1003       |              |              |

Body:
What you have tried was to insert a line which is already in the table. That's why you are getting the error. If the primary key already exists in the given table, you cant use INSERT keyword. Use UPDATE query as below.

UPDATE MachineData SET PrimaryUser = 'Mickey Mouse' WHERE ResourceId LIKE '1001'


问:
I loop over 4 objects and render their images while applying a class based on the truthness of a property but sometimes the DOM doesn't rerender
I loop over 4 objects and render their images while applying a class based on the truthness of a property BUT sometimes the DOM doesn't update/rerender with the right classes even though the object's property value has changed from true to false or vice-versa and I have no idea why is this happening.

Let me explain what exactly is happening. I render 4 images with class card-image and the active image gets an extra class active. I've binded a on-click function to each image so that when the user clicks the image, that image becomes the active one and the previous active image becomes inactive. This works to a certain degree, however, if I start clicking the images in a certain order, the DOM stops getting rendered with the correct classes on the correct image. For example:

Image 1 is active by default. If I click image 3, image 3 gets the active class. Then if I click image 1 again, image 3 losses the active tag and image 1 receives the active class

However in the following scenario, something goes wrong:

Image 1 is active by default. If I click image 3, image 3 gets the active class. Then if I click image 2 or image 4, image 3 doesn't lose its active class and image 2 or 4 don't get the active class EVEN THOUGH the console shows that image 3 property active has become false and image 2/4 property active has become true.

I've included a gif that showcases what happens: https://gyazo.com/81e1c89fffc6c84d8ffead751a223b01.

```<code><div v-for='card in associatedCards'>
    <div class="card-image" :class='{ active: card.active }' @click='makeCardActive(card)'>
        <img :src='"../assets/cards/" + card.cardCode + ".webp"'>
    </div>
</div>

<script>
    import cards from '../assets/json/set1-en_us.json'

    export default {
        data(){
            return {
                cardCode: this.$route.params.cardCode,
                cards: cards,
                card: null,
                associatedCards: null
            }
        },
        methods: {
            makeCardActive(card){
                this.activeCard.active = false
                card.active = true
                console.log(this.associatedCards)
            }
        },
        computed: {
            activeCard(){
                return this.associatedCards.find((card) => {
                    return card.active == true
                })
            }
        },
        mounted(){
            this.card = this.cards.find((card) => {
                return card.cardCode == this.cardCode
            })

            let associatedCards = this.cards.filter((card) => {
                return this.card.associatedCardRefs.includes(card.cardCode)
            })

            let combinedArray = [{...this.card}, ...associatedCards]

            combinedArray.map((card) => {
                card.active = false
            })

            combinedArray[0].active = true

            this.associatedCards = combinedArray
        }
    }
</script>
</code>```

答:
I think there is some delay in the code, to be safe just make all cards to false then set the active card to true</p>

```<code>            makeCardActive(card){
                this.associatedCards =
                this.associatedCards.map(aC => {
                    aC.active = false;
                    return aC;
                 });
                this.activeCard.active = false
                card.active = true
                console.log(this.associatedCards)
            }
        },

</code>```

Body:
I think there is some delay in the code, to be safe just make all cards to false then set the active card to true

            makeCardActive(card){
                this.associatedCards =
                this.associatedCards.map(aC => {
                    aC.active = false;
                    return aC;
                 });
                this.activeCard.active = false
                card.active = true
                console.log(this.associatedCards)
            }
        },


问:
ngx-datatable selecting both a row and a checkbox
So I have need to support both checkbox selection per row as well as selecting the row itself.
the problem is when I support checkbox selection I am not longer notified when a row is selected.
here is the code:

```<code><ngx-datatable #table class="material dark"
               style="width: 90%"
               [rows]="rows"
               [columnMode]="'force'"
               [headerHeight]="50"
               [columns]="columns"
               [footerHeight]="50"
               rowHeight="auto"
               [limit]="50"
               [selected]="selected"
               [selectionType]="'checkbox'"
               [selectAllRowsOnPage]="false"
               [displayCheck]="displayCheck"
               (activate)="onActivate($event)"
               (onClick )="onClick($event)">
</code>```

Now I am able to get both selection, per row and per checkbox since I added the (onClick), the problem is that I don't get the data object selected since onClick no longer get me any useful $event information (it has Input x y etc...)

Basically all I am trying to do is support both chebox selection (which works fine now) but at the same time support row selection and get the Object of the row of the selected row item when (onClick) is fired.

Thanks

Sean

答:
I am achieving row selection on click and from checkbox by this.
It was just first attempt and I didn't tried to improve it so just deal with it.
The only trade off it has is that once a  row is selected it cannot be deselected. the only way is to select all and deselect all from header checkbox.
I hope this will help.

```<code><ngx-datatable
style="height:100%;"
class="material"
[rows]="rows"
columnMode="force"
[headerHeight]="40"
[loadingIndicator]="true"
[rowHeight]="50"
[trackByProp]="_id"
[rowIdentity]="rowIdentity"
[footerHeight]="50"
[scrollbarV]="true"
[scrollbarH]="true"
[virtualization]="true"
[rowClass]="getRowClass"
[selected]="checkboxedSkus"
[selectionType]="SelectionType.multi"
[selectAllRowsOnPage]="false"
(activate)="onActivate($event)"
(select)="selectListener($event)">

<ngx-datatable-column [width]="40" [sortable]="false" [canAutoResize]="false" [frozenLeft]="true"
  [headerCheckboxable]="true" [cellClass]="getCheckboxClass">
  <ng-template ngx-datatable-header-template let-value="value" let-allRowsSelected="allRowsSelected"
    let-selectFn="selectFn">
    <label class="checkbox-container">
      <input type="checkbox" class="ngx-datatable-checkbox" [checked]="allRowsSelected"
        (change)="selectFn(!allRowsSelected)" />
      <span class="checkmark header-checkmark"></span>
    </label>
  </ng-template>
  <ng-template ngx-datatable-cell-template let-value="value" let-isSelected="isSelected"
    let-onCheckboxChangeFn="onCheckboxChangeFn">
    <label class="checkbox-container">
      <input type="checkbox" class="ngx-datatable-checkbox" [checked]="isSelected"
        (change)="onCheckboxChangeFn($event)" />
      <span class="checkmark"></span>
    </label>
  </ng-template>
</ngx-datatable-column>

<ng-container *ngFor="let col of columns">
  <ng-container *ngIf="(col.prop === 'name') || (col.name === 'Status') ; else elseTemplate">
    <ngx-datatable-column [name]="col.name" [headerClass]="getHeaderClass" [cellClass]="getCellClass"
      [frozenLeft]="true" [prop]="col.prop"></ngx-datatable-column>
  </ng-container>
  <ng-container>
    <ng-template #elseTemplate>
      <ngx-datatable-column [name]="col.name" [headerClass]="getHeaderClass" [prop]="col.prop">
      </ngx-datatable-column>
    </ng-template>
  </ng-container>
</ng-container>
</code>```

Body:
So I have need to support both checkbox selection per row as well as selecting the row itself.
the problem is when I support checkbox selection I am not longer notified when a row is selected.
here is the code:

<ngx-datatable #table class="material dark"
               style="width: 90%"
               [rows]="rows"
               [columnMode]="'force'"
               [headerHeight]="50"
               [columns]="columns"
               [footerHeight]="50"
               rowHeight="auto"
               [limit]="50"
               [selected]="selected"
               [selectionType]="'checkbox'"
               [selectAllRowsOnPage]="false"
               [displayCheck]="displayCheck"
               (activate)="onActivate($event)"
               (onClick )="onClick($event)">

Now I am able to get both selection, per row and per checkbox since I added the (onClick), the problem is that I don't get the data object selected since onClick no longer get me any useful $event information (it has Input x y etc...)

Basically all I am trying to do is support both chebox selection (which works fine now) but at the same time support row selection and get the Object of the row of the selected row item when (onClick) is fired.

Thanks

Sean

Body:
I am achieving row selection on click and from checkbox by this.
It was just first attempt and I didn't tried to improve it so just deal with it.
The only trade off it has is that once a  row is selected it cannot be deselected. the only way is to select all and deselect all from header checkbox.
I hope this will help.

<ngx-datatable
style="height:100%;"
class="material"
[rows]="rows"
columnMode="force"
[headerHeight]="40"
[loadingIndicator]="true"
[rowHeight]="50"
[trackByProp]="_id"
[rowIdentity]="rowIdentity"
[footerHeight]="50"
[scrollbarV]="true"
[scrollbarH]="true"
[virtualization]="true"
[rowClass]="getRowClass"
[selected]="checkboxedSkus"
[selectionType]="SelectionType.multi"
[selectAllRowsOnPage]="false"
(activate)="onActivate($event)"
(select)="selectListener($event)">

<ngx-datatable-column [width]="40" [sortable]="false" [canAutoResize]="false" [frozenLeft]="true"
  [headerCheckboxable]="true" [cellClass]="getCheckboxClass">
  <ng-template ngx-datatable-header-template let-value="value" let-allRowsSelected="allRowsSelected"
    let-selectFn="selectFn">
    <label class="checkbox-container">
      <input type="checkbox" class="ngx-datatable-checkbox" [checked]="allRowsSelected"
        (change)="selectFn(!allRowsSelected)" />
      <span class="checkmark header-checkmark"></span>
    </label>
  </ng-template>
  <ng-template ngx-datatable-cell-template let-value="value" let-isSelected="isSelected"
    let-onCheckboxChangeFn="onCheckboxChangeFn">
    <label class="checkbox-container">
      <input type="checkbox" class="ngx-datatable-checkbox" [checked]="isSelected"
        (change)="onCheckboxChangeFn($event)" />
      <span class="checkmark"></span>
    </label>
  </ng-template>
</ngx-datatable-column>

<ng-container *ngFor="let col of columns">
  <ng-container *ngIf="(col.prop === 'name') || (col.name === 'Status') ; else elseTemplate">
    <ngx-datatable-column [name]="col.name" [headerClass]="getHeaderClass" [cellClass]="getCellClass"
      [frozenLeft]="true" [prop]="col.prop"></ngx-datatable-column>
  </ng-container>
  <ng-container>
    <ng-template #elseTemplate>
      <ngx-datatable-column [name]="col.name" [headerClass]="getHeaderClass" [prop]="col.prop">
      </ngx-datatable-column>
    </ng-template>
  </ng-container>
</ng-container>


问:
Docker Images Are Being Slow to Build on Windows/MVC Core
I have a MVC Core 2.2 with multiple projects in docker containers. When I run it, it takes approximately 4 minutes to build the images and fire up the containers. I am using docker-compose.

This seems slow, given that this is small development and I have a decent computer. It seems that the resources are not being used, because processor is under 8% during image build, ram doesn't budge, disk almost at 0%. GPU 0%. I can see internet spiking for a few seconds while Microsoft image is downloaded, but that's it. I have given docker the following resources:

```<code>Cores: 8
RAM: 8GB
SWAP: 3gb
Disk Image Size: 64GB (30.5 GB used)
</code>```

Any ideas how these hardware resources can be used to make builds faster?

答:
check if there are too many files in the build directory , if there is dcoker need to send all the files to the daemon which need also time to finish......

you can ignore the unwanted files using .dockerignore

Before the docker CLI sends the context to the docker daemon, it looks
  for a file named .dockerignore in the root directory of the context.
  If this file exists, the CLI modifies the context to exclude files and
  directories that match patterns in it. This helps to avoid
  unnecessarily sending large or sensitive files and directories to the
  daemon and potentially adding them to images using ADD or COPY.

Body:
I have a MVC Core 2.2 with multiple projects in docker containers. When I run it, it takes approximately 4 minutes to build the images and fire up the containers. I am using docker-compose.

This seems slow, given that this is small development and I have a decent computer. It seems that the resources are not being used, because processor is under 8% during image build, ram doesn't budge, disk almost at 0%. GPU 0%. I can see internet spiking for a few seconds while Microsoft image is downloaded, but that's it. I have given docker the following resources:

Cores: 8
RAM: 8GB
SWAP: 3gb
Disk Image Size: 64GB (30.5 GB used)

Any ideas how these hardware resources can be used to make builds faster?


问:
How do I make a string bold in a console window?
So I'm trying to find a simple code that makes my code get printed in bold. When I searched the internet all of them were so complicated that it wasn't even worth it. Is there any easier way to make a string or just a Console.WriteLine(" "); bold? </p>

```<code>Console.Write("Type in the number of people to create: ");
int time = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nGenerating " + time + " people please stand by...");
System.Threading.Thread.Sleep(3000);
Console.Clear();
</code>```

答:
You can use the ANSII escape codes, as long as your console supports it.

You can do basics like, color text, background and bold,underline and reverse colors.
for example in c#

Console.WriteLine("\x1b[1mTEST\x1b[0m");
```

will print it in bold. \x1b[0m at the end is used to reset the formatting, many formatting options are made by changing the number after the bracket.

look into these links, I have used it with C and Python in bash, but I'm not sure about C# at the moment.

https://www.jerriepelser.com/blog/using-ansi-color-codes-in-net-console-apps/

ANSI-Coloring Console Output with .NET

This link has all the codes for ANSII escape codes, I have used it in C, so It may need some modifications.

http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html

Body:
So I'm trying to find a simple code that makes my code get printed in bold. When I searched the internet all of them were so complicated that it wasn't even worth it. Is there any easier way to make a string or just a Console.WriteLine(" "); bold?

Console.Write("Type in the number of people to create: ");
int time = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nGenerating " + time + " people please stand by...");
System.Threading.Thread.Sleep(3000);
Console.Clear();

Body:
You can use the ANSII escape codes, as long as your console supports it.

You can do basics like, color text, background and bold,underline and reverse colors.
for example in c#

Console.WriteLine("\x1b[1mTEST\x1b[0m");

will print it in bold. \x1b[0m at the end is used to reset the formatting, many formatting options are made by changing the number after the bracket.

look into these links, I have used it with C and Python in bash, but I'm not sure about C# at the moment.

https://www.jerriepelser.com/blog/using-ansi-color-codes-in-net-console-apps/

ANSI-Coloring Console Output with .NET

This link has all the codes for ANSII escape codes, I have used it in C, so It may need some modifications.

http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html


问:
Javascript custom Array.prototype interfering with for-in loops
I was attempting to extend Javascript's Object type with a function that retrieves all of the property names that are part of that object (basically what PHP's array_keys() function does to associative arrays).

```<code>Object.prototype.keys = function() {
    var a = [];
    for (var property in this) {
        a.push(property);
    }
    return a;
};

var a = {a:1,b:2,c:3,d:4};
alert(a.toSource());

var b = a.keys();
alert(b.toSource());
</code>```

When the variable b was alerted, I was expecting to see ["a","b","c","d"], instead I'm seeing ["a","b","c","d","keys"].

It appears the for-in loop is including the prototyped keys() functions.

Is it possible to avoid this behaviour whilst still prototying, or should I just avoid prototyping all together?

答:
The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties. MDN

So you can define non-enumerable properties.

```<code>Object.defineProperty(Array.prototype, 'foo', {
  value: 'bar',
  enumerable: false // Defaults to false.
});

const arr = [1,2,3];
for(const k in arr) console.log(k); // 0, 1, 2
console.log(arr.foo); // bar
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I was attempting to extend Javascript's Object type with a function that retrieves all of the property names that are part of that object (basically what PHP's array_keys() function does to associative arrays).

Object.prototype.keys = function() {
    var a = [];
    for (var property in this) {
        a.push(property);
    }
    return a;
};

var a = {a:1,b:2,c:3,d:4};
alert(a.toSource());

var b = a.keys();
alert(b.toSource());

When the variable b was alerted, I was expecting to see ["a","b","c","d"], instead I'm seeing ["a","b","c","d","keys"].

It appears the for-in loop is including the prototyped keys() functions.

Is it possible to avoid this behaviour whilst still prototying, or should I just avoid prototyping all together?

Body:
The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties. MDN

So you can define non-enumerable properties.

Object.defineProperty(Array.prototype, 'foo', {
  value: 'bar',
  enumerable: false // Defaults to false.
});

const arr = [1,2,3];
for(const k in arr) console.log(k); // 0, 1, 2
console.log(arr.foo); // bar


问:
How to insert a map into a popover - bootstrap
I need to have a popover which can present a map inside its body. I did this basic example:

```<code>    <!DOCTYPE html>
<html>

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />
  <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>

  <link rel="stylesheet" href="css/style.css">
  <script src="script/script.js"></script>
</head>

<body>
  <div class="container">
    <h3>Popover Example</h3>
    <a href="#" data-toggle="popover">Toggle popover</a>
  </div>

  <script>
    let script = `
    <script>
    var map = L.map('map').setView([51.505, -0.09], 13);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);

    L.marker([51.5, -0.09]).addTo(map)
    .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
    .openPopup();
    <\/script>`;

    console.log(script);
    $(document).ready(function() {
      $('[data-toggle="popover"]').popover({
        title: 'A nice map inside a popover!',
        content: "<div id='map' style='background: gray;'></div>" + script,
        html: true
      });

    });
  </script>
</body>

</html>
</code>```

It sends html content which contains a div and script for the leaflet map. It doesn't work.
I am not sure this approach would work out and maybe you know a better way to have a map once a table cell or any other element is clicked.

答:
Please check following code snippet:

      $(document).ready(function() {
           $('[data-toggle="popover"]').popover({
             title: 'A nice map inside a popover!',
             content: "

",
             html: true
           });

           $("[data-toggle=popover]").on('shown.bs.popover', function () {

         var map = L.map('map').setView([51.505, -0.09], 13);

         L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
         attribution: '© OpenStreetMap contributors'}).addTo(map);

         L.marker([51.5, -0.09]).addTo(map)
         .bindPopup('A pretty CSS3 popup.
 Easily customizable.')
         .openPopup();
         });

         });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> #map{
         height:300px;
         width:300px;
         }</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />

Popover Example

         Toggle popover

```

Hope this will helps you.

Body:
I need to have a popover which can present a map inside its body. I did this basic example:

    <!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />

  <link rel="stylesheet" href="css/style.css">

Popover Example

    Toggle popover

It sends html content which contains a div and script for the leaflet map. It doesn't work.
I am not sure this approach would work out and maybe you know a better way to have a map once a table cell or any other element is clicked.

Body:
Please check following code snippet:

      $(document).ready(function() {
           $('[data-toggle="popover"]').popover({
             title: 'A nice map inside a popover!',
             content: "<div id='map' style='background: gray;'></div>",
             html: true
           });

           $("[data-toggle=popover]").on('shown.bs.popover', function () {

         var map = L.map('map').setView([51.505, -0.09], 13);

         L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
         attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);

         L.marker([51.5, -0.09]).addTo(map)
         .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
         .openPopup();
         });

         });

 #map{
         height:300px;
         width:300px;
         }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />
      <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>

      <div class="container">
         <h3>Popover Example</h3>
         <a href="#" data-toggle="popover">Toggle popover</a>
      </div>

Hope this will helps you.


问:
Alternative to fgets()?
Description:

Obtain output from an executable

Note:

Will not compile, due to fgets() declaration

Question:

What is the best alternative to fgets, as fgets requires char *?

Is there a better alternative?

Illustration:

```<code>void Q_analysis (const char *data)
{
string buffer;
size_t found;
found = buffer.find_first_of (*data);

FILE *condorData = _popen ("condor_q", "r");
while (fgets (buffer.c_str(), buffer.max_size(), condorData) != NULL)
{
    if (found == string::npos)
    {
        Sleep(2000);
    } else {
        break;
    }
}
return;
}
</code>```

答:
You're right that you can't read directly into a std::string because its c_str and data methods both return const pointers. You could read into a std::vector<char> instead.

You could also use the getline function. But it requires an iostream object, not a C FILE pointer. You can get from one to the other, though, in a vendor-specific way. See "A Handy Guide To Handling Handles" for a diagram and some suggestions on how to get from one file type to another. Call fileno on your FILE* to get a numeric file descriptor, and then use fstream::attach to associate it with an fstream object. Then you can use getline.

Title: Alternative to fgets()?

Body:
Description:

Obtain output from an executable

Note:

Will not compile, due to fgets() declaration

Question:

What is the best alternative to fgets, as fgets requires char *?

Is there a better alternative?

Illustration:

void Q_analysis (const char *data)
{
string buffer;
size_t found;
found = buffer.find_first_of (*data);

FILE *condorData = _popen ("condor_q", "r");
while (fgets (buffer.c_str(), buffer.max_size(), condorData) != NULL)
{
    if (found == string::npos)
    {
        Sleep(2000);
    } else {
        break;
    }
}
return;
}

OwnerDisplayName: Rob Kennedy


问:
Floating three divs next to a fourth one
Is there a way I can have a 2 column layout, with div one, two and three on the left and div four on the right? I could achieve this by adding another div around divs one, two and three, but can it be done without adding any html?</p>

答:
Yes, => http://jsfiddle.net/steweb/hwpJT/

put #four above others and add float:right

ContentLicense: CC BY-SA 3.0


问:
Select IN query cosmos DB
How to write a select IN query in cosmos db/document db? Something similar to this

```<code>SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...)
</code>```

I am using Microsoft.Azure.DocumentDB.Core nuget package.

答:
Have you had a look at IN and CONTAINS?

FOR EX,

```<code>  SELECT *
    FROM Families
    WHERE Families.id IN ('AndersenFamily', 'WakefieldFamily')
</code>```

Title: Select IN query cosmos DB

Body:
How to write a select IN query in cosmos db/document db? Something similar to this

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...)

I am using Microsoft.Azure.DocumentDB.Core nuget package.

Body:
Have you had a look at IN and CONTAINS?

FOR EX,

  SELECT *
    FROM Families
    WHERE Families.id IN ('AndersenFamily', 'WakefieldFamily')


问:
How RDMA WRITE/READ behaves when the remote memory buffer is unpinned by the OS?
let two infiniband process execute on two machines. When one process terminates, all its resources (allocated file, buffers, ...) are freed even the memory that the process registered for RDMA WRITE/READ operations.

Can someone has references on how the remote Channel Adapter on the other process knows that the buffer memory is now free ? Which element of the infiniband stack does this control and when ?

答: When a connected peer exits without sending a disconnect, the IB core initiates a clean up procedure which also sends a RDMA DISCONNECT MAD packet to the other RNIC if it's RC QP. On seeing a disconnect, the other end RNIC cleansup it's SQs/RQs and stuff</p>


问:
Error while creating Azure IR:Check the linked service configuration is correct
Error while creating an Azure IR data factory.

Cannot connect to SQL Database:
'mysqlserversowmya.database.windows.net', Database: 'master', User:
'adminuser'. Check the linked service configuration is correct, and
make sure the SQL Database firewall allows the integration runtime to
access.

答:
Make sure you have open the SQL database firewall: add client ip and Allow Azure services and resources to access this server On portal:

To see: Server-level IP firewall rules

Hope this helps.


问:
Javascript: reassign array value using querySelectorAll() failed to update
path = element[i].nextElementSibling;

Getting the value of element[i].nextElementSibling change the variable path value,
but when I reassign the value of element[i]

element[i] = path;

the element[i] stay as it is. Why is this happening?

/*
Press Ctrl+Shift+C while opening the web console with google chrome or mozzila firefox (Tools > Web Developer > Web Console) and hover over the element display by the console to highlight the element.
*/
let element = document.querySelectorAll("a");
console.log(element.length);
for (let i = 0; i < element.length; i++) {
 let path = element[i].nextElementSibling;
 //Is NOT next sibling element exist and is

 if(!(path && path.matches("p"))){
  //path is null, reasign to
  path = element[i];
  console.log("path = element[i] (Origin):");
  console.log(path = element[i]);
  //get  parent element
  path = path.parentElement;
  console.log("path = path.parentElement (Origin's Parent):");
  console.log(path); //display

  if(path && path.nextElementSibling.matches("p")){
   //get destination
   element[i] = path.nextElementSibling;
   //fail to changed T_T
   console.log("element[i] = path.nextElementSibling; (Origin's Parent's Next Sibling)");
   console.log("'path.nextElementSibling' value:");
   console.log(path.nextElementSibling); //display

   console.log("Value of 'element[i]' (did not change!):");
   console.log(element[i]); //why still ? not

  }
 }else{ //sibling element
  element[i] = path;
  console.log("element[i] = path");
  console.log("'path' value:");
  console.log(path);
  console.log("Value of 'element[i]' (did not change!):");
  console.log(element[i]);
 }
 console.log("FINAL value of element[i]:");
 element[i].classList.add("get--target");
 console.log(element[i]);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
 font-size: 20px;
 font-weight: bold;
 color: white;
 background: black;
}
div{
 background: navy;
 padding: 20px;
}
span{
 display: none;
 margin: 10px 0;
 padding: 10px;
}
a, .get--target{
 display: block;
 margin: 10px;
 padding: 10px;
}
a{
 text-decoration: none;
 color: white;
 background: orange;
}
p{
 background: blue;
 padding: 10px;
}
p.get--target span{
 display: block;
 background: lightgreen;
}
a.get--target span{
 display: block;
 background: red;
}</code>```

  Origin Failed

Destination Success

Destination Success

```

P.S.
Google Chrome and Mozilla Firefox have different display of console log
the the first result of element[i] that still not yet set to have get--target class, have in Google Chrome?
Google Chrome and Mozilla Firefox console log results

答:
I think the reason is document.querySelectorAll() method will NodeList Object. The NodeList Object cannot be modified. Inorder to alter NodeList object you have to convert it into normal javascript array. Array.from(document.querySelectorAll('[selector]')) will return javascript array instead of NodeList Object.Hope this helps.

/*
Press Ctrl+Shift+C while opening the web console with google chrome or mozzila firefox (Tools > Web Developer > Web Console) and hover over the element display by the console to highlight the element.
*/
let element = Array.from(document.querySelectorAll("a"));
console.log(element.length);
for (let i = 0; i < element.length; i++) {
 let path = element[i].nextElementSibling;
 //Is NOT next sibling element exist and is

 if(!(path && path.matches("p"))){
  //path is null, reasign to
  path = element[i];
  console.log("path = element[i] (Origin):");
  console.log(path = element[i]);
  //get  parent element
  path = path.parentElement;
  console.log("path = path.parentElement (Origin's Parent):");
  console.log(path); //display

  if(path && path.nextElementSibling.matches("p")){
   //get destination
   element[i] = path.nextElementSibling;
   //fail to changed T_T
   console.log("element[i] = path.nextElementSibling; (Origin's Parent's Next Sibling)");
   console.log("'path.nextElementSibling' value:");
   console.log(path.nextElementSibling); //display

   console.log("Value of 'element[i]' (did not change!):");
   console.log(element[i]); //why still ? not

  }
 }else{ //sibling element
  element[i] = path;
  console.log("element[i] = path");
  console.log("'path' value:");
  console.log(path);
  console.log("Value of 'element[i]' (did not change!):");
  console.log(element[i]);
 }
 console.log("FINAL value of element[i]:");
 element[i].classList.add("get--target");
 console.log(element[i]);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
 font-size: 20px;
 font-weight: bold;
 color: white;
 background: black;
}
div{
 background: navy;
 padding: 20px;
}
span{
 display: none;
 margin: 10px 0;
 padding: 10px;
}
a, .get--target{
 display: block;
 margin: 10px;
 padding: 10px;
}
a{
 text-decoration: none;
 color: white;
 background: orange;
}
p{
 background: blue;
 padding: 10px;
}
p.get--target span{
 display: block;
 background: lightgreen;
}
a.get--target span{
 display: block;
 background: red;
}</code>```

  Origin Failed

Destination Success

Destination Success

```

Body:
path = element[i].nextElementSibling;

Getting the value of element[i].nextElementSibling change the variable path value,
but when I reassign the value of element[i]

element[i] = path;

the element[i] stay as it is. Why is this happening?

/*
Press Ctrl+Shift+C while opening the web console with google chrome or mozzila firefox (Tools > Web Developer > Web Console) and hover over the element display by the console to highlight the element.
*/
let element = document.querySelectorAll("a");
console.log(element.length);
for (let i = 0; i < element.length; i++) {
 let path = element[i].nextElementSibling;
 //Is NOT next sibling element exist and is

 if(!(path && path.matches("p"))){
  //path is null, reasign to
  path = element[i];
  console.log("path = element[i] (Origin):");
  console.log(path = element[i]);
  //get  parent element
  path = path.parentElement;
  console.log("path = path.parentElement (Origin's Parent):");
  console.log(path); //display

  if(path && path.nextElementSibling.matches("p")){
   //get destination
   element[i] = path.nextElementSibling;
   //fail to changed T_T
   console.log("element[i] = path.nextElementSibling; (Origin's Parent's Next Sibling)");
   console.log("'path.nextElementSibling' value:");
   console.log(path.nextElementSibling); //display

   console.log("Value of 'element[i]' (did not change!):");
   console.log(element[i]); //why still ? not

  }
 }else{ //sibling element
  element[i] = path;
  console.log("element[i] = path");
  console.log("'path' value:");
  console.log(path);
  console.log("Value of 'element[i]' (did not change!):");
  console.log(element[i]);
 }
 console.log("FINAL value of element[i]:");
 element[i].classList.add("get--target");
 console.log(element[i]);
}

body{
 font-size: 20px;
 font-weight: bold;
 color: white;
 background: black;
}
div{
 background: navy;
 padding: 20px;
}
span{
 display: none;
 margin: 10px 0;
 padding: 10px;
}
a, .get--target{
 display: block;
 margin: 10px;
 padding: 10px;
}
a{
 text-decoration: none;
 color: white;
 background: orange;
}
p{
 background: blue;
 padding: 10px;
}
p.get--target span{
 display: block;
 background: lightgreen;
}
a.get--target span{
 display: block;
 background: red;
}

  Origin Failed

Destination Success

Destination Success

P.S.
Google Chrome and Mozilla Firefox have different display of console log
the the first result of element[i] that still not yet set to have get--target class, have in Google Chrome?
Google Chrome and Mozilla Firefox console log results

Body:
I think the reason is document.querySelectorAll() method will NodeList Object. The NodeList Object cannot be modified. Inorder to alter NodeList object you have to convert it into normal javascript array. Array.from(document.querySelectorAll('[selector]')) will return javascript array instead of NodeList Object.Hope this helps.

/*
Press Ctrl+Shift+C while opening the web console with google chrome or mozzila firefox (Tools > Web Developer > Web Console) and hover over the element display by the console to highlight the element.
*/
let element = Array.from(document.querySelectorAll("a"));
console.log(element.length);
for (let i = 0; i < element.length; i++) {
 let path = element[i].nextElementSibling;
 //Is NOT next sibling element exist and is <p>
 if(!(path && path.matches("p"))){
  //path is null, reasign to <a>
  path = element[i];
  console.log("path = element[i] (Origin):");
  console.log(path = element[i]);
  //get <a> parent element
  path = path.parentElement;
  console.log("path = path.parentElement (Origin's Parent):");
  console.log(path); //display <div>
  if(path && path.nextElementSibling.matches("p")){
   //get destination
   element[i] = path.nextElementSibling;
   //fail to changed T_T
   console.log("element[i] = path.nextElementSibling; (Origin's Parent's Next Sibling)");
   console.log("'path.nextElementSibling' value:");
   console.log(path.nextElementSibling); //display <p>
   console.log("Value of 'element[i]' (did not change!):");
   console.log(element[i]); //why still <a>? not <p>
  }
 }else{ //sibling element
  element[i] = path;
  console.log("element[i] = path");
  console.log("'path' value:");
  console.log(path);
  console.log("Value of 'element[i]' (did not change!):");
  console.log(element[i]);
 }
 console.log("FINAL value of element[i]:");
 element[i].classList.add("get--target");
 console.log(element[i]);
}

body{
 font-size: 20px;
 font-weight: bold;
 color: white;
 background: black;
}
div{
 background: navy;
 padding: 20px;
}
span{
 display: none;
 margin: 10px 0;
 padding: 10px;
}
a, .get--target{
 display: block;
 margin: 10px;
 padding: 10px;
}
a{
 text-decoration: none;
 color: white;
 background: orange;
}
p{
 background: blue;
 padding: 10px;
}
p.get--target span{
 display: block;
 background: lightgreen;
}
a.get--target span{
 display: block;
 background: red;
}

<body>
 <div>
  <a href="#">Origin <span>Failed</span></a>
  <p>Destination <span>Success</span></p>
 </div>
 <p>Destination <span>Success</span></p>
</body>


问:
MongoError: $match with $text is only allowed as the first pipeline stage
I have MongoDb aggreate with search text.
but the mongoDb throw Execption, idk maybe my aggregate is wrong? or i cant use $match more than 1 time? Sorry im new with MongoDB

```<code>const current_date = new Date()
var two_days_ago = current_date
two_days_ago.setDate(current_date.getDate() - 2)

return Post.aggregate([
    { $match: { editorChoice: false }},
    { $match: { $text: { $search: category } } },
    { $match: { $expr: { $and: [{ $gte: ["$createdAt", two_days_ago ] }, { $lte: ["$createdAt", current_date ] }] } } },
    { $sort: {'likeCount': -1} },
    { $limit: 80 },
    { $lookup: {
        from: 'likes',
        let: { postUid: '$_id' },
        pipeline: [ {
            $match: {
                $expr: {
                    $and: [
                    { $eq: ['$user_id', mongose.Types.ObjectId(user_id)] },
                    { $eq: ['$post_id', '$$postUid'] } ]
                }
            }
        } ],
        as: 'likes' } },
    { $addFields: { isLike: { $eq: ['$likeCount', 1] } } },
    { $lookup: {
        from: 'locations',
        localField: 'location',
        foreignField: '_id',
        as: 'location' } },
    { $unwind: {
        path: '$location',
        preserveNullAndEmptyArrays: true }},
    { $lookup: {
        from: 'sticker_images',
        localField: 'sticker',
        foreignField: '_id',
        as: 'sticker' } },
    { $unwind: {
        path: '$sticker',
        preserveNullAndEmptyArrays: true }},
    { $lookup: {
        from: 'prangko_images',
        localField: 'prangko',
        foreignField: '_id',
        as: 'prangko' } },
    { $unwind: {
        path: '$prangko',
        preserveNullAndEmptyArrays: true }},
    { $project: aggregate_project }
]).exec()
</code>```

but i have similar aggreate with text search but without this

```<code>{ $match: { $expr: { $and: [{ $gte: ["$createdAt", two_days_ago ] }, { $lte: ["$createdAt", current_date ] }] } } },
</code>```

Its my $match wrong or something about Date variable?

答:
try like this</p>

```<code>return Post.aggregate([
    { $match: { $text: { $search: category } } },
    { $match: { editorChoice: false }},
    { $match: { $expr: { $and: [{ $gte: ["$createdAt", two_days_ago ] }, { $lte: ["$createdAt", current_date ] }] } } },
    { $sort: {'likeCount': -1} },
    { $limit: 80 },
    { $lookup: {
        from: 'likes',
        let: { postUid: '$_id' },
        pipeline: [ {
            $match: {
                $expr: {
                    $and: [
                    { $eq: ['$user_id', mongose.Types.ObjectId(user_id)] },
                    { $eq: ['$post_id', '$$postUid'] } ]
                }
            }
        } ],
        as: 'likes' } },
    { $addFields: { isLike: { $eq: ['$likeCount', 1] } } },
    { $lookup: {
        from: 'locations',
        localField: 'location',
        foreignField: '_id',
        as: 'location' } },
    { $unwind: {
        path: '$location',
        preserveNullAndEmptyArrays: true }},
    { $lookup: {
        from: 'sticker_images',
        localField: 'sticker',
        foreignField: '_id',
        as: 'sticker' } },
    { $unwind: {
        path: '$sticker',
        preserveNullAndEmptyArrays: true }},
    { $lookup: {
        from: 'prangko_images',
        localField: 'prangko',
        foreignField: '_id',
        as: 'prangko' } },
    { $unwind: {
        path: '$prangko',
        preserveNullAndEmptyArrays: true }},
    { $project: aggregate_project }
]).exec()
</code>```

Body:
I have MongoDb aggreate with search text.
but the mongoDb throw Execption, idk maybe my aggregate is wrong? or i cant use $match more than 1 time? Sorry im new with MongoDB

const current_date = new Date()
var two_days_ago = current_date
two_days_ago.setDate(current_date.getDate() - 2)

return Post.aggregate([
    { $match: { editorChoice: false }},
    { $match: { $text: { $search: category } } },
    { $match: { $expr: { $and: [{ $gte: ["$createdAt", two_days_ago ] }, { $lte: ["$createdAt", current_date ] }] } } },
    { $sort: {'likeCount': -1} },
    { $limit: 80 },
    { $lookup: {
        from: 'likes',
        let: { postUid: '$_id' },
        pipeline: [ {
            $match: {
                $expr: {
                    $and: [
                    { $eq: ['$user_id', mongose.Types.ObjectId(user_id)] },
                    { $eq: ['$post_id', '$$postUid'] } ]
                }
            }
        } ],
        as: 'likes' } },
    { $addFields: { isLike: { $eq: ['$likeCount', 1] } } },
    { $lookup: {
        from: 'locations',
        localField: 'location',
        foreignField: '_id',
        as: 'location' } },
    { $unwind: {
        path: '$location',
        preserveNullAndEmptyArrays: true }},
    { $lookup: {
        from: 'sticker_images',
        localField: 'sticker',
        foreignField: '_id',
        as: 'sticker' } },
    { $unwind: {
        path: '$sticker',
        preserveNullAndEmptyArrays: true }},
    { $lookup: {
        from: 'prangko_images',
        localField: 'prangko',
        foreignField: '_id',
        as: 'prangko' } },
    { $unwind: {
        path: '$prangko',
        preserveNullAndEmptyArrays: true }},
    { $project: aggregate_project }
]).exec()

but i have similar aggreate with text search but without this

{ $match: { $expr: { $and: [{ $gte: ["$createdAt", two_days_ago ] }, { $lte: ["$createdAt", current_date ] }] } } },

Its my $match wrong or something about Date variable?

Body:
try like this

return Post.aggregate([
    { $match: { $text: { $search: category } } },
    { $match: { editorChoice: false }},
    { $match: { $expr: { $and: [{ $gte: ["$createdAt", two_days_ago ] }, { $lte: ["$createdAt", current_date ] }] } } },
    { $sort: {'likeCount': -1} },
    { $limit: 80 },
    { $lookup: {
        from: 'likes',
        let: { postUid: '$_id' },
        pipeline: [ {
            $match: {
                $expr: {
                    $and: [
                    { $eq: ['$user_id', mongose.Types.ObjectId(user_id)] },
                    { $eq: ['$post_id', '$$postUid'] } ]
                }
            }
        } ],
        as: 'likes' } },
    { $addFields: { isLike: { $eq: ['$likeCount', 1] } } },
    { $lookup: {
        from: 'locations',
        localField: 'location',
        foreignField: '_id',
        as: 'location' } },
    { $unwind: {
        path: '$location',
        preserveNullAndEmptyArrays: true }},
    { $lookup: {
        from: 'sticker_images',
        localField: 'sticker',
        foreignField: '_id',
        as: 'sticker' } },
    { $unwind: {
        path: '$sticker',
        preserveNullAndEmptyArrays: true }},
    { $lookup: {
        from: 'prangko_images',
        localField: 'prangko',
        foreignField: '_id',
        as: 'prangko' } },
    { $unwind: {
        path: '$prangko',
        preserveNullAndEmptyArrays: true }},
    { $project: aggregate_project }
]).exec()


问:
How to iterate this Go interface
Here is a sample of my JSON post:

```<code>{
    "jsonFilter" :[{
        "column": "",
        "contains": "",
        "condition": "",
        "not": true
    }, {
        "column": "",
        "contains": "",
        "condition": "",
        "not": true
    }]
}
</code>```

My Echo framework handler:

```<code>func GetFilteredFileData(c echo.Context) error {
    body := echo.Map{}
    if err := c.Bind(&body); err != nil {
        fmt.Println(err)
    }

    fmt.Println(body)

    for key, element := range body {
        fmt.Println(key, element)
    }
}
</code>```

Results:

```<code>jsonFilter [map[column:StartTimestamp condition:contains contains:<nil> not:false] map[column:SourceIP condition:startsWith contains:<nil> not:true]]
</code>```

This is not index accessible, nor key accessible. I was told I needed to make a struct or 2, but all my efforts there did not work (gorilla schema, json.Marshal, etc)

What is the proper way to take this map and make it actually usable in a variable/struct ref?

答:
You can unmarshal that json into the following struct:

```<code>type Body struct {
  Filter []JSONFilter `json:"jsonFilter"`
}

type JSONFilter struct {
   Column string `json:"column"`
   Contains string `json:"contains"`
   Condition string `json:"condition"`
   Not bool `json:"not"`
}
</code>```

I don't know about this echo framework, but it looks like something like this should work:

```<code>    body := Body{}
    if err := c.Bind(&body); err != nil {
        fmt.Println(err)
    }
</code>```

Or, json.Unmarshal, if the above doesn't do.

Title: How to iterate this Go interface

Body:
Here is a sample of my JSON post:

{
    "jsonFilter" :[{
        "column": "",
        "contains": "",
        "condition": "",
        "not": true
    }, {
        "column": "",
        "contains": "",
        "condition": "",
        "not": true
    }]
}

My Echo framework handler:

func GetFilteredFileData(c echo.Context) error {
    body := echo.Map{}
    if err := c.Bind(&body); err != nil {
        fmt.Println(err)
    }

    fmt.Println(body)

    for key, element := range body {
        fmt.Println(key, element)
    }
}

Results:

jsonFilter [map[column:StartTimestamp condition:contains contains:<nil> not:false] map[column:SourceIP condition:startsWith contains:<nil> not:true]]

This is not index accessible, nor key accessible. I was told I needed to make a struct or 2, but all my efforts there did not work (gorilla schema, json.Marshal, etc)

What is the proper way to take this map and make it actually usable in a variable/struct ref?

Body:
You can unmarshal that json into the following struct:

type Body struct {
  Filter []JSONFilter `json:"jsonFilter"`
}

type JSONFilter struct {
   Column string `json:"column"`
   Contains string `json:"contains"`
   Condition string `json:"condition"`
   Not bool `json:"not"`
}

I don't know about this echo framework, but it looks like something like this should work:

    body := Body{}
    if err := c.Bind(&body); err != nil {
        fmt.Println(err)
    }

Or, json.Unmarshal, if the above doesn't do.


问:
How to delete the image from the storage in laravel?
I am currently trying to delete an image when a user updates his/her post before publishing.

Everything works fine, the image is changed in the database and post page, but I want to delete the previous image.

Here is my controller

```<code>public function updatePost(Request $request){
    $data = $request->all();
    $postid = $request['id'];
    $isExist = Post::where('id', $postid)->first();
    if($isExist){
        if ($request->hasFile('image')) {

            $file = $request->File('image');
            //Get filename with extension
            $fileNameToStoreWithExt = $file[0]->getClientOriginalName();
            //Get just filename
            $filename = pathinfo($fileNameToStoreWithExt, PATHINFO_FILENAME);
            //Get just ext
            $extension = $file[0]->getClientOriginalExtension();
            //File to store
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            //Upload Image
            $path = $file[0]->storeAs('image', $fileNameToStore);
            $file[0]->move('storage/image', $fileNameToStore);
            File::delete(public_path('storage/image'.$isExist['image']));
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content'],
                'image' => $path
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }else{
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content']
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }
    }else{
        return response()->json([
            'error'=> 'post does not exist'
        ]);
    }
}
</code>```

I used:

File::delete(public_path('storage/image'.$isExist['image']));

but it didn't do the job

my delete function

```<code>       public function deletePost($id){
        $post = Post::where('id',$id)->first();
//        dd($post);
        if(!$post){
            return response()->json([
                'status' => '500',
                'error' => 'post not found'
            ]);
        }
        Storage::disk('public')->delete('/storage/image'. $post['image']);
        Post::where('id', $id)->delete();
        return response()->json([
            'status'=> '200',
            'response'=> 'Post successfully deleted'
        ]);
    }
</code>```

my storage path snapshot

答:
You can use File to delete file from specific path

```<code> $file= "image path here";
 \File::delete($file);
</code>```

Delete uploaded file from public dir

OR

You can use unlink for the same

```<code>$image_path = "image path here";

 if (file_exists($image_path)) {

       @unlink($image_path);

   }
</code>```

PHP -> unlink

Body:
I am currently trying to delete an image when a user updates his/her post before publishing.

Everything works fine, the image is changed in the database and post page, but I want to delete the previous image.

Here is my controller

public function updatePost(Request $request){
    $data = $request->all();
    $postid = $request['id'];
    $isExist = Post::where('id', $postid)->first();
    if($isExist){
        if ($request->hasFile('image')) {

            $file = $request->File('image');
            //Get filename with extension
            $fileNameToStoreWithExt = $file[0]->getClientOriginalName();
            //Get just filename
            $filename = pathinfo($fileNameToStoreWithExt, PATHINFO_FILENAME);
            //Get just ext
            $extension = $file[0]->getClientOriginalExtension();
            //File to store
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            //Upload Image
            $path = $file[0]->storeAs('image', $fileNameToStore);
            $file[0]->move('storage/image', $fileNameToStore);
            File::delete(public_path('storage/image'.$isExist['image']));
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content'],
                'image' => $path
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }else{
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content']
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }
    }else{
        return response()->json([
            'error'=> 'post does not exist'
        ]);
    }
}

I used:

File::delete(public_path('storage/image'.$isExist['image']));

but it didn't do the job

my delete function

       public function deletePost($id){
        $post = Post::where('id',$id)->first();
//        dd($post);
        if(!$post){
            return response()->json([
                'status' => '500',
                'error' => 'post not found'
            ]);
        }
        Storage::disk('public')->delete('/storage/image'. $post['image']);
        Post::where('id', $id)->delete();
        return response()->json([
            'status'=> '200',
            'response'=> 'Post successfully deleted'
        ]);
    }

my storage path snapshot

Body:
You can use File to delete file from specific path

 $file= "image path here";
 \File::delete($file);

Delete uploaded file from public dir

OR

You can use unlink for the same

$image_path = "image path here";

 if (file_exists($image_path)) {

       @unlink($image_path);

   }

PHP -> unlink


问:
Python functions call by reference
In some languages you can pass a parameter by reference or value by using a special reserved word like ref or val. When you pass a parameter to a Python function it never alters the value of the parameter on leaving the function.The only way to do this is by using the global reserved word (or as i understand it currently).

Example 1:

```<code>k = 2

def foo (n):
     n = n * n     #clarity regarding comment below
     square = n
     return square

j = foo(k)
print j
print k
</code>```

would show

```<code>>>4
>>2
</code>```

showing k to be unchanged.

In this example the variable n is never changed

Example 2:

```<code>n = 0
def foo():
    global n
    n = n * n
    return n
</code>```

In this example the variable n is changed.

Is there any way in Python to call a function and tell Python that the parameter is either a value or reference parameter instead of using global?

答:
Consider that the variable is a box and the value it points to is the "thing" inside the box:

1. Pass by reference : function shares the same box and thereby the thing inside also.

2. Pass by value : function creates a new box, a replica of the old one, including a copy of whatever thing is inside it. Eg. Java - functions create a copy of the box and the thing inside it which can be: a primitive / a reference to an object. (note that the copied reference in the new box and the original both still point to the same object, here the reference IS the thing inside the box, not the object it is pointing to)

3. Pass by object-reference: the function creates a box, but it encloses the same thing the initial box was enclosing. So in Python:

a) if the thing inside said box is mutable, changes made will reflect back in the original box  (eg. lists)

b) if the thing is immutable (like python strings and numeric types), then the box inside the function will hold the same thing UNTIL you try to change its value. Once changed, the thing in the function's box is a totally new thing compared to the original one. Hence id() for that box will now give the identity of the new thing it encloses.

Title: Python functions call by reference

Body:
In some languages you can pass a parameter by reference or value by using a special reserved word like ref or val. When you pass a parameter to a Python function it never alters the value of the parameter on leaving the function.The only way to do this is by using the global reserved word (or as i understand it currently).

Example 1:

k = 2

def foo (n):
     n = n * n     #clarity regarding comment below
     square = n
     return square

j = foo(k)
print j
print k

would show

>>4
>>2

showing k to be unchanged.

In this example the variable n is never changed

Example 2:

n = 0
def foo():
    global n
    n = n * n
    return n

In this example the variable n is changed.

Is there any way in Python to call a function and tell Python that the parameter is either a value or reference parameter instead of using global?


问:
lavaral 5 ERROR{ (SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)}
```<code>  'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => [

    'sqlite' => [
        'driver'   => 'sqlite',
        'database' => storage_path('database.sqlite'),
        'prefix'   => '',
    ],
</code>```

**JUST CHANGED THE CODE FOR LOCALHOST AND  CHANNGED THE NAME TO ROOT AND SET THE PASSWORD OF PHPMYADMIN . **

**WHEN WRITTING  THE COMMAND IN XAMPP SHELL ((Php artisan migrate:install)) **

```<code>        'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'laravel'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', 'password'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

    'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'password'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ],

    'sqlsrv' => [
        'driver'   => 'sqlsrv',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'password'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
    ],

],

/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/

'migrations' => 'migrations',

/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/

'redis' => [

    'cluster' => false,

    'default' => [
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ],

],
</code>```

it is showing error   SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)

答:
Make sure you have to set up right server credentials into .env file on your Laravel project:

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp_db
DB_USERNAME=root
DB_PASSWORD=pass
</code>```

Try to clean up artisan cache and restart the artisan,

```<code>php artisan config:clear
restart php artisan
</code>```

Body:
  'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => [

    'sqlite' => [
        'driver'   => 'sqlite',
        'database' => storage_path('database.sqlite'),
        'prefix'   => '',
    ],

**JUST CHANGED THE CODE FOR LOCALHOST AND  CHANNGED THE NAME TO ROOT AND SET THE PASSWORD OF PHPMYADMIN . **

**WHEN WRITTING  THE COMMAND IN XAMPP SHELL ((Php artisan migrate:install)) **

        'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'laravel'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', 'password'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

    'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'password'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ],

    'sqlsrv' => [
        'driver'   => 'sqlsrv',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'password'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
    ],

],

/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/

'migrations' => 'migrations',

/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/

'redis' => [

    'cluster' => false,

    'default' => [
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ],

],

it is showing error   SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)

Body:
Make sure you have to set up right server credentials into .env file on your Laravel project:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp_db
DB_USERNAME=root
DB_PASSWORD=pass

Try to clean up artisan cache and restart the artisan,

php artisan config:clear
restart php artisan


问:
What is the recommended way to fanout in SQS lambda environment?
I would like to send a push notification to users in my database in a lambda environment via SQS / messaging queue architecture, in order to do that

I would first need to query all users in my database with push notifications enabled.

loop over all of them them

send a SQS event/message for each user.

let my sqs triggered lambda handle/send the push notification

Is there a better way to implement this to avoid querying a big number of users and/or looping over all the results to send a SQS message for each?

答:
I would suggest an additional piece in your application architecture,

I personally prefer to avoid using the Primary database for heavy querying,

assuming you have a large user base.

I will suggest maintaining your user list in a Search Engine like ElasticSearch or CloudSearch, or a simple table with just the user list in AWS DynamoDb or create a Read Replica of your DB.

To no confuse you, use a Search Engine(first choice) or an AWS DynamoDb

This will avoid creating pressure on your database when you query the read specialty datastore and won't affect other modules in operation

And it's way fast to query this way

Step 2: loop over all of them them

Step 3: batch send messages to SQS using its SendMessageBatch method like Jason is suggesting

Step 4: Based on your SQS setting, you may process multiple messages on your Lambda function


问:
Does Cassandra need Autocompaction for completely immutable data?
I am trying to optimize performance of a Cassandra Table we have in production that is classic event data with timestamps. Going through the different settings, I've been spending some time looking at compaction strategys and wat compaction in cassandra does.

At first, I thought that TimeWindowCompaction was Ideal for our use case, but then I realized that we never delete or update Data.

Is it possible that it is better to disable compaction completely? How are SSTables formed when there is no compaction strategy at all?

答:
Disabling compaction is really not a good option but you can change compaction strategy based on your application behaviour.In your case you can go with Size Tiered Compaction Strategy or Leveled Compaction Strategy.

However,TimeWindowCompactionStrategy is a good option for time series data.
You may refer details as below to understand the use cases.

TimeWindowCompactionStrategy (TWCS) is designed specifically for workloads where it’s beneficial to have data on disk grouped by the timestamp of the data, a common goal when the workload is time-series in nature or when all data is written with a TTL. In an expiring/TTL workload, the contents of an entire SSTable likely expire at approximately the same time, allowing them to be dropped completely.

http://cassandra.apache.org/doc/latest/operating/compaction.html


答:
You can use normal PHP delete file keyword @unlink</p>

```<code>if (file_exists($image)) {
  @unlink($image);
}
</code>```

Title: How to delete the image from the storage in laravel?

Body:
You can use normal PHP delete file keyword @unlink

if (file_exists($image)) {
  @unlink($image);
}


问:
Python or Java for text processing (text mining, information retrieval, natural language processing)
I'm soon to start on a new project where I am going to do lots of text processing tasks like searching, categorization/classifying, clustering, and so on.

There's going to be a huge amount of documents that need to be processed; probably millions of documents. After the initial processing, it also has to be able to be updated daily with multiple new documents.

Can I use Python to do this, or is Python too slow? Is it best to use Java?

If possible, I would prefer Python since that's what I have been using lately. Plus, I would finish the coding part much faster. But it all depends on Python's speed. I have used Python for some small scale text processing tasks with only a couple of thousand documents, but I am not sure how well it scales up.

答:
Both are good. Java has a lot of steam going into text processing. Stanford's text processing system, OpenNLP, UIMA, and GATE seem to be the big players (I know I am missing some). You can literally run the StanfordNLP module on a large corpus after a few minutes of playing with it. But, it has major memory requirements (3 GB or so when I was using it).

NLTK, Gensim, Pattern, and many other Python modules are very good at text processing. Their memory usage and performance are very reasonable.

Python scales up because text processing is a very easily scalable problem. You can use multiprocessing very easily when parsing/tagging/chunking/extracting documents. Once your get your text into any sort of feature vector, then you can use numpy arrays, and we all know how great numpy is...

I learned with NLTK, and Python has helped me greatly in reducing development time, so I opine that you give that a shot first. They have a very helpful mailing list as well, which I suggest you join.

If you have custom scripts, you might want to check out how well they perform with PyPy.


问:
Change request parameters name - Laravel
is there anyway to change the parameters name of request in laravel?

something like :

```<code>//we have $request['email'] in our request object and we need to change the name of it NOT VALUE

ChangeParaName($request['email'],$request['password']);

//now instead of $request['email'] we have $request['password'] with same value in our request object and just name of parameter changed
</code>```

答:
You could do this:

```<code>$request->merge(['password' => $request->email]);
</code>```

This will simply put a key called password in $request with value of $request->email.
The email key would still be there.

Body:
is there anyway to change the parameters name of request in laravel?

something like :

//we have $request['email'] in our request object and we need to change the name of it NOT VALUE

ChangeParaName($request['email'],$request['password']);

//now instead of $request['email'] we have $request['password'] with same value in our request object and just name of parameter changed

Body:
You could do this:

$request->merge(['password' => $request->email]);

This will simply put a key called password in $request with value of $request->email.
The email key would still be there.


问:
Python input contains NaN, infinity or a value too large for dtype float32
I'm trying to classify using sklearn's decision tree classifier. I've stored my training and testing datasets into two seperate pandas dataframes. I'm calling the classifier like so:

```<code>classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)
classifier.fit(features_in_training_set, class_labels_in_training_set)
predictions = classifier.predict(features_in_testing_set)
</code>```

However, I'm receiving this error, which seems to be common when classifying with the tree.

```<code>ValueError: Input contains NaN, infinity or a value too large for dtype('float32').
</code>```

I know that there are no missing values in either dataset. I am changing them using the imputer method. The print out of my dataframes shows this but to double check, I've also tried df.isna() and the outputs are all False. I don't think I have infinity values as the frames consist of binary values. I don't want to remove rows or the columns as I don't want to reduce my dataset. I also don't want to replace them on any other criteria.

I'm not quite sure how to find which columns are too large for dtype float 32 and how to change them if they are. I have a feeling that it could be my timestamp column. Here's a snippet of the training data frame as it's quite large:

```<code>             time      A     B
0       1.518999e+09   1     1
1       1.518999e+09   1     0
2       1.518999e+09   0     1
3       1.518999e+09   0     0
</code>```

答:
Try to check the summary of the dataframe.
for e.g. if your data frame shows missing samples for any features, it means there are null values for some of the observations.

a possible divide by null scenario is being encountered.

Body:
I'm trying to classify using sklearn's decision tree classifier. I've stored my training and testing datasets into two seperate pandas dataframes. I'm calling the classifier like so:

classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)
classifier.fit(features_in_training_set, class_labels_in_training_set)
predictions = classifier.predict(features_in_testing_set)

However, I'm receiving this error, which seems to be common when classifying with the tree.

ValueError: Input contains NaN, infinity or a value too large for dtype('float32').

I know that there are no missing values in either dataset. I am changing them using the imputer method. The print out of my dataframes shows this but to double check, I've also tried df.isna() and the outputs are all False. I don't think I have infinity values as the frames consist of binary values. I don't want to remove rows or the columns as I don't want to reduce my dataset. I also don't want to replace them on any other criteria.

I'm not quite sure how to find which columns are too large for dtype float 32 and how to change them if they are. I have a feeling that it could be my timestamp column. Here's a snippet of the training data frame as it's quite large:

             time      A     B
0       1.518999e+09   1     1
1       1.518999e+09   1     0
2       1.518999e+09   0     1
3       1.518999e+09   0     0