问:
How to make a for cycle with if conditions faster
I have written a piece of code however it takes an enormous amount of time to run and I don't know how to make it faster. Can anyone help me?

Here is the code:

```<code>import networkx as nx
import matplotlib.pyplot as plt
import osmnx as ox
import pandas as pd
from shapely.wkt import loads as load_wkt
import numpy as np
import matplotlib.cm as cm
ox.config(log_console=True, use_cache=True)
import matplotlib as mpl
import random as rd

distrito = ['Lisbon District', 'Setúbal District']
G = ox.graph_from_place(distrito, network_type='all_private')
hospitals = ox.pois_from_place(city, amenities=['hospital'])

coord_1 = (38.74817825481225, -9.160815118526642)
coord_2 = (38.74110711410615, -9.152159572392323)
coord_3 = (38.7287248180068, -9.139114834357233)
target_1 = ox.get_nearest_node(G, coord_1)
target_2 = ox.get_nearest_node(G, coord_2)
target_3 = ox.get_nearest_node(G, coord_3)

nodes, edges = ox.graph_to_gdfs(G, nodes=True, edges=True)  # Transform nodes and edges into Geodataframes

travel_speed = 20  # km/h
meters_per_minute = travel_speed * 1000 / 60

nodes['shortest_route_length_to_target'] = 0
route_lengths = []
list_nodes = []
i = 0
# print(G.edges(data=True))
for u, v, k, data in G.edges(data=True, keys=True):

    data['time'] = data['length'] / meters_per_minute

for node in G.nodes:
    try:
        route_length_1 = nx.shortest_path_length(G, node, target_1, weight='time')
        route_length_2 = nx.shortest_path_length(G, node, target_3, weight='time')
        if route_length_1 < route_length_2:
            route_lengths.append(route_length_1)
            nodes['shortest_route_length_to_target'][node] = route_length_1
            list_nodes.append(node)
        elif route_length_1 > route_length_2:
            route_lengths.append(route_length_2)
            nodes['shortest_route_length_to_target'][node] = route_length_2
            list_nodes.append(node)

    except nx.exception.NetworkXNoPath:
        continue
</code>```

In general up until the for node in G.nodes: the code runs quite fast. It's this for cycle that is taking far too long.

Thank you in advance.

答:
You should profile your code to identify exactly what is slow. With high confidence I would assume that it is not your if conditions within that for loop (though they could be optimized a bit more). It looks like approximately all of your time complexity comes from trying to solve two shortest paths within each for loop run. This is inherently slow.

You could try calculating your shortest paths with something like igraph, which would be faster.

Note also that you do not need to manually calculate edge traversal times as of OSMnx v0.13.0.

Body:
I have written a piece of code however it takes an enormous amount of time to run and I don't know how to make it faster. Can anyone help me?

Here is the code:

import networkx as nx
import matplotlib.pyplot as plt
import osmnx as ox
import pandas as pd
from shapely.wkt import loads as load_wkt
import numpy as np
import matplotlib.cm as cm
ox.config(log_console=True, use_cache=True)
import matplotlib as mpl
import random as rd

distrito = ['Lisbon District', 'Setúbal District']
G = ox.graph_from_place(distrito, network_type='all_private')
hospitals = ox.pois_from_place(city, amenities=['hospital'])

coord_1 = (38.74817825481225, -9.160815118526642)
coord_2 = (38.74110711410615, -9.152159572392323)
coord_3 = (38.7287248180068, -9.139114834357233)
target_1 = ox.get_nearest_node(G, coord_1)
target_2 = ox.get_nearest_node(G, coord_2)
target_3 = ox.get_nearest_node(G, coord_3)

nodes, edges = ox.graph_to_gdfs(G, nodes=True, edges=True)  # Transform nodes and edges into Geodataframes

travel_speed = 20  # km/h
meters_per_minute = travel_speed * 1000 / 60

nodes['shortest_route_length_to_target'] = 0
route_lengths = []
list_nodes = []
i = 0
# print(G.edges(data=True))
for u, v, k, data in G.edges(data=True, keys=True):

    data['time'] = data['length'] / meters_per_minute

for node in G.nodes:
    try:
        route_length_1 = nx.shortest_path_length(G, node, target_1, weight='time')
        route_length_2 = nx.shortest_path_length(G, node, target_3, weight='time')
        if route_length_1 < route_length_2:
            route_lengths.append(route_length_1)
            nodes['shortest_route_length_to_target'][node] = route_length_1
            list_nodes.append(node)
        elif route_length_1 > route_length_2:
            route_lengths.append(route_length_2)
            nodes['shortest_route_length_to_target'][node] = route_length_2
            list_nodes.append(node)

    except nx.exception.NetworkXNoPath:
        continue

In general up until the for node in G.nodes: the code runs quite fast. It's this for cycle that is taking far too long.

Thank you in advance.


来源: stackexchange

问:
Django admin many-to-many reversed?
The answer to question Django admin ManyToMany inline "has no ForeignKey to" error refers to the Django Admin documentation.  The models given there are:

```<code>class Person(models.Model):
    name = models.CharField(max_length=128)

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, related_name='groups')
</code>```

and the inline admin classes are:

```<code>class MembershipInline(admin.TabularInline):
    model = Group.members.through

class PersonAdmin(admin.ModelAdmin):
    inlines = [MembershipInline,]

class GroupAdmin(admin.ModelAdmin):
    inlines = [MembershipInline,]
    exclude = ('members',)
</code>```

... which allows group membership to be managed from the Person page but not from the Group page.  But what if the administrator wants to manage members only from the Group page?  Getting rid of the exclude line would allow both pages to manage the relationship, but the Django documentation (probably incorrectly) says "you must tell Django’s admin to not display this widget".  What they probably mean is that you "should" tell Django's admin not to display it - nothing bad will happen if you don't, but it's redundant.

So without changing the models, is it possible to exclude the membership widget from the Person page instead of from the Group page?  Both obvious attempts:

```<code>class PersonAdmin(admin.ModelAdmin):
    inlines = [MembershipInline,]
    exclude = ('Group.members',)
</code>```

and

```<code>class PersonAdmin(admin.ModelAdmin):
    inlines = [MembershipInline,]
    exclude = ('groups',)
</code>```

(the second using the related_name from the model) fail with the error:

```<code>'PersonAdmin.exclude' refers to field 'groups' that is missing from the form.
</code>```

Yes, the model could be changed to put the ManyToManyField under Person.  But since it is a symmetric relationship, there is no logical reason why it could not be managed from either Person or Group (but not both) without having to change the database schema.  Can Django Admin manage group membership from the group page and exclude it from the person page?

答:
what if the administrator wants to manage members only from the Group
  page?

```<code>@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    pass

@admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
    pass
</code>```

Django by default shows a Person m2m widget in the GroupAdmin. You correctly use the through model to get inlines, but the inlines are a separate definition not affected by the exclude. EDIT: Another simple way to put it is that you only specify the inlines on the Admin where you want them, no need to specify them on the opposite side's Admin.

Using inlines:

```<code>from core.models import Group, Person

class MembershipInline(admin.TabularInline):
    model = Group.members.through

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    pass

@admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
    inlines = [MembershipInline, ]
    exclude = ('members',)
</code>```

(tested on Django 3.0.3)

ContentLicense: CC BY-SA 3.0

Title: Django admin many-to-many reversed?

Body:
The answer to question Django admin ManyToMany inline "has no ForeignKey to" error refers to the Django Admin documentation.  The models given there are:

class Person(models.Model):
    name = models.CharField(max_length=128)

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, related_name='groups')

and the inline admin classes are:

class MembershipInline(admin.TabularInline):
    model = Group.members.through

class PersonAdmin(admin.ModelAdmin):
    inlines = [MembershipInline,]

class GroupAdmin(admin.ModelAdmin):
    inlines = [MembershipInline,]
    exclude = ('members',)

... which allows group membership to be managed from the Person page but not from the Group page.  But what if the administrator wants to manage members only from the Group page?  Getting rid of the exclude line would allow both pages to manage the relationship, but the Django documentation (probably incorrectly) says "you must tell Django’s admin to not display this widget".  What they probably mean is that you "should" tell Django's admin not to display it - nothing bad will happen if you don't, but it's redundant.

So without changing the models, is it possible to exclude the membership widget from the Person page instead of from the Group page?  Both obvious attempts:

class PersonAdmin(admin.ModelAdmin):
    inlines = [MembershipInline,]
    exclude = ('Group.members',)

and

class PersonAdmin(admin.ModelAdmin):
    inlines = [MembershipInline,]
    exclude = ('groups',)

(the second using the related_name from the model) fail with the error:

'PersonAdmin.exclude' refers to field 'groups' that is missing from the form.

Yes, the model could be changed to put the ManyToManyField under Person.  But since it is a symmetric relationship, there is no logical reason why it could not be managed from either Person or Group (but not both) without having to change the database schema.  Can Django Admin manage group membership from the group page and exclude it from the person page?

Body:
what if the administrator wants to manage members only from the Group
  page?

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    pass

@admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
    pass

Django by default shows a Person m2m widget in the GroupAdmin. You correctly use the through model to get inlines, but the inlines are a separate definition not affected by the exclude. EDIT: Another simple way to put it is that you only specify the inlines on the Admin where you want them, no need to specify them on the opposite side's Admin.

Using inlines:

from core.models import Group, Person

class MembershipInline(admin.TabularInline):
    model = Group.members.through

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    pass

@admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
    inlines = [MembershipInline, ]
    exclude = ('members',)

(tested on Django 3.0.3)

ContentLicense: CC BY-SA 4.0


问:
SQL Server: how to construct a IF like system within "where" clause?
I have a table like below after several joins

```<code>username    trandate    positionname       ChannelID
--------    ----        ------------       ---------
system      01/01/2019                     1
anderson    06/04/2019  chief              1
williams    07/03/2019  chief              2
julie       15/02/2019  technician         48
julie       27/05/2019  chief technician   21
</code>```

I want to count total number of transactions, sum of amount grouped by month, year and channel type.

there is a condition: if channelID is equals to "1", then query should exclude (1) transactions with has null value on "positionname" or (2) transactions with "system" username.

My code is something like this below:

```<code>    select DISTINCT

DATEPART(YEAR,a.TranDate) as [year],
DATEPART(MONTH,a.TranDate) as [month],

    count(*) as [transaction number],
    sum(a.Amount) as [Total amount],

    b.Name as [branch name],
    c.ChannelName as [channel]

    from transactions_main as a

left join branches      as b    WITH (NOLOCK) ON a.TranBranch=b.BranchId
left join Channels      as c    WITH (NOLOCK) ON a.ChannelId=c.ChannelId
left join Staff_Info    as d    WITH (NOLOCK) ON a.UserName=d.UserCode

where
        a.TranDate>'20181231'
        and b.name not in ('HQ')
        and (a.ChannelId=1
            and d.positionname is not null
            and a.UserName not in ('SYSTEM', 'auto') )

            group by b.Name, c.ChannelName,DATEPART(YEAR,a.TranDate), DATEPART(MONTH,a.TranDate)

order by b.Name, Year,month
</code>```

In the end, of course, it didnt worked. I got the sum and count of transactions of only channelID=1's.

BONUS: You want to help another topic of mine? in which i also need help about indexing:

determining the staff's title when a certain transaction is done

here it is : link

答:
use an OR operator</p>

```<code>where
        a.TranDate>'20181231'
        and b.name not in ('HQ')
        and (
                (a.ChannelId=1
                and d.positionname is not null
                and a.UserName not in ('SYSTEM', 'auto') )
                )
                OR
                a.ChannelId<>1
            )
</code>```

Body:
I have a table like below after several joins

username    trandate    positionname       ChannelID
--------    ----        ------------       ---------
system      01/01/2019                     1
anderson    06/04/2019  chief              1
williams    07/03/2019  chief              2
julie       15/02/2019  technician         48
julie       27/05/2019  chief technician   21

I want to count total number of transactions, sum of amount grouped by month, year and channel type.

there is a condition: if channelID is equals to "1", then query should exclude (1) transactions with has null value on "positionname" or (2) transactions with "system" username.

My code is something like this below:

    select DISTINCT

DATEPART(YEAR,a.TranDate) as [year],
DATEPART(MONTH,a.TranDate) as [month],

    count(*) as [transaction number],
    sum(a.Amount) as [Total amount],

    b.Name as [branch name],
    c.ChannelName as [channel]

    from transactions_main as a

left join branches      as b    WITH (NOLOCK) ON a.TranBranch=b.BranchId
left join Channels      as c    WITH (NOLOCK) ON a.ChannelId=c.ChannelId
left join Staff_Info    as d    WITH (NOLOCK) ON a.UserName=d.UserCode

where
        a.TranDate>'20181231'
        and b.name not in ('HQ')
        and (a.ChannelId=1
            and d.positionname is not null
            and a.UserName not in ('SYSTEM', 'auto') )

            group by b.Name, c.ChannelName,DATEPART(YEAR,a.TranDate), DATEPART(MONTH,a.TranDate)

order by b.Name, Year,month

In the end, of course, it didnt worked. I got the sum and count of transactions of only channelID=1's.

BONUS: You want to help another topic of mine? in which i also need help about indexing:

determining the staff's title when a certain transaction is done

here it is : link

Body:
use an OR operator

where
        a.TranDate>'20181231'
        and b.name not in ('HQ')
        and (
                (a.ChannelId=1
                and d.positionname is not null
                and a.UserName not in ('SYSTEM', 'auto') )
                )
                OR
                a.ChannelId<>1
            )


问:
Producer-consumer pattern implementation using semaphores
guys! I know that the producer-consumer pattern can be implemented using the semaphore synchronization primitive. But how many semaphores and on what events are necessary for implementation?</p>

答:
Conceptually, there are three components to the Producer-Consumer Pattern:

One or more producers

One or more consumers

A shared queue of produced objects

The producers generate objects and put them in the queue. The consumers wait until there are objects in the queue to consume and then perform some action with each object. In general, the queue can be considered unbounded (i.e., can store unlimited objects).

At its most basic level, a single, mutually-exclusive (mutex) semaphore is needed that acts as the signal for the queue. This mutex allows only one client to acquire the mutex at a time. The producer creates an object, acquires the mutex, enqueues the object, and then releases the mutex. The consumer acquires the mutex, removes one element from the queue, and then releases the mutex.

The pseudocode for the producer is:

```<code>produce(queue, mutex):
    object := createObject()
    mutex.acquire()
    queue.enqueue(object)
    mutex.release()

consume(queue, mutex):
    mutex.acquire()
    object := queue.pop()
    mutex.release()
    handle(object)
</code>```

This conceptual model becomes more complex when we introduce the idea of a bounded queue (i.e., there is a limit on the number of objects that can be stored in a queue). This requires that we protect the consumers from popping from the queue when there are no objects in the queue and protect the producers from enqueuing when the queue is full.

To accomplish this, we have to introduce the idea of a counting semaphore. We then create two new semaphores:

empty: Initialized with the maximum capacity of the queue

full: Initialized to 0

As a new item is enqueued, the full semaphore is incremented and the empty semaphore is is decremented. The full semaphore tracks how many filled slots there in the queue and the empty semaphore tracks the number of empty slots in the queue. When a producer enqueues a new object, it decrements the empty count and increments the full count. The consumer does the opposite when popping from the queue.

For the bounded use case, pseudocode becomes:

```<code>produce(queue, mutex, full, empty):

    object := createObject()

    empty.decrement()
    mutex.acquire()

    queue.enqueue(object)

    mutex.release()
    full.increment()

consume(queue, mutex, full, empty):

    full.decrement()
    mutex.acquire()

    object := queue.pop()

    mutex.release()
    empty.increment()

    handle(object)
</code>```

Body:
Conceptually, there are three components to the Producer-Consumer Pattern:

One or more producers

One or more consumers

A shared queue of produced objects

The producers generate objects and put them in the queue. The consumers wait until there are objects in the queue to consume and then perform some action with each object. In general, the queue can be considered unbounded (i.e., can store unlimited objects).

At its most basic level, a single, mutually-exclusive (mutex) semaphore is needed that acts as the signal for the queue. This mutex allows only one client to acquire the mutex at a time. The producer creates an object, acquires the mutex, enqueues the object, and then releases the mutex. The consumer acquires the mutex, removes one element from the queue, and then releases the mutex.

The pseudocode for the producer is:

produce(queue, mutex):
    object := createObject()
    mutex.acquire()
    queue.enqueue(object)
    mutex.release()

consume(queue, mutex):
    mutex.acquire()
    object := queue.pop()
    mutex.release()
    handle(object)

This conceptual model becomes more complex when we introduce the idea of a bounded queue (i.e., there is a limit on the number of objects that can be stored in a queue). This requires that we protect the consumers from popping from the queue when there are no objects in the queue and protect the producers from enqueuing when the queue is full.

To accomplish this, we have to introduce the idea of a counting semaphore. We then create two new semaphores:

empty: Initialized with the maximum capacity of the queue

full: Initialized to 0

As a new item is enqueued, the full semaphore is incremented and the empty semaphore is is decremented. The full semaphore tracks how many filled slots there in the queue and the empty semaphore tracks the number of empty slots in the queue. When a producer enqueues a new object, it decrements the empty count and increments the full count. The consumer does the opposite when popping from the queue.

For the bounded use case, pseudocode becomes:

produce(queue, mutex, full, empty):

    object := createObject()

    empty.decrement()
    mutex.acquire()

    queue.enqueue(object)

    mutex.release()
    full.increment()

consume(queue, mutex, full, empty):

    full.decrement()
    mutex.acquire()

    object := queue.pop()

    mutex.release()
    empty.increment()

    handle(object)


问:
getting "AttributeError: 'list' object has no attribute 'val' " while compareing binary tree in python
I am trying to compare two binary tree p and q but  continuosly an error is raised saying "AttributeError: 'list' object has no attribute 'val'". I am not able to get over the error.
Can you please help me in resolving the issue and improve my understanding please?
Please find the code below:

```<code># Definition for a binary tree node.

p = [1,2,3]
q = [1,2,3]
class TreeNode(object):
    def __init__(self, v=0, l=None, r=None):
            self.val = v
            self.left = l
            self.right = r

    def compareBinaryTree(self, p, q):
        stack = [(p, q)]
        while stack:
            node1, node2 = stack.pop()
            print(node1,node2)
            if not node1 and not node2:
                continue
            elif None in [node1, node2]:
                return False
            else:
                if node1.val != node2.val:
                    return False
                stack.append((node1.right, node2.right))
                stack.append((node1.left, node2.left))
        return True
</code>```

Please find below the error which is displayed while running the code:

```<code>>>>TreeNode.compareBinaryTree(t,p,q)

[1, 2, 3] [1, 2, 3]
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-26-1372e5b88a65> in <module>
----> 1 TreeNode.compareBinaryTree(t,p,q)

<ipython-input-23-5eef65d6c59b> in compareBinaryTree(self, p, q)
     18                 return False
     19             else:
---> 20                 if node1.val != node2.val:
     21                     return False
     22                 stack.append((node1.right, node2.right))

**AttributeError: 'list' object has no attribute 'val'**
</code>```

答: p and q seem to be lists and not trees. [1, 2, 3] is a list and I think you mean to pass another instance of TreeNode instead.

Body:
I am trying to compare two binary tree p and q but  continuosly an error is raised saying "AttributeError: 'list' object has no attribute 'val'". I am not able to get over the error.
Can you please help me in resolving the issue and improve my understanding please?
Please find the code below:

# Definition for a binary tree node.

p = [1,2,3]
q = [1,2,3]
class TreeNode(object):
    def __init__(self, v=0, l=None, r=None):
            self.val = v
            self.left = l
            self.right = r

    def compareBinaryTree(self, p, q):
        stack = [(p, q)]
        while stack:
            node1, node2 = stack.pop()
            print(node1,node2)
            if not node1 and not node2:
                continue
            elif None in [node1, node2]:
                return False
            else:
                if node1.val != node2.val:
                    return False
                stack.append((node1.right, node2.right))
                stack.append((node1.left, node2.left))
        return True

Please find below the error which is displayed while running the code:

>>>TreeNode.compareBinaryTree(t,p,q)

[1, 2, 3] [1, 2, 3]
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-26-1372e5b88a65> in <module>
----> 1 TreeNode.compareBinaryTree(t,p,q)

<ipython-input-23-5eef65d6c59b> in compareBinaryTree(self, p, q)
     18                 return False
     19             else:
---> 20                 if node1.val != node2.val:
     21                     return False
     22                 stack.append((node1.right, node2.right))

**AttributeError: 'list' object has no attribute 'val'**


问:
Get the count of distinct userids for last couple of days
Let's say the last 7 days for this table:

```<code>Userid   Download time
Rab01    2020-04-29 03:28
Klm01    2020-04-29 04:01
Klm01    2020-04-30 05:10
Rab01    2020-04-29 12:14
Osa_3    2020-04-25 09:01
</code>```

Following is the required output:

```<code>Count  Download_time
1      2020-04-25
2      2020-04-29
1      2020-04-30
</code>```

答:
Tested with PostgreSQL. You also tagged Redshift, which forked at Postgres 8.2, a long time ago. There may be discrepancies ..

Since you seem to be happy with standard ISO format, a simple cast to date would be most efficient:

```<code>SELECT count(DISTINCT userid) AS "Count"
     , download_time::date AS "Download_Day"
FROM   tbl
WHERE  download_time >= CURRENT_DATE - 7
AND    download_time <  CURRENT_DATE
GROUP  BY 2;
</code>```

db<>fiddle here

CURRENT_DATE is standard SQL and works for both Postgres and Redshift. Related:

How do I determine the last day of the previous month using PostgreSQL?

About the "last 7 days": I took the last 7 whole days (excluding today - necessarily incomplete), with syntax that can use a plain index on (download_time). Related:

Get dates of a day of week in a date range

Slow LEFT JOIN on CTE with time intervals

Interval (days) in PostgreSQL with two parameters

Ideally, you have a composite index on (download_time, userid) (and fulfill some preconditions) to get very fast index-only scans. See:

Is a composite index also good for queries on the first field?

count(DISTINCT ...) is typically slow. For big tables with many duplicates, there are faster techniques. Disclose your exact setup and cardinalities if you need to optimize performance.

If the actual data type is timestamptz, not just timestamp, you also need to define the time zone defining day boundaries. See:

Ignoring time zones altogether in Rails and PostgreSQL

About the optional short syntax GROUP BY 2:

Select first row in each GROUP BY group?

About capitalization of identifiers:

Are PostgreSQL column names case-sensitive?

Body:
Let's say the last 7 days for this table:

Userid   Download time
Rab01    2020-04-29 03:28
Klm01    2020-04-29 04:01
Klm01    2020-04-30 05:10
Rab01    2020-04-29 12:14
Osa_3    2020-04-25 09:01

Following is the required output:

Count  Download_time
1      2020-04-25
2      2020-04-29
1      2020-04-30

Body:
Tested with PostgreSQL. You also tagged Redshift, which forked at Postgres 8.2, a long time ago. There may be discrepancies ..

Since you seem to be happy with standard ISO format, a simple cast to date would be most efficient:

SELECT count(DISTINCT userid) AS "Count"
     , download_time::date AS "Download_Day"
FROM   tbl
WHERE  download_time >= CURRENT_DATE - 7
AND    download_time <  CURRENT_DATE
GROUP  BY 2;

db<>fiddle here

CURRENT_DATE is standard SQL and works for both Postgres and Redshift. Related:

How do I determine the last day of the previous month using PostgreSQL?

About the "last 7 days": I took the last 7 whole days (excluding today - necessarily incomplete), with syntax that can use a plain index on (download_time). Related:

Get dates of a day of week in a date range

Slow LEFT JOIN on CTE with time intervals

Interval (days) in PostgreSQL with two parameters

Ideally, you have a composite index on (download_time, userid) (and fulfill some preconditions) to get very fast index-only scans. See:

Is a composite index also good for queries on the first field?

count(DISTINCT ...) is typically slow. For big tables with many duplicates, there are faster techniques. Disclose your exact setup and cardinalities if you need to optimize performance.

If the actual data type is timestamptz, not just timestamp, you also need to define the time zone defining day boundaries. See:

Ignoring time zones altogether in Rails and PostgreSQL

About the optional short syntax GROUP BY 2:

Select first row in each GROUP BY group?

About capitalization of identifiers:

Are PostgreSQL column names case-sensitive?


问:
How to constrain Interface generic to only string or object or null?

export interface Foo<T extends string | object | null> {
  bar: T;
}

type Callback<T = any> = (res: T) => void

function hydra<T extends string | object | null>(callback: Callback<Foo<T>>) {
    callback({
        bar: 'Hello World'
    });
}

```

<p>I doesn't work. It throws this error:</p>

<pre class="lang-js prettyprint-override"><code>Type '"Hello World"' is not assignable to type 'T'.
  '"Hello World"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | object | null'.
</code>```

Playground Link

How can I solve this issue?

答:
The main problem here is, although the literal Hello World is assignable to a string, the fact of having a generic argument (as a constraint) relies on having possibly a subtype of string which Hello World would not satisfy.

Suppose this scenario

```<code>type StringSubtype = 'Not Hello World';
hydra<StringSubtype>(res => {
    // ...
});
</code>```

The generic argument of the function hydra is now a subset of string. And, indeed, it satisfies the extends string | object | null constraint. All valid.

But, res.bar is of type 'Not Hello World' which means not other string value can match the type.

```<code>hydra<StringSubtype>(res => {
    // ...

    // Type '"Hello World"' is not assignable to type '"Not Hello World"'
    res = {
        bar: `Hello World`
    };
});
</code>```

This is what your compilation error says

Type '"Hello World"' is not assignable to type 'T'.
    '"Hello World"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | object | null'.

Even if Hello World is assignable to string, the compiler does not guarantee that T could be a subtype of string.

Solution

Simply don't declare your hydra function as generic. Use the more flexible union type as a type argument of Foo<> directly.

```<code>function hydra(callback: Callback<Foo<string | object | null>>) {
    callback({
        bar: 'Hello World'
    });
}
</code>```

EDIT: Alternative solutions

Force casting Hello World as T

```<code>function hydra<T extends string | object | null>(callback: Callback<Foo<T>>) {
    callback({
        bar: 'Hello World' as unknown as T
    });
}
</code>```

Union the T with the forced value

```<code>function hydra<T extends string | object | null>(callback: Callback<Foo<T | 'Hello World'>>) {
    callback({
        bar: 'Hello World'
    });
}
</code>```

But, deeply enough, if you are forcing a value to res.bar, there's no reason to have any generic argument.

However, your example is a sample and I guess there should be a reason for this... I hope any of these three workarounds matches with your intention.

I explained what the error was, at least. So you can achieve what you need with this knowledge, I guess.

Hope it helps.

Body:
export interface Foo<T extends string | object | null> {
  bar: T;
}

type Callback<T = any> = (res: T) => void

function hydra<T extends string | object | null>(callback: Callback<Foo<T>>) {
    callback({
        bar: 'Hello World'
    });
}

I doesn't work. It throws this error:

Type '"Hello World"' is not assignable to type 'T'.
  '"Hello World"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | object | null'.

Playground Link

How can I solve this issue?

Body:
The main problem here is, although the literal Hello World is assignable to a string, the fact of having a generic argument (as a constraint) relies on having possibly a subtype of string which Hello World would not satisfy.

Suppose this scenario

type StringSubtype = 'Not Hello World';
hydra<StringSubtype>(res => {
    // ...
});

The generic argument of the function hydra is now a subset of string. And, indeed, it satisfies the extends string | object | null constraint. All valid.

But, res.bar is of type 'Not Hello World' which means not other string value can match the type.

hydra<StringSubtype>(res => {
    // ...

    // Type '"Hello World"' is not assignable to type '"Not Hello World"'
    res = {
        bar: `Hello World`
    };
});

This is what your compilation error says

Type '"Hello World"' is not assignable to type 'T'.
    '"Hello World"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | object | null'.

Even if Hello World is assignable to string, the compiler does not guarantee that T could be a subtype of string.

Solution

Simply don't declare your hydra function as generic. Use the more flexible union type as a type argument of Foo<> directly.

function hydra(callback: Callback<Foo<string | object | null>>) {
    callback({
        bar: 'Hello World'
    });
}

EDIT: Alternative solutions

Force casting Hello World as T

function hydra<T extends string | object | null>(callback: Callback<Foo<T>>) {
    callback({
        bar: 'Hello World' as unknown as T
    });
}

Union the T with the forced value

function hydra<T extends string | object | null>(callback: Callback<Foo<T | 'Hello World'>>) {
    callback({
        bar: 'Hello World'
    });
}

But, deeply enough, if you are forcing a value to res.bar, there's no reason to have any generic argument.

However, your example is a sample and I guess there should be a reason for this... I hope any of these three workarounds matches with your intention.

I explained what the error was, at least. So you can achieve what you need with this knowledge, I guess.

Hope it helps.


问:
How to display data from a nested JSON response into table in ReactJS
React newbie here; I have a table which displays the simple JSON response I get from my backend. But, I am not able to display some nested properties I have for each item.

What I Tried

I am not sure if I need to use .map function or run a loop, or use any accessor. I have a table filled with a JSON response, but it needs to have another row with the correct nested data being displayed for each row.
The data is being sent just fine. I think I am not able to parse it.

My Code

```<code>const dispatchPlanColumns = [
  {
    dataField: "id",
    text: "ID",
    sort: true
  },
  {
    dataField: "name",
    text: "Truck",
    sort: true,
    isDummyField: true,
    formatter: (cell, row) => (
      <span>
        {row.truck_type} {row.truck_name}
      </span>
    )
  },
  {
    dataField: "total_trucks",
    text: "NO. of trucks",
    sort: true
  },
  {
    dataField: "weight",
    text: "Weight",
    sort: true
  },
  {
    dataField: "percent_filled",
    text: "Volume utilisation",
    sort: true
  },
  {
    dataField: "origin",
    text: "Route",
    isDummyField: true,
    formatter: (cell, row) => (
      <span>
        {row.origin} -> {row.destination}
      </span>
    )
  },
  {
    dataField: "distance",
    text: "Route Distance",
    sort: true
  },
  {
    dataField: "route_tat",
    text: "Date",
    sort: true
  },
  {
    dataField: "time",
    text: "Dispatch Time",
    sort: true
  },
  {
    dataField: "Action",
    text: "Action",
    sort: true,
    formatter: (row, cell) => <Button color="primary">Raise RFQ</Button>
  }
];

const dispatchListColumns = [
  {
    dataField: "id",
    text: "SKU ID",
    sort: true
  },
  {
    dataField: "name",
    text: "Name",
    sort: true
  },
  {
    dataField: "quantity",
    text: "Quantity",
    sort: true
  },
  {
    dataField: "weight",
    text: "Weight",
    sort: true
  }
];

const LoadingPlan = ({ row }) => {
  const [plan, setPlan] = useState([]);

  useEffect(() => {
    const getNetwork = async () => {
      const data = await getDispatchHistory();
      const plan = await getDispatchHistory();
      setPlan(data);
      setPlan(plan);
    };

    getNetwork();
  }, [setPlan]);

  return (
    <div
      className={"animated slideInDown lightSpeedIn"}
      style={{ marginBottom: 60, marginTop: 20 }}
    >
      <Row>
        <Col lg={7}>
          <DataTable columns={dispatchListColumns} data={plan} />
        </Col>
        <Col lg={4}>
          <DispatchMapWrapper />
        </Col>
      </Row>
    </div>
  );
};

const expandRow = row => <LoadingPlan row={row} />;

export default props => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const getNetwork = async () => {
      const data = await getDispatchHistory();
      setData(data);
    };

    getNetwork();
  }, [setData]);

  return (
    <Row>
      <Col lg={12}>
        <Card>
          <CardHeader>
            <b>Dispatch Plan</b>
          </CardHeader>

          <CardBody>
            <DataTable
              columns={dispatchPlanColumns}
              data={data}
              expandRow={{ renderer: expandRow }}
            />
          </CardBody>
        </Card>
      </Col>
    </Row>
  );
};
</code>```

This is the data

```<code>let data = [
  {
    id: 11,
    truck_name: "20 ft sxl 7 Ton",
    truck_type: "Container",
    items: [
      {
        id: "10",
        name: "Coupling",
        pid: 6,
        quantity: 2,
        length: 5.0,
        width: 4.0,
        height: 3.0,
        volume: 60.0,
        weight: 650.0,
        truck_type: "Container",
        origin: "Delhi",
        date: "2019-09-20T12:00:00",
        destination: "Gaya",
        time: "2019-08-01T17:09:06.106859",
        rtd: false,
        is_dispatched: false,
        uploaded_by: 1
      }
    ],
    comments: "Autogenerated",
    origin: "Delhi",
    destination: "Gaya",
    total_trucks: 1,
    material_type: "Non-Fragile",
    scheduled_date: "2019-09-20T12:00:00",
    offered_price: 0,
    weight: 6500,
    status: "Hold",
    created_on: "2019-08-13T10:06:40.761801",
    route_distance: 1088.821,
    route_tat: "19 Hours 27 Minutes",
    etd: "2019-08-15T14:39:32.261802",
    eta: "2019-09-20T12:00:00",
    route_link:
      "https://www.google.com/maps/embed/v1/directions?&key=AIzaSyBa6popp4h4-uNP98vV_-qhI9-GdHg1uQ8&origin=Delhi&destination=Gaya&mode=driving&language=en",
    percent_filled: "92.85714285714286",
    owner: 1
  },
  {
    id: 12,
    truck_name: "20 ft sxl 6 Ton",
    truck_type: "Container",
    items: [
      {
        id: "7",
        name: "Cover Shaft",
        pid: 3,
        quantity: 2,
        length: 3.0,
        width: 3.0,
        height: 4.0,
        volume: 36.0,
        weight: 500.0,
        truck_type: "Container",
        origin: "Delhi",
        date: "2019-08-10T12:00:00",
        destination: "Kalyan-Dombivli",
        time: "2019-08-01T17:09:05.898876",
        rtd: false,
        is_dispatched: false,
        uploaded_by: 1
      },
      {
        id: "7",
        name: "Cover Shaft",
        pid: 3,
        quantity: 2,
        length: 3.0,
        width: 3.0,
        height: 4.0,
        volume: 36.0,
        weight: 500.0,
        truck_type: "Container",
        origin: "Delhi",
        date: "2019-08-10T12:00:00",
        destination: "Kalyan-Dombivli",
        time: "2019-08-01T17:09:05.898876",
        rtd: false,
        is_dispatched: false,
        uploaded_by: 1
      }
    ]
  }
];
</code>```

These are some routes info, and the nested item's info within each route. I am not able to display the item's info.

答:
Following your code, I have found this issue:

      const data = await getDispatchHistory();
      const plan = await getDispatchHistory();
      setPlan(data);
      setPlan(plan);
```

Are you fetching and setting the state twice? Could this be the problem?

Body:
React newbie here; I have a table which displays the simple JSON response I get from my backend. But, I am not able to display some nested properties I have for each item.

What I Tried

I am not sure if I need to use .map function or run a loop, or use any accessor. I have a table filled with a JSON response, but it needs to have another row with the correct nested data being displayed for each row.
The data is being sent just fine. I think I am not able to parse it.

My Code

const dispatchPlanColumns = [
  {
    dataField: "id",
    text: "ID",
    sort: true
  },
  {
    dataField: "name",
    text: "Truck",
    sort: true,
    isDummyField: true,
    formatter: (cell, row) => (

        {row.truck_type} {row.truck_name}

    )
  },
  {
    dataField: "total_trucks",
    text: "NO. of trucks",
    sort: true
  },
  {
    dataField: "weight",
    text: "Weight",
    sort: true
  },
  {
    dataField: "percent_filled",
    text: "Volume utilisation",
    sort: true
  },
  {
    dataField: "origin",
    text: "Route",
    isDummyField: true,
    formatter: (cell, row) => (

        {row.origin} -> {row.destination}

    )
  },
  {
    dataField: "distance",
    text: "Route Distance",
    sort: true
  },
  {
    dataField: "route_tat",
    text: "Date",
    sort: true
  },
  {
    dataField: "time",
    text: "Dispatch Time",
    sort: true
  },
  {
    dataField: "Action",
    text: "Action",
    sort: true,
    formatter: (row, cell) => <Button color="primary">Raise RFQ</Button>
  }
];

const dispatchListColumns = [
  {
    dataField: "id",
    text: "SKU ID",
    sort: true
  },
  {
    dataField: "name",
    text: "Name",
    sort: true
  },
  {
    dataField: "quantity",
    text: "Quantity",
    sort: true
  },
  {
    dataField: "weight",
    text: "Weight",
    sort: true
  }
];

const LoadingPlan = ({ row }) => {
  const [plan, setPlan] = useState([]);

  useEffect(() => {
    const getNetwork = async () => {
      const data = await getDispatchHistory();
      const plan = await getDispatchHistory();
      setPlan(data);
      setPlan(plan);
    };

    getNetwork();
  }, [setPlan]);

  return (

      <Row>
        <Col lg={7}>
          <DataTable columns={dispatchListColumns} data={plan} />
        </Col>
        <Col lg={4}>
          <DispatchMapWrapper />
        </Col>
      </Row>

  );
};

const expandRow = row => <LoadingPlan row={row} />;

export default props => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const getNetwork = async () => {
      const data = await getDispatchHistory();
      setData(data);
    };

    getNetwork();
  }, [setData]);

  return (
    <Row>
      <Col lg={12}>
        <Card>
          <CardHeader>
            Dispatch Plan
          </CardHeader>

          <CardBody>
            <DataTable
              columns={dispatchPlanColumns}
              data={data}
              expandRow={{ renderer: expandRow }}
            />
          </CardBody>
        </Card>
      </Col>
    </Row>
  );
};

This is the data

let data = [
  {
    id: 11,
    truck_name: "20 ft sxl 7 Ton",
    truck_type: "Container",
    items: [
      {
        id: "10",
        name: "Coupling",
        pid: 6,
        quantity: 2,
        length: 5.0,
        width: 4.0,
        height: 3.0,
        volume: 60.0,
        weight: 650.0,
        truck_type: "Container",
        origin: "Delhi",
        date: "2019-09-20T12:00:00",
        destination: "Gaya",
        time: "2019-08-01T17:09:06.106859",
        rtd: false,
        is_dispatched: false,
        uploaded_by: 1
      }
    ],
    comments: "Autogenerated",
    origin: "Delhi",
    destination: "Gaya",
    total_trucks: 1,
    material_type: "Non-Fragile",
    scheduled_date: "2019-09-20T12:00:00",
    offered_price: 0,
    weight: 6500,
    status: "Hold",
    created_on: "2019-08-13T10:06:40.761801",
    route_distance: 1088.821,
    route_tat: "19 Hours 27 Minutes",
    etd: "2019-08-15T14:39:32.261802",
    eta: "2019-09-20T12:00:00",
    route_link:
      "https://www.google.com/maps/embed/v1/directions?&key=AIzaSyBa6popp4h4-uNP98vV_-qhI9-GdHg1uQ8&origin=Delhi&destination=Gaya&mode=driving&language=en",
    percent_filled: "92.85714285714286",
    owner: 1
  },
  {
    id: 12,
    truck_name: "20 ft sxl 6 Ton",
    truck_type: "Container",
    items: [
      {
        id: "7",
        name: "Cover Shaft",
        pid: 3,
        quantity: 2,
        length: 3.0,
        width: 3.0,
        height: 4.0,
        volume: 36.0,
        weight: 500.0,
        truck_type: "Container",
        origin: "Delhi",
        date: "2019-08-10T12:00:00",
        destination: "Kalyan-Dombivli",
        time: "2019-08-01T17:09:05.898876",
        rtd: false,
        is_dispatched: false,
        uploaded_by: 1
      },
      {
        id: "7",
        name: "Cover Shaft",
        pid: 3,
        quantity: 2,
        length: 3.0,
        width: 3.0,
        height: 4.0,
        volume: 36.0,
        weight: 500.0,
        truck_type: "Container",
        origin: "Delhi",
        date: "2019-08-10T12:00:00",
        destination: "Kalyan-Dombivli",
        time: "2019-08-01T17:09:05.898876",
        rtd: false,
        is_dispatched: false,
        uploaded_by: 1
      }
    ]
  }
];

These are some routes info, and the nested item's info within each route. I am not able to display the item's info.

Body:
Following your code, I have found this issue:

      const data = await getDispatchHistory();
      const plan = await getDispatchHistory();
      setPlan(data);
      setPlan(plan);

Are you fetching and setting the state twice? Could this be the problem?


问:
Is it possible to setText for an Edittext for a long data type element in android
Is it possible to setText for an Edittext view for a long data type element in android XML? I know that setText can take integer but it is not accepting any long data type. So how can I write a long variable in an Edittext without converting it to integer?</p>

答: setText with int type parameter exist to put string resource into TextView. If you put just a some random in you will have an exception that will say to you that string with such id doesn't exist. To put number by setText method you have to convert it to string as Levan mentioned.


问:
how to change bootstrap datepicker month view to display quarters
I have an application where i have to submit monthly reports and quarterly reports. I am using the bootstrap-datepicker for the monthly report, and I want to keep the same standarts in my application therefore it would be great if I avoid using a select box to display quarters.
This is what bootstrap offers when you are in month view mode

And this is what I want to do

When it's selected, all 3 months of the quarter will be selected.

I checked the bootstrap-datepicker.js file and i only saw the table generation code which was:

```<code>DPGlobal.template = '<div class="datepicker">'+
                        '<div class="datepicker-days">'+
                            '<table class=" table-condensed">'+
                                DPGlobal.headTemplate+
                                '<tbody></tbody>'+
                                DPGlobal.footTemplate+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-months">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                                DPGlobal.footTemplate+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-years">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                                DPGlobal.footTemplate+
                            '</table>'+
                        '</div>'+
                    '</div>';
</code>```

and in the DPGlobal variable were the templates:

```<code>headTemplate: '<thead>'+
                        '<tr>'+
                            '<th class="prev">«</th>'+
                            '<th colspan="5" class="datepicker-switch"></th>'+
                            '<th class="next">»</th>'+
                        '</tr>'+
                    '</thead>',
    contTemplate: '<tbody><tr><td colspan="9"></td></tr></tbody>',
    footTemplate: '<tfoot>'+
                        '<tr>'+
                            '<th colspan="7" class="today"></th>'+
                        '</tr>'+
                        '<tr>'+
                            '<th colspan="7" class="clear"></th>'+
                        '</tr>'+
                    '</tfoot>'
</code>```

All the help is appreciated

答:
a litte improvement and fix a issue when changing quarter typing in the input.

remove

```<code>.on("show", function(event) {
  $(".month").each(function(index, element) {
  if (index > 3) $(element).hide();
  });
 });
</code>```

add css

```<code> .datepicker-months table tbody tr td span:nth-child(1n + 5) {
 background: red;
 display: none;
 }
</code>```

Body:
I have an application where i have to submit monthly reports and quarterly reports. I am using the bootstrap-datepicker for the monthly report, and I want to keep the same standarts in my application therefore it would be great if I avoid using a select box to display quarters.
This is what bootstrap offers when you are in month view mode

And this is what I want to do

When it's selected, all 3 months of the quarter will be selected.

I checked the bootstrap-datepicker.js file and i only saw the table generation code which was:

DPGlobal.template = '
'+
                        '
'+
                            '
'+
                                DPGlobal.headTemplate+
                                '

'+
                                DPGlobal.footTemplate+
                            '
'+
                        '
'+
                        '
'+
                            '
'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                                DPGlobal.footTemplate+
                            '
'+
                        '
'+
                        '
'+
                            '
'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                                DPGlobal.footTemplate+
                            '
'+
                        '
'+
                    '
';

and in the DPGlobal variable were the templates:

headTemplate: '
'+
                        '
'+
                            '«	'+
                            '	'+
                            '»	'+
                        '
'+
                    '
',
    contTemplate: '

',
    footTemplate: '
'+
                        '
'+
                            '	'+
                        '
'+
                        '
'+
                            '	'+
                        '
'+
                    '
'

All the help is appreciated

Body:
a litte improvement and fix a issue when changing quarter typing in the input.

remove

.on("show", function(event) {
  $(".month").each(function(index, element) {
  if (index > 3) $(element).hide();
  });
 });

add css

 .datepicker-months table tbody tr td span:nth-child(1n + 5) {
 background: red;
 display: none;
 }


问:
How to check if pyodbc cursor is empty?
using pyodbc to query a MySQL database with SELECT. I need to determine if the query returned anything or not, the way I found that people were using is the rowcount, however this always returns -1 for me after some testing. I found this on the github wiki for cursor which I think describes my problem.

rowcount
The number of rows modified by the last SQL statement.

This is -1 if no SQL has been executed or if the number of rows is unknown. Note that it is not uncommon for databases to report -1 immediately after a SQL select statement for performance reasons. (The exact number may not be known before the first records are returned to the application.)

I am wondering if either there is a way around this or if there is another way to do it, thanks.

答:
I always check the length of the return results

res=newcursor.fetchall()

if len(res)==0:##means no results

Title: How to check if pyodbc cursor is empty?


问:
Getting owner of file from smb share, by using python on linux
I need to find out for a script I'm writing who is the true owner of a file in an smb share (mounted using mount -t cifs of course on my server and using net use through windows machines).

Turns out it is a real challenge finding this information out using python on a linux server.

I tried using many many smb libraries (such as smbprotocol, smbclient and others), nothing worked.

I find few solutions for windows, they all use pywin32 or another windows specific package.

And I also managed to do it from bash using smbcalcs but couldn't do it cleanly but using subprocess.popen('smbcacls')..

Any idea on how to solve it?

答:
This was unbelievably not a trivial task, and unfortunately the answer isn't simple as I hoped it would be..

I'm posting this answer if someone will be stuck with this same problem in the future, but hope maybe someone would post a better solution earlier

In order to find the owner I used this library with its examples:

from smb.SMBConnection import SMBConnection

conn = SMBConnection(username='<username>', password='<password>', domain=<domain>', my_name='<some pc name>', remote_name='<server name>')
conn.connect('<server name>')

sec_att = conn.getSecurity('<share name>', r'\some\file\path')
owner_sid = sec_att.owner
```

<p>The problem is that <code>pysmb</code> package will only give you the owner's SID and not his name.<br>
In order to get his name you need to make an ldap query like in this answer (reposting the code):</p>

<pre class="lang-py prettyprint-override"><code>from ldap3 import Server, Connection, ALL
from ldap3.utils.conv import escape_bytes

s = Server('my_server', get_info=ALL)
c = Connection(s, 'my_user', 'my_password')
c.bind()

binary_sid = b'....'  # your sid must be in binary format

c.search('my_base', '(objectsid=' + escape_bytes(binary_sid) + ')', attributes=['objectsid', 'samaccountname'])
print(c.entries)
</code>```

But of course nothing will be easy, it took me hours to find a way to convert a string SID to binary SID in python, and in the end this solved it:

# posting the needed functions and omitting the class part
def byte(strsid):
    '''
    Convert a SID into bytes
        strdsid - SID to convert into bytes
    '''
    sid = str.split(strsid, '-')
    ret = bytearray()
    sid.remove('S')
    for i in range(len(sid)):
        sid[i] = int(sid[i])
    sid.insert(1, len(sid)-2)
    ret += longToByte(sid[0], size=1)
    ret += longToByte(sid[1], size=1)
    ret += longToByte(sid[2], False, 6)
    for i in range(3, len(sid)):
        ret += cls.longToByte(sid[i])
    return ret

def byteToLong(byte, little_endian=True):
    '''
    Convert bytes into a Python integer
        byte - bytes to convert
        little_endian - True (default) or False for little or big endian
    '''
    if len(byte) > 8:
        raise Exception('Bytes too long. Needs to be <= 8 or 64bit')
    else:
        if little_endian:
            a = byte.ljust(8, b'\x00')
            return struct.unpack('<q', a)[0]
        else:
            a = byte.rjust(8, b'\x00')
            return struct.unpack('>q', a)[0]
```

... AND finally you have the full solution! enjoy :(

Body:
This was unbelievably not a trivial task, and unfortunately the answer isn't simple as I hoped it would be..

I'm posting this answer if someone will be stuck with this same problem in the future, but hope maybe someone would post a better solution earlier

In order to find the owner I used this library with its examples:

from smb.SMBConnection import SMBConnection

conn = SMBConnection(username='<username>', password='<password>', domain=<domain>', my_name='<some pc name>', remote_name='<server name>')
conn.connect('<server name>')

sec_att = conn.getSecurity('<share name>', r'\some\file\path')
owner_sid = sec_att.owner

The problem is that pysmb package will only give you the owner's SID and not his name.

In order to get his name you need to make an ldap query like in this answer (reposting the code):

from ldap3 import Server, Connection, ALL
from ldap3.utils.conv import escape_bytes

s = Server('my_server', get_info=ALL)
c = Connection(s, 'my_user', 'my_password')
c.bind()

binary_sid = b'....'  # your sid must be in binary format

c.search('my_base', '(objectsid=' + escape_bytes(binary_sid) + ')', attributes=['objectsid', 'samaccountname'])
print(c.entries)

But of course nothing will be easy, it took me hours to find a way to convert a string SID to binary SID in python, and in the end this solved it:

# posting the needed functions and omitting the class part
def byte(strsid):
    '''
    Convert a SID into bytes
        strdsid - SID to convert into bytes
    '''
    sid = str.split(strsid, '-')
    ret = bytearray()
    sid.remove('S')
    for i in range(len(sid)):
        sid[i] = int(sid[i])
    sid.insert(1, len(sid)-2)
    ret += longToByte(sid[0], size=1)
    ret += longToByte(sid[1], size=1)
    ret += longToByte(sid[2], False, 6)
    for i in range(3, len(sid)):
        ret += cls.longToByte(sid[i])
    return ret

def byteToLong(byte, little_endian=True):
    '''
    Convert bytes into a Python integer
        byte - bytes to convert
        little_endian - True (default) or False for little or big endian
    '''
    if len(byte) > 8:
        raise Exception('Bytes too long. Needs to be <= 8 or 64bit')
    else:
        if little_endian:
            a = byte.ljust(8, b'\x00')
            return struct.unpack('<q', a)[0]
        else:
            a = byte.rjust(8, b'\x00')
            return struct.unpack('>q', a)[0]

... AND finally you have the full solution! enjoy :(


问:
How can I disable highlighting in html or JS?
I need to disable the highlighting of selected text on my web app. I have a good reason for doing this and know that this is generally a bad idea. But I need to do it anyway. It doesn't matter if I need to use CSS or JS to do it. What I'm mainly going for is the removal of the blue color given to highlighted elements.</p>

答:
I just used * to disable highlighting or outline highlight for all elements

```<code>*{
 outline: none;
}
</code>```

answer reference: How to remove focus border (outline) around text/input boxes? (Chrome)

Body:
I just used * to disable highlighting or outline highlight for all elements

*{
 outline: none;
}

answer reference: How to remove focus border (outline) around text/input boxes? (Chrome)


问:
show user an error in net core web app in the try catch block
I have a controller that posts a new game to the server via an API.

That part works, but some reason my email is failing and I want to show the user the error.

So I tried putting a Response.Write in my catch statement like below.

But it can't find a definition for both 'Response.Write' or 'Server'.

How would I go about adding these?

Thanks!

```<code>   [HttpPost]
    public async Task<ActionResult> ProcessGameForm([FromBody] MakeGame game)
    {

        ' xx post form code

       ' now send email alert
       try
        {
            SendMyEmail(game.Title);

        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + Server.HtmlEncode(ex.ToString()) + "')</script>");
        }

        return Ok();
    }
</code>```

答:
In the spirit of this site and in hopes that you're using that code purely for debugging, I'll answer how exactly to get what you're trying to do working, but man... There is so much wrong with that code!

In .NET Core there are no more in-context Response or Server objects.

You would instead have to do something like:

```<code>await HttpResponseWritingExtensions.WriteAsync(this.Response, "<script>alert('" + HttpUtility.HtmlEncode(ex.ToString()) + "')</script>");
</code>```

Also I think an even easier (and slightly more correct way) would be:

```<code>return Content("<script>alert('" + HttpUtility.HtmlEncode(ex.ToString()) + "');
</code>```

I haven't tested either of the above but it should work.

However, you should really have a proper error page (including for internal use) which will accept an Exception object as the model, and then present that however you want using Razor syntax.

Body:
I have a controller that posts a new game to the server via an API.

That part works, but some reason my email is failing and I want to show the user the error.

So I tried putting a Response.Write in my catch statement like below.

But it can't find a definition for both 'Response.Write' or 'Server'.

How would I go about adding these?

Thanks!

   [HttpPost]
    public async Task<ActionResult> ProcessGameForm([FromBody] MakeGame game)
    {

        ' xx post form code

       ' now send email alert
       try
        {
            SendMyEmail(game.Title);

        }
        catch (Exception ex)
        {
            Response.Write("");
        }

        return Ok();
    }

Body:
In the spirit of this site and in hopes that you're using that code purely for debugging, I'll answer how exactly to get what you're trying to do working, but man... There is so much wrong with that code!

In .NET Core there are no more in-context Response or Server objects.

You would instead have to do something like:

await HttpResponseWritingExtensions.WriteAsync(this.Response, "<script>alert('" + HttpUtility.HtmlEncode(ex.ToString()) + "')</script>");

Also I think an even easier (and slightly more correct way) would be:

return Content("<script>alert('" + HttpUtility.HtmlEncode(ex.ToString()) + "');

I haven't tested either of the above but it should work.

However, you should really have a proper error page (including for internal use) which will accept an Exception object as the model, and then present that however you want using Razor syntax.


问:
Iterate over nested JSON objects and append data to variable
i'm pretty new with JS and i'm struggling a little bit with iterating over a nested JSON object.

I need to grab the value of each nested Node_Subtask_Success in history and save that to a variable I can access later.

The dataset is rather large so I won't add it directly into this post, but i've uploaded it to pastebin here: https://pastebin.com/puZ77V0K

What i've tried so far:

```<code>updateData: function() {
                axios
                .get('http://localhost/api/node/839b6556940b19cf9651d0ff7ed08c1154d42b8ef2ef0bda92ffd188d9c82aa0600504389a10f54429c6f83d8cfd58c3e9be1598a4592f37ddd8cd3b3adb9cba')
                .then((response) => {
                    _.each(response.data, function(node) {
                      for(var num in response.data.history) {
                        console.log(num.Node_Subtask_Success)
                      }
                    });
                })
            },
</code>```

But the above just prints undefined 269 times.

答:
You're looking to iterate over the history array, so you should do that and only that. You don't need multiple iterations here.

updateData: function() {
                axios
                .get('http://localhost/api/node/839b6556940b19cf9651d0ff7ed08c1154d42b8ef2ef0bda92ffd188d9c82aa0600504389a10f54429c6f83d8cfd58c3e9be1598a4592f37ddd8cd3b3adb9cba')
                .then((response) => {
                    _.each(response.data.history, function(node) {
                        console.log(num.Node_Subtask_Success)
                    });
                })
            },
```

<p>If you want to do it using vanilla JavaScript:</p>

<pre class="lang-js prettyprint-override"><code>updateData: function() {
                axios
                .get('http://localhost/api/node/839b6556940b19cf9651d0ff7ed08c1154d42b8ef2ef0bda92ffd188d9c82aa0600504389a10f54429c6f83d8cfd58c3e9be1598a4592f37ddd8cd3b3adb9cba')
                .then((response) => {
                    for(hist in response.data.history) {
                        console.log(hist.Node_Subtask_Success)
                    });
                })
            },
</code>```

Body:
i'm pretty new with JS and i'm struggling a little bit with iterating over a nested JSON object.

I need to grab the value of each nested Node_Subtask_Success in history and save that to a variable I can access later.

The dataset is rather large so I won't add it directly into this post, but i've uploaded it to pastebin here: https://pastebin.com/puZ77V0K

What i've tried so far:

updateData: function() {
                axios
                .get('http://localhost/api/node/839b6556940b19cf9651d0ff7ed08c1154d42b8ef2ef0bda92ffd188d9c82aa0600504389a10f54429c6f83d8cfd58c3e9be1598a4592f37ddd8cd3b3adb9cba')
                .then((response) => {
                    _.each(response.data, function(node) {
                      for(var num in response.data.history) {
                        console.log(num.Node_Subtask_Success)
                      }
                    });
                })
            },

But the above just prints undefined 269 times.

Body:
You're looking to iterate over the history array, so you should do that and only that. You don't need multiple iterations here.

updateData: function() {
                axios
                .get('http://localhost/api/node/839b6556940b19cf9651d0ff7ed08c1154d42b8ef2ef0bda92ffd188d9c82aa0600504389a10f54429c6f83d8cfd58c3e9be1598a4592f37ddd8cd3b3adb9cba')
                .then((response) => {
                    _.each(response.data.history, function(node) {
                        console.log(num.Node_Subtask_Success)
                    });
                })
            },

If you want to do it using vanilla JavaScript:

updateData: function() {
                axios
                .get('http://localhost/api/node/839b6556940b19cf9651d0ff7ed08c1154d42b8ef2ef0bda92ffd188d9c82aa0600504389a10f54429c6f83d8cfd58c3e9be1598a4592f37ddd8cd3b3adb9cba')
                .then((response) => {
                    for(hist in response.data.history) {
                        console.log(hist.Node_Subtask_Success)
                    });
                })
            },


问:
Handle French Characters in Java
I Have a Page where I search for a term and it is displaying perfect. Whatever character type it is.

Now when I have few checkboxes in JSP and I check it and submit. In these checkboxes I have one box name like ABC Farmacéutica Corporation.

When I click on submit button, I am calling a function and will set all parameters to a form and will submit that form. (I tested putting alert for the special character display before submit and it is displaying good).

Now, coming to the Java end, I use Springs Frame work. When I print the term in controller, then it is displayed like ABC FarmacÃ©utica Corporation.

Please help...
Thanks in advance.

EDIT :

Please try this sample Example

```<code>import java.net.*;
class sample{
    public static void main(String[] args){
        try{
            String aaa = "ABC Farmacéutica Corporation";
            String bbb = "ABC FarmacÃ©utica Corporation";

            aaa = URLEncoder.encode(aaa, "UTF-8");
            bbb = URLDecoder.decode(bbb, "UTF-8");

            System.out.println("aaa   "+aaa);
            System.out.println("bbb   "+bbb);

        }catch(Exception e){
            System.out.println(e);
        }
    }
}
</code>```

I am getting output as,

```<code>aaa   PiSA+Farmac%C3%A9utica+Mexicana+Corporativo
bbb   PiSA Farmac├⌐utica Mexicana Corporativo
</code>```

Try to print the string aaa as it is.

答:
This is an encoding problem, and the Ã clearly identify that this is UTF-8 text interpreted as ISO-Latin-1 (or one of its cousins).

Ensure that your JSP-page at the top show that it uses UTF-8 encoding.

Title: Handle French Characters in Java

Body:
I Have a Page where I search for a term and it is displaying perfect. Whatever character type it is.

Now when I have few checkboxes in JSP and I check it and submit. In these checkboxes I have one box name like ABC Farmacéutica Corporation.

When I click on submit button, I am calling a function and will set all parameters to a form and will submit that form. (I tested putting alert for the special character display before submit and it is displaying good).

Now, coming to the Java end, I use Springs Frame work. When I print the term in controller, then it is displayed like ABC FarmacÃ©utica Corporation.

Please help...
Thanks in advance.

EDIT :

Please try this sample Example

import java.net.*;
class sample{
    public static void main(String[] args){
        try{
            String aaa = "ABC Farmacéutica Corporation";
            String bbb = "ABC FarmacÃ©utica Corporation";

            aaa = URLEncoder.encode(aaa, "UTF-8");
            bbb = URLDecoder.decode(bbb, "UTF-8");

            System.out.println("aaa   "+aaa);
            System.out.println("bbb   "+bbb);

        }catch(Exception e){
            System.out.println(e);
        }
    }
}

I am getting output as,

aaa   PiSA+Farmac%C3%A9utica+Mexicana+Corporativo
bbb   PiSA Farmac├⌐utica Mexicana Corporativo

Try to print the string aaa as it is.


问:
Why is changing the background-attatchment from scroll to fixed changing the width of this background-image?
When I change background-attatchment from scroll to fixed it actually changes the dimensions (at least the width) of the background image. Why is this?

#background-image {
                height: 500px;
                width: 500px;
                background-image: url(https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1407523604l/15136531.jpg);
                background-repeat: no-repeat;
                background-size: contain;
                background-attachment: scroll;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="background-image"></div>
<div>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Officia, harum molestias quia tempore doloribus enim rem eius facere inventore sit nostrum totam assumenda, impedit laudantium fugit? Ratione dignissimos dolor sed. Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam iusto mollitia facere, voluptate enim natus. Dolorem accusantium cum voluptatibus quasi minima, laborum enim quisquam maiores iusto esse dolor beatae quam. Lorem, ipsum dolor sit amet consectetur adipisicing elit. Asperiores optio voluptate ipsam maiores corrupti, quidem aut ex enim est deleniti! Rerum laboriosam earum, voluptas possimus animi quae et quis asperiores. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Eaque nobis nesciunt eos fugiat voluptatem natus repudiandae iusto numquam optio, laudantium quia maxime perferendis soluta eligendi fugit esse totam voluptatum hic! Lorem, ipsum dolor sit amet consectetur adipisicing elit. Eaque a, quo cumque nemo velit quidem eveniet? Quae, iusto iste, neque aperiam ut architecto hic rerum necessitatibus recusandae quisquam quo temporibus. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Est perferendis ea nostrum necessitatibus explicabo culpa ipsa fuga natus maxime tempora ex blanditiis harum accusamus qui corporis ullam ducimus, dolorum quae? Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nobis fugit ipsa natus architecto, officia atque ex. Quia, minus illum vitae omnis, incidunt accusamus explicabo voluptatum repudiandae eaque maxime reprehenderit qui. Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure blanditiis ipsam at excepturi assumenda laborum quibusdam tempora quam perferendis ratione, sunt voluptate ducimus, velit distinctio. Hic eaque deleniti quisquam quod. Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum eos eaque cum, consequatur assumenda quam error dolor molestiae labore ex itaque delectus officia animi eius, odio harum, hic voluptatibus ut! Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint voluptas, aperiam excepturi ratione libero, placeat est, saepe quas labore fugit enim architecto voluptatem maxime facere sunt impedit repellat maiores exercitationem? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Architecto placeat, assumenda nulla harum quia officiis ullam facilis eaque dolore magni modi, fugiat quis! Ipsum, facere incidunt voluptates laboriosam id quidem? Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quam eum laboriosam sint animi nisi minima placeat in recusandae amet et iste, asperiores ipsa hic, culpa unde, fugiat voluptatibus! Quos, omnis? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dignissimos beatae tenetur dolores ad temporibus laboriosam repellendus dolorum corporis praesentium quos, possimus obcaecati fugiat reiciendis similique fuga est. Blanditiis, in pariatur. Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laboriosam est temporibus eos beatae. Atque eum tenetur voluptas totam, vero voluptatem in dolorem dolore velit maxime, enim laudantium. Est, facilis corporis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum debitis est similique quis. Cumque iusto repudiandae velit ea repellat dolore sunt expedita ut voluptatibus culpa quam totam vitae, ducimus modi? Lorem ipsum dolor sit amet consectetur adipisicing elit. Quis magni iure numquam sit! Nostrum quia, nemo neque deserunt, ex modi saepe optio ea illo debitis nesciunt officia consequuntur eum repudiandae! Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint adipisci animi minima, porro totam consectetur, ad labore consequatur aspernatur quod, ex tempore aperiam non. Ullam odit dolorem tempore doloremque est. Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus, eligendi? Ea, ab maiores quia error nam esse totam perspiciatis aperiam illo nesciunt voluptates autem at. Ducimus suscipit voluptates libero voluptatibus! Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eaque praesentium laboriosam, ratione, voluptatum error inventore ducimus illo dolorum sed delectus nam dolore est minima velit! Quae praesentium doloremque cumque explicabo. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Laboriosam dicta autem numquam obcaecati? Dolores impedit repellat tempora quas voluptatem aspernatur blanditiis est, eum laborum, aut dolorem, odit magnam inventore corrupti. Lorem ipsum dolor sit amet consectetur adipisicing elit. Exercitationem iusto officia a soluta explicabo quo officiis quos sunt beatae modi. Sunt, maxime ex tenetur adipisci laudantium iure velit ea corrupti! Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt quia deleniti, ipsa excepturi reiciendis reprehenderit at odit inventore, earum perferendis aspernatur, soluta dicta voluptatibus provident tempore saepe animi ratione assumenda. Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugiat, necessitatibus! Explicabo sit culpa perspiciatis id esse quod placeat! Dolore aperiam molestias esse excepturi, voluptate provident neque. A porro minus libero?</div></code>```

答:
From the specification:

If background images are specified, this property specifies whether they are fixed with regard to the viewport (fixed) or scroll along with the element (scroll) or its contents (local). The property’s value is given as a comma-separated list of <attachment> keywords where

So the reference for contain will not more be the element but the viewport when using fixed

To avoid this effect don't use contain but consider auto 500px since you know the dimension of your div:

#background-image {
  height: 500px;
  width: 500px;
  background-image: url(https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1407523604l/15136531.jpg);
  background-repeat: no-repeat;
  background-size: auto 500px;
  background-attachment: fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="background-image"></div>
<div>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Officia, harum molestias quia tempore doloribus enim rem eius facere inventore sit nostrum totam assumenda, impedit laudantium fugit? Ratione dignissimos dolor sed. Lorem ipsum dolor sit amet consectetur
  adipisicing elit. Quisquam iusto mollitia facere, voluptate enim natus. Dolorem accusantium cum voluptatibus quasi minima, laborum enim quisquam maiores iusto esse dolor beatae quam. Lorem, ipsum dolor sit amet consectetur adipisicing elit. Asperiores
  optio voluptate ipsam maiores corrupti, quidem aut ex enim est deleniti! Rerum laboriosam earum, voluptas possimus animi quae et quis asperiores. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Eaque nobis nesciunt eos fugiat voluptatem natus
  repudiandae iusto numquam optio, laudantium quia maxime perferendis soluta eligendi fugit esse totam voluptatum hic! Lorem, ipsum dolor sit amet consectetur adipisicing elit. Eaque a, quo cumque nemo velit quidem eveniet? Quae, iusto iste, neque aperiam
  ut architecto hic rerum necessitatibus recusandae quisquam quo temporibus. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Est perferendis ea nostrum necessitatibus explicabo culpa ipsa fuga natus maxime tempora ex blanditiis harum accusamus
  qui corporis ullam ducimus, dolorum quae? Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nobis fugit ipsa natus architecto, officia atque ex. Quia, minus illum vitae omnis, incidunt accusamus explicabo voluptatum repudiandae eaque maxime
  reprehenderit qui. Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure blanditiis ipsam at excepturi assumenda laborum quibusdam tempora quam perferendis ratione, sunt voluptate ducimus, velit distinctio. Hic eaque deleniti quisquam quod.
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum eos eaque cum, consequatur assumenda quam error dolor molestiae labore ex itaque delectus officia animi eius, odio harum, hic voluptatibus ut! Lorem ipsum dolor sit amet consectetur adipisicing
  elit. Sint voluptas, aperiam excepturi ratione libero, placeat est, saepe quas labore fugit enim architecto voluptatem maxime facere sunt impedit repellat maiores exercitationem? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Architecto placeat,
  assumenda nulla harum quia officiis ullam facilis eaque dolore magni modi, fugiat quis! Ipsum, facere incidunt voluptates laboriosam id quidem? Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quam eum laboriosam sint animi nisi minima placeat
  in recusandae amet et iste, asperiores ipsa hic, culpa unde, fugiat voluptatibus! Quos, omnis? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dignissimos beatae tenetur dolores ad temporibus laboriosam repellendus dolorum corporis praesentium
  quos, possimus obcaecati fugiat reiciendis similique fuga est. Blanditiis, in pariatur. Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laboriosam est temporibus eos beatae. Atque eum tenetur voluptas totam, vero voluptatem in dolorem dolore
  velit maxime, enim laudantium. Est, facilis corporis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum debitis est similique quis. Cumque iusto repudiandae velit ea repellat dolore sunt expedita ut voluptatibus culpa quam totam vitae,
  ducimus modi? Lorem ipsum dolor sit amet consectetur adipisicing elit. Quis magni iure numquam sit! Nostrum quia, nemo neque deserunt, ex modi saepe optio ea illo debitis nesciunt officia consequuntur eum repudiandae! Lorem ipsum dolor sit amet consectetur
  adipisicing elit. Sint adipisci animi minima, porro totam consectetur, ad labore consequatur aspernatur quod, ex tempore aperiam non. Ullam odit dolorem tempore doloremque est. Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus, eligendi?
  Ea, ab maiores quia error nam esse totam perspiciatis aperiam illo nesciunt voluptates autem at. Ducimus suscipit voluptates libero voluptatibus! Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eaque praesentium laboriosam, ratione, voluptatum
  error inventore ducimus illo dolorum sed delectus nam dolore est minima velit! Quae praesentium doloremque cumque explicabo. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Laboriosam dicta autem numquam obcaecati? Dolores impedit repellat
  tempora quas voluptatem aspernatur blanditiis est, eum laborum, aut dolorem, odit magnam inventore corrupti. Lorem ipsum dolor sit amet consectetur adipisicing elit. Exercitationem iusto officia a soluta explicabo quo officiis quos sunt beatae modi.
  Sunt, maxime ex tenetur adipisci laudantium iure velit ea corrupti! Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt quia deleniti, ipsa excepturi reiciendis reprehenderit at odit inventore, earum perferendis aspernatur, soluta dicta
  voluptatibus provident tempore saepe animi ratione assumenda. Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugiat, necessitatibus! Explicabo sit culpa perspiciatis id esse quod placeat! Dolore aperiam molestias esse excepturi, voluptate
  provident neque. A porro minus libero?</div></code>```

Body:
When I change background-attatchment from scroll to fixed it actually changes the dimensions (at least the width) of the background image. Why is this?

#background-image {
                height: 500px;
                width: 500px;
                background-image: url(https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1407523604l/15136531.jpg);
                background-repeat: no-repeat;
                background-size: contain;
                background-attachment: scroll;
}

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Officia, harum molestias quia tempore doloribus enim rem eius facere inventore sit nostrum totam assumenda, impedit laudantium fugit? Ratione dignissimos dolor sed. Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam iusto mollitia facere, voluptate enim natus. Dolorem accusantium cum voluptatibus quasi minima, laborum enim quisquam maiores iusto esse dolor beatae quam. Lorem, ipsum dolor sit amet consectetur adipisicing elit. Asperiores optio voluptate ipsam maiores corrupti, quidem aut ex enim est deleniti! Rerum laboriosam earum, voluptas possimus animi quae et quis asperiores. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Eaque nobis nesciunt eos fugiat voluptatem natus repudiandae iusto numquam optio, laudantium quia maxime perferendis soluta eligendi fugit esse totam voluptatum hic! Lorem, ipsum dolor sit amet consectetur adipisicing elit. Eaque a, quo cumque nemo velit quidem eveniet? Quae, iusto iste, neque aperiam ut architecto hic rerum necessitatibus recusandae quisquam quo temporibus. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Est perferendis ea nostrum necessitatibus explicabo culpa ipsa fuga natus maxime tempora ex blanditiis harum accusamus qui corporis ullam ducimus, dolorum quae? Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nobis fugit ipsa natus architecto, officia atque ex. Quia, minus illum vitae omnis, incidunt accusamus explicabo voluptatum repudiandae eaque maxime reprehenderit qui. Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure blanditiis ipsam at excepturi assumenda laborum quibusdam tempora quam perferendis ratione, sunt voluptate ducimus, velit distinctio. Hic eaque deleniti quisquam quod. Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum eos eaque cum, consequatur assumenda quam error dolor molestiae labore ex itaque delectus officia animi eius, odio harum, hic voluptatibus ut! Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint voluptas, aperiam excepturi ratione libero, placeat est, saepe quas labore fugit enim architecto voluptatem maxime facere sunt impedit repellat maiores exercitationem? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Architecto placeat, assumenda nulla harum quia officiis ullam facilis eaque dolore magni modi, fugiat quis! Ipsum, facere incidunt voluptates laboriosam id quidem? Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quam eum laboriosam sint animi nisi minima placeat in recusandae amet et iste, asperiores ipsa hic, culpa unde, fugiat voluptatibus! Quos, omnis? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dignissimos beatae tenetur dolores ad temporibus laboriosam repellendus dolorum corporis praesentium quos, possimus obcaecati fugiat reiciendis similique fuga est. Blanditiis, in pariatur. Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laboriosam est temporibus eos beatae. Atque eum tenetur voluptas totam, vero voluptatem in dolorem dolore velit maxime, enim laudantium. Est, facilis corporis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum debitis est similique quis. Cumque iusto repudiandae velit ea repellat dolore sunt expedita ut voluptatibus culpa quam totam vitae, ducimus modi? Lorem ipsum dolor sit amet consectetur adipisicing elit. Quis magni iure numquam sit! Nostrum quia, nemo neque deserunt, ex modi saepe optio ea illo debitis nesciunt officia consequuntur eum repudiandae! Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint adipisci animi minima, porro totam consectetur, ad labore consequatur aspernatur quod, ex tempore aperiam non. Ullam odit dolorem tempore doloremque est. Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus, eligendi? Ea, ab maiores quia error nam esse totam perspiciatis aperiam illo nesciunt voluptates autem at. Ducimus suscipit voluptates libero voluptatibus! Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eaque praesentium laboriosam, ratione, voluptatum error inventore ducimus illo dolorum sed delectus nam dolore est minima velit! Quae praesentium doloremque cumque explicabo. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Laboriosam dicta autem numquam obcaecati? Dolores impedit repellat tempora quas voluptatem aspernatur blanditiis est, eum laborum, aut dolorem, odit magnam inventore corrupti. Lorem ipsum dolor sit amet consectetur adipisicing elit. Exercitationem iusto officia a soluta explicabo quo officiis quos sunt beatae modi. Sunt, maxime ex tenetur adipisci laudantium iure velit ea corrupti! Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt quia deleniti, ipsa excepturi reiciendis reprehenderit at odit inventore, earum perferendis aspernatur, soluta dicta voluptatibus provident tempore saepe animi ratione assumenda. Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugiat, necessitatibus! Explicabo sit culpa perspiciatis id esse quod placeat! Dolore aperiam molestias esse excepturi, voluptate provident neque. A porro minus libero?

Body:
From the specification:

If background images are specified, this property specifies whether they are fixed with regard to the viewport (fixed) or scroll along with the element (scroll) or its contents (local). The property’s value is given as a comma-separated list of <attachment> keywords where

So the reference for contain will not more be the element but the viewport when using fixed

To avoid this effect don't use contain but consider auto 500px since you know the dimension of your div:

#background-image {
  height: 500px;
  width: 500px;
  background-image: url(https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1407523604l/15136531.jpg);
  background-repeat: no-repeat;
  background-size: auto 500px;
  background-attachment: fixed;
}

<div id="background-image"></div>
<div>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Officia, harum molestias quia tempore doloribus enim rem eius facere inventore sit nostrum totam assumenda, impedit laudantium fugit? Ratione dignissimos dolor sed. Lorem ipsum dolor sit amet consectetur
  adipisicing elit. Quisquam iusto mollitia facere, voluptate enim natus. Dolorem accusantium cum voluptatibus quasi minima, laborum enim quisquam maiores iusto esse dolor beatae quam. Lorem, ipsum dolor sit amet consectetur adipisicing elit. Asperiores
  optio voluptate ipsam maiores corrupti, quidem aut ex enim est deleniti! Rerum laboriosam earum, voluptas possimus animi quae et quis asperiores. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Eaque nobis nesciunt eos fugiat voluptatem natus
  repudiandae iusto numquam optio, laudantium quia maxime perferendis soluta eligendi fugit esse totam voluptatum hic! Lorem, ipsum dolor sit amet consectetur adipisicing elit. Eaque a, quo cumque nemo velit quidem eveniet? Quae, iusto iste, neque aperiam
  ut architecto hic rerum necessitatibus recusandae quisquam quo temporibus. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Est perferendis ea nostrum necessitatibus explicabo culpa ipsa fuga natus maxime tempora ex blanditiis harum accusamus
  qui corporis ullam ducimus, dolorum quae? Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nobis fugit ipsa natus architecto, officia atque ex. Quia, minus illum vitae omnis, incidunt accusamus explicabo voluptatum repudiandae eaque maxime
  reprehenderit qui. Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure blanditiis ipsam at excepturi assumenda laborum quibusdam tempora quam perferendis ratione, sunt voluptate ducimus, velit distinctio. Hic eaque deleniti quisquam quod.
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum eos eaque cum, consequatur assumenda quam error dolor molestiae labore ex itaque delectus officia animi eius, odio harum, hic voluptatibus ut! Lorem ipsum dolor sit amet consectetur adipisicing
  elit. Sint voluptas, aperiam excepturi ratione libero, placeat est, saepe quas labore fugit enim architecto voluptatem maxime facere sunt impedit repellat maiores exercitationem? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Architecto placeat,
  assumenda nulla harum quia officiis ullam facilis eaque dolore magni modi, fugiat quis! Ipsum, facere incidunt voluptates laboriosam id quidem? Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quam eum laboriosam sint animi nisi minima placeat
  in recusandae amet et iste, asperiores ipsa hic, culpa unde, fugiat voluptatibus! Quos, omnis? Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dignissimos beatae tenetur dolores ad temporibus laboriosam repellendus dolorum corporis praesentium
  quos, possimus obcaecati fugiat reiciendis similique fuga est. Blanditiis, in pariatur. Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laboriosam est temporibus eos beatae. Atque eum tenetur voluptas totam, vero voluptatem in dolorem dolore
  velit maxime, enim laudantium. Est, facilis corporis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum debitis est similique quis. Cumque iusto repudiandae velit ea repellat dolore sunt expedita ut voluptatibus culpa quam totam vitae,
  ducimus modi? Lorem ipsum dolor sit amet consectetur adipisicing elit. Quis magni iure numquam sit! Nostrum quia, nemo neque deserunt, ex modi saepe optio ea illo debitis nesciunt officia consequuntur eum repudiandae! Lorem ipsum dolor sit amet consectetur
  adipisicing elit. Sint adipisci animi minima, porro totam consectetur, ad labore consequatur aspernatur quod, ex tempore aperiam non. Ullam odit dolorem tempore doloremque est. Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus, eligendi?
  Ea, ab maiores quia error nam esse totam perspiciatis aperiam illo nesciunt voluptates autem at. Ducimus suscipit voluptates libero voluptatibus! Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eaque praesentium laboriosam, ratione, voluptatum
  error inventore ducimus illo dolorum sed delectus nam dolore est minima velit! Quae praesentium doloremque cumque explicabo. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Laboriosam dicta autem numquam obcaecati? Dolores impedit repellat
  tempora quas voluptatem aspernatur blanditiis est, eum laborum, aut dolorem, odit magnam inventore corrupti. Lorem ipsum dolor sit amet consectetur adipisicing elit. Exercitationem iusto officia a soluta explicabo quo officiis quos sunt beatae modi.
  Sunt, maxime ex tenetur adipisci laudantium iure velit ea corrupti! Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt quia deleniti, ipsa excepturi reiciendis reprehenderit at odit inventore, earum perferendis aspernatur, soluta dicta
  voluptatibus provident tempore saepe animi ratione assumenda. Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugiat, necessitatibus! Explicabo sit culpa perspiciatis id esse quod placeat! Dolore aperiam molestias esse excepturi, voluptate
  provident neque. A porro minus libero?</div>