问:
How to restrict media files of django project via nginx without dedicated server
I am running a Django project in a docker container. Uwsgi is my chosen protocol. Nginx is acting as a reverse proxy.

I am able to restrict django sites for users based user.is_authenticated().
I am not able to restrict media and static files for not authenticated users as they get served directly from the filesystem.

I do not have a second, dedicated server which only purpose is to identify and authenticate users. As I already have the functionality within my django project, I want to use this.

My nginx configuration:

```<code>events{}

daemon off;

http {
    access_log /dev/stdout;
    error_log /var/log/nginx/error.log;

    upstream django {
        server unix:///tmp/nginx/diplab.sock;
    }

    server {
    listen 8080;

    location = /accounts/check-authenticated {
        internal;
        uwsgi_pass              django;
        proxy_pass_request_body off;
        proxy_set_header        Content-Length "";
        }

    location /static {
        alias /vol/web/static;
        include /etc/nginx/mime.types;
        }

    location /media {
        alias /vol/web/media;
        include /etc/nginx/mime.types;
        auth_request /accounts/check-authenticated;
        auth_request_set $auth_status $upstream_status;
        }

    location / {
        uwsgi_pass django;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        include /etc/nginx/uwsgi_params;
        }
    }
}
</code>```

My Django Setup of the view which has the purpose to authenticate a user (200) or not (401).

```<code># urls.py
app_name = 'accounts'
urlpatterns = [
    path('check-authenticated/', views.is_authenticated_view, name="check-authenticated"),
    path('login/', views.UserLoginView.as_view(), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

# views.py
def is_authenticated_view(request):
    if request.user.is_authenticated:
        return HttpResponse(status=200)
    return HttpResponse(status=401)
</code>```

The error that shows up is fairly deep inside Djangos core:

```<code>Traceback (most recent call last):
  File "/root/miniconda3/envs/myproject/lib/python3.10/site-packages/django/core/handlers/wsgi.py", line 130, in __call__
    request = self.request_class(environ)
  File "/root/miniconda3/envs/myproject/lib/python3.10/site-packages/django/core/handlers/wsgi.py", line 78, in __init__
    self.method = environ["REQUEST_METHOD"].upper()
KeyError: 'REQUEST_METHOD'
</code>```

The error.log of nginx shows the following:

```<code>2022/12/06 17:42:27 [error] 194#194: *1 upstream prematurely closed connection while reading response header from upstream, client: 172.19.0.1, server: , request: "GET /media/myname/compound_structures/1cf10238af0.png HTTP/1.1", subrequest: "/accounts/check-authenticated", upstream: "uwsgi://unix:///tmp/nginx/diplab.sock:", host: "127.0.0.1:8080", referrer: "http://127.0.0.1:8080/toolbox/"
2022/12/06 17:42:27 [error] 194#194: *1 auth request unexpected status: 502 while sending to client, client: 172.19.0.1, server: , request: "GET /media/myname/compound_structures/1cf10238af0.png HTTP/1.1", host: "127.0.0.1:8080", referrer: "http://127.0.0.1:8080/toolbox/"
</code>```

I tried to add the REQUEST_METHOD plus some other variables like this, but without being successful - still same error.

```<code>location = /accounts/check-authenticated {
    internal;
    uwsgi_pass              django;
    proxy_pass_request_body off;
    proxy_set_header        Content-Length "";
    proxy_set_header        REQUEST_METHOD GET;
    proxy_set_header X-Original-URI $request_uri;
    proxy_set_header X-Original-Remote-Addr $remote_addr;
    proxy_set_header X-Original-Host $host;
    }
</code>```

I am by far no expert in terms of nginx and appreciate any help! This is the approach I found first. I'd be happy if you recommend me another approach if you are not able to help me with this one.

Edit 1

As Elgin Cahangirov suggested, I now include the uwsgi_params to the location block like this:

```<code>location = /accounts/check-authenticated {
    internal;
    uwsgi_pass              django;
    proxy_pass_request_body off;
    proxy_set_header        Content-Length "";
    proxy_set_header        X-Original-URI $request_uri;
    include /etc/nginx/uwsgi_params;
    }
</code>```

I think it definitely helped on my journey, as one of many errors is fixed, but sadly the images still do not show up.
uwsgi:

```<code>172.19.0.1 - - [07/Dec/2022:08:33:33 +0000] "GET /media/myname/compound_structures/1cf10238af0.png HTTP/1.1" 500 186 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
[pid: 219|app: 0|req: 19/19] 172.19.0.1 () {52 vars in 936 bytes} [Wed Dec  7 08:33:33 2022] GET /media/myname/compound_structures/1cf10238af0.png => generated 0 bytes in 1 msecs (HTTP/1.1 301) 6 headers in 239 bytes (1 switches on core 0)
</code>```

nginx error.log

```<code>2022/12/07 08:33:33 [error] 195#195: *30 auth request unexpected status: 301 while sending to client, client: 172.19.0.1, server: , request: "GET /media/myname/compound_structures/1cf10238af0.png HTTP/1.1", host: "127.0.0.1:8080"
</code>```

Body:
I am running a Django project in a docker container. Uwsgi is my chosen protocol. Nginx is acting as a reverse proxy.

I am able to restrict django sites for users based user.is_authenticated().
I am not able to restrict media and static files for not authenticated users as they get served directly from the filesystem.

I do not have a second, dedicated server which only purpose is to identify and authenticate users. As I already have the functionality within my django project, I want to use this.

My nginx configuration:

events{}

daemon off;

http {
    access_log /dev/stdout;
    error_log /var/log/nginx/error.log;

    upstream django {
        server unix:///tmp/nginx/diplab.sock;
    }

    server {
    listen 8080;

    location = /accounts/check-authenticated {
        internal;
        uwsgi_pass              django;
        proxy_pass_request_body off;
        proxy_set_header        Content-Length "";
        }

    location /static {
        alias /vol/web/static;
        include /etc/nginx/mime.types;
        }

    location /media {
        alias /vol/web/media;
        include /etc/nginx/mime.types;
        auth_request /accounts/check-authenticated;
        auth_request_set $auth_status $upstream_status;
        }

    location / {
        uwsgi_pass django;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        include /etc/nginx/uwsgi_params;
        }
    }
}

My Django Setup of the view which has the purpose to authenticate a user (200) or not (401).

# urls.py
app_name = 'accounts'
urlpatterns = [
    path('check-authenticated/', views.is_authenticated_view, name="check-authenticated"),
    path('login/', views.UserLoginView.as_view(), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

# views.py
def is_authenticated_view(request):
    if request.user.is_authenticated:
        return HttpResponse(status=200)
    return HttpResponse(status=401)

The error that shows up is fairly deep inside Djangos core:

Traceback (most recent call last):
  File "/root/miniconda3/envs/myproject/lib/python3.10/site-packages/django/core/handlers/wsgi.py", line 130, in __call__
    request = self.request_class(environ)
  File "/root/miniconda3/envs/myproject/lib/python3.10/site-packages/django/core/handlers/wsgi.py", line 78, in __init__
    self.method = environ["REQUEST_METHOD"].upper()
KeyError: 'REQUEST_METHOD'

The error.log of nginx shows the following:

2022/12/06 17:42:27 [error] 194#194: *1 upstream prematurely closed connection while reading response header from upstream, client: 172.19.0.1, server: , request: "GET /media/myname/compound_structures/1cf10238af0.png HTTP/1.1", subrequest: "/accounts/check-authenticated", upstream: "uwsgi://unix:///tmp/nginx/diplab.sock:", host: "127.0.0.1:8080", referrer: "http://127.0.0.1:8080/toolbox/"
2022/12/06 17:42:27 [error] 194#194: *1 auth request unexpected status: 502 while sending to client, client: 172.19.0.1, server: , request: "GET /media/myname/compound_structures/1cf10238af0.png HTTP/1.1", host: "127.0.0.1:8080", referrer: "http://127.0.0.1:8080/toolbox/"

I tried to add the REQUEST_METHOD plus some other variables like this, but without being successful - still same error.

location = /accounts/check-authenticated {
    internal;
    uwsgi_pass              django;
    proxy_pass_request_body off;
    proxy_set_header        Content-Length "";
    proxy_set_header        REQUEST_METHOD GET;
    proxy_set_header X-Original-URI $request_uri;
    proxy_set_header X-Original-Remote-Addr $remote_addr;
    proxy_set_header X-Original-Host $host;
    }

I am by far no expert in terms of nginx and appreciate any help! This is the approach I found first. I'd be happy if you recommend me another approach if you are not able to help me with this one.

Edit 1

As Elgin Cahangirov suggested, I now include the uwsgi_params to the location block like this:

location = /accounts/check-authenticated {
    internal;
    uwsgi_pass              django;
    proxy_pass_request_body off;
    proxy_set_header        Content-Length "";
    proxy_set_header        X-Original-URI $request_uri;
    include /etc/nginx/uwsgi_params;
    }

I think it definitely helped on my journey, as one of many errors is fixed, but sadly the images still do not show up.
uwsgi:

172.19.0.1 - - [07/Dec/2022:08:33:33 +0000] "GET /media/myname/compound_structures/1cf10238af0.png HTTP/1.1" 500 186 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
[pid: 219|app: 0|req: 19/19] 172.19.0.1 () {52 vars in 936 bytes} [Wed Dec  7 08:33:33 2022] GET /media/myname/compound_structures/1cf10238af0.png => generated 0 bytes in 1 msecs (HTTP/1.1 301) 6 headers in 239 bytes (1 switches on core 0)

nginx error.log

2022/12/07 08:33:33 [error] 195#195: *30 auth request unexpected status: 301 while sending to client, client: 172.19.0.1, server: , request: "GET /media/myname/compound_structures/1cf10238af0.png HTTP/1.1", host: "127.0.0.1:8080"


来源: stackexchange

问:
Winforms when Application.EnableVisualStyles() added can t change progress bar color
When i ve added in Program.cs Application.EnableVisualStyles(); then i can t change progress bar color. Do you know another solution without deleting that line because it change all styles used in the app

Application.EnableVisualStyles(); it helps to disable that but it leads to styles problems

ContentLicense: CC BY-SA 4.0


问:
how to read buffer backwards? x86 TASM
I need to display the buffer backwards than it is at first</p>
```<code>....
MOV cx, ax
    MOV si, offset skBuf
    MOV di, offset raBuf
 work
    MOV dl, [si]

    MOV [di], dl
    INC si
    INC di
    LOOP    work
....
</code>```

Title: how to read buffer backwards? x86 TASM

Body:
I need to display the buffer backwards than it is at first

....
MOV cx, ax
    MOV si, offset skBuf
    MOV di, offset raBuf
 work
    MOV dl, [si]

    MOV [di], dl
    INC si
    INC di
    LOOP    work
....


问:
Add all form input value to closest div as class
I have a form with a bunch of text inputfield. Each of them is embedded in a div. When the user clicks the save button, i need each of the input values to be added to corresponding div that wraps it as a class. Right after that happens, then next function, which initiates the saving process, should start.

At first I used on("change") , but that led to the each noew value to be added as a new class on every keystroke. That way I only had once chance: copy and paste the entire text and don't make a mistake.

```<code>redips.save = function () {
    // scan timetable content
     $(".input").on("change", "input[type='text']", function() {
            var klasse;
            klasse = $(this).val();
            //alert(klasse);
            $(this).closest('div').addClass(klasse);
        });
    let content = REDIPS.drag.saveContent('table2');
    // and save content
    window.location.href = 'redips_db_save.php?' + content;
};

</code>```

This is the HTML:

```<code>print "<div id=\"$id\" class=\"input btn btn-secondary redips-drag klasse $class\">$name

            <input type=\"text\" class=\"input\" id=\"addinfo\" value=\"$addinfo\" placeholder=\"Add Info\" name=\"$pos\"></input>
           </div> ";
</code>```

in this table (timetable(..) creates the divs with the inputs):

```<code> <table id="table2" class="table table-responsive">
                    <colgroup>
                        <col max-width="50" />
                        <col max-width="100" />
                        <col max-width="100" />
                        <col max-width="100" />
                        <col max-width="100" />
                        <col max-width="100" />
                        <col max-width="100" />
                        <col max-width="100" />
                    </colgroup>
                    <tbody>
                        <tr>
                            <!-- if checkbox is checked, clone school subjects to the whole table row  -->
                            <td class="redips-mark blank">
                                <input id="week" type="checkbox" title="Apply school subjects to the week" checked />
                                <input id="report" type="checkbox" title="Show subject report" />
                            </td>
                            <td class="redips-mark dark">Monday</td>
                            <td class="redips-mark dark">Tuesday</td>
                            <td class="redips-mark dark">Wednesday</td>
                            <td class="redips-mark dark">Thursday</td>
                            <td class="redips-mark dark">Friday</td>
                            <td class="redips-mark dark">Saturday</td>
                            <td class="redips-mark dark">Sunday</td>
                        </tr>

                        <?php timetable('Week 1', 1) ?>
                        <?php timetable('Week 2', 2) ?>
                        <?php timetable('Week 3', 3) ?>
                        <?php timetable('Week 4', 4) ?>
                        <?php timetable('Week 5', 5) ?>

                        <?php timetable('Week 6', 6) ?>
                        <?php timetable('Week 7', 7) ?>
                        <?php timetable('Week 8', 8) ?>
                        <?php timetable('Week 9', 9) ?>
                    </tbody>
                </table>
</code>```

here is what I have tried then:

```<code>redips.save = function () {
    // scan timetable content
            var klasse;
        //get input values from inputs
            klasse = $(".input").val();
            //alert(klasse);
            //add each value to the closest div class
            $(this).closest('div').addClass(klasse);

    let content = REDIPS.drag.saveContent('table2');
    // and save content
    window.location.href = 'redips_db_save.php?' + content;
};
</code>```

Alert(klasse) alerts without text - so I guess the problem starts with a wrong selection.
Can you help me and point me in the right direction?

thank you!

Body:
I have a form with a bunch of text inputfield. Each of them is embedded in a div. When the user clicks the save button, i need each of the input values to be added to corresponding div that wraps it as a class. Right after that happens, then next function, which initiates the saving process, should start.

At first I used on("change") , but that led to the each noew value to be added as a new class on every keystroke. That way I only had once chance: copy and paste the entire text and don't make a mistake.

redips.save = function () {
    // scan timetable content
     $(".input").on("change", "input[type='text']", function() {
            var klasse;
            klasse = $(this).val();
            //alert(klasse);
            $(this).closest('div').addClass(klasse);
        });
    let content = REDIPS.drag.saveContent('table2');
    // and save content
    window.location.href = 'redips_db_save.php?' + content;
};

This is the HTML:

print "
$name

            <input type=\"text\" class=\"input\" id=\"addinfo\" value=\"$addinfo\" placeholder=\"Add Info\" name=\"$pos\"></input>

 ";

in this table (timetable(..) creates the divs with the inputs):

                    <colgroup>
                        <col max-width="50" />
                        <col max-width="100" />
                        <col max-width="100" />
                        <col max-width="100" />
                        <col max-width="100" />
                        <col max-width="100" />
                        <col max-width="100" />
                        <col max-width="100" />
                    </colgroup>

                                <input id="week" type="checkbox" title="Apply school subjects to the week" checked />
                                <input id="report" type="checkbox" title="Show subject report" />

                            Monday
                            Tuesday
                            Wednesday
                            Thursday
                            Friday
                            Saturday
                            Sunday

                        <?php timetable('Week 1', 1) ?>
                        <?php timetable('Week 2', 2) ?>
                        <?php timetable('Week 3', 3) ?>
                        <?php timetable('Week 4', 4) ?>
                        <?php timetable('Week 5', 5) ?>

                        <?php timetable('Week 6', 6) ?>
                        <?php timetable('Week 7', 7) ?>
                        <?php timetable('Week 8', 8) ?>
                        <?php timetable('Week 9', 9) ?>

here is what I have tried then:

redips.save = function () {
    // scan timetable content
            var klasse;
        //get input values from inputs
            klasse = $(".input").val();
            //alert(klasse);
            //add each value to the closest div class
            $(this).closest('div').addClass(klasse);

    let content = REDIPS.drag.saveContent('table2');
    // and save content
    window.location.href = 'redips_db_save.php?' + content;
};

Alert(klasse) alerts without text - so I guess the problem starts with a wrong selection.
Can you help me and point me in the right direction?

thank you!


问:
How to know which CSS3 properties require vendor prefixes like -webkit-,-moz-,-0- etc.?
I use wordpress and every now and then have to add custom CSS with some 'lesser' known properties like isolation and just add it like isolation: isolate;. But what I would like to know is that do I really need to go to caniuse(dot)com and check the 'Notes' tab for each property  every time I have to add some custom CSS to learn about its vendor prefix requirement? Is this the only way? Any comprehensive cheatsheet-'type' content exists? I'm not sure because I have seem some 'seemingly' common CSS properties too utilizing those prefixes. Thanks.


问:
To knit an external pagedown rmd file to a pdf
Is it possible in a pagedown rmd file to call and knit an external pagedown rmd file?

I tried rmarkdown::render() in an r code chunk.  It did not work.


问:
iterate through df with a condition
I'm automating data upload from excel on a website which looks like this:

My dataframe looks like this:

```<code>Depot            Quantity   Product Name
KSBCL HUBBALLI-1    50      Old Tavern Whisky-PET 750MLx12P.Btls(0033)
KSBCL HUBBALLI-1    90      Bagpiper Deluxe Whisky 375 Ml (0033)
KSBCL GOKAK         30      Bagpiper XXX Rum-Aseptic Brick Pack 180MLx48ABPack(0033)
KSBCL GOKAK         60      Bagpiper XXX Rum-ASEPTIC BRIK PACK 90MLx96ABP(0033)
KSBCL GOKAK         90      Haywards Cheers Whisky-TETRA PACK 90MLx96 T.Pack(0033)

</code>```

The dropdown that you can see on the website image will have the depot values from df, and the qty goes into the input field right next to the product names.

The problem that I'm facing is that I don't know how to iterate through the df in such a way that, for each depot in df, it should fill in qty of all products under that depot, submit, and then only move to the next depot.

This is the current code that I built, but it doesn't wait for all items in a depot to get filled before submission.

```<code>for i, j in df.iterrows():

    addToShoppingBagBtn = wait.until(lambda web: web.find_element(By.XPATH, '//*[@id="ContentPlaceHolder1_btntopindent"]'))

    if j['Depot Mapping'].upper() in citiesList:

            Select(wait.until(lambda web: web.find_element(By.XPATH, '//*[@id="ContentPlaceHolder1_dddepot"]'))).select_by_visible_text(j['Depot Mapping'].upper())

            time.sleep(2)

    qty = rowdict[j['SKU Mapping']][1].find_element(By.TAG_NAME,'input')

    qty.send_keys(j['Quantity'])

    checkBtn = rowdict[j['SKU Mapping']][7].find_element(By.TAG_NAME,'input')

    checkBtn.click()

    time.sleep(2)

    addToShoppingBagBtn.click()
</code>```

Title: iterate through df with a condition

Body:
I'm automating data upload from excel on a website which looks like this:

My dataframe looks like this:

Depot            Quantity   Product Name
KSBCL HUBBALLI-1    50      Old Tavern Whisky-PET 750MLx12P.Btls(0033)
KSBCL HUBBALLI-1    90      Bagpiper Deluxe Whisky 375 Ml (0033)
KSBCL GOKAK         30      Bagpiper XXX Rum-Aseptic Brick Pack 180MLx48ABPack(0033)
KSBCL GOKAK         60      Bagpiper XXX Rum-ASEPTIC BRIK PACK 90MLx96ABP(0033)
KSBCL GOKAK         90      Haywards Cheers Whisky-TETRA PACK 90MLx96 T.Pack(0033)

The dropdown that you can see on the website image will have the depot values from df, and the qty goes into the input field right next to the product names.

The problem that I'm facing is that I don't know how to iterate through the df in such a way that, for each depot in df, it should fill in qty of all products under that depot, submit, and then only move to the next depot.

This is the current code that I built, but it doesn't wait for all items in a depot to get filled before submission.

for i, j in df.iterrows():

    addToShoppingBagBtn = wait.until(lambda web: web.find_element(By.XPATH, '//*[@id="ContentPlaceHolder1_btntopindent"]'))

    if j['Depot Mapping'].upper() in citiesList:

            Select(wait.until(lambda web: web.find_element(By.XPATH, '//*[@id="ContentPlaceHolder1_dddepot"]'))).select_by_visible_text(j['Depot Mapping'].upper())

            time.sleep(2)

    qty = rowdict[j['SKU Mapping']][1].find_element(By.TAG_NAME,'input')

    qty.send_keys(j['Quantity'])

    checkBtn = rowdict[j['SKU Mapping']][7].find_element(By.TAG_NAME,'input')

    checkBtn.click()

    time.sleep(2)

    addToShoppingBagBtn.click()


问:
How can I import EF database into Brightway2?
I am trying to import EF database (not just the method) into Brightway2.
EF database is available for Simapro, for GaBi, and for openLCA.
I was able to download the ef_secondarydata_202202.zolca file from openLCA Nexus and import it into openLCA.

But from there, I don't see any path to bring it to Brightway.

It is possible to export processes and methods in EcoSpold1 format from openLCA.
But trying to import them into Brightway using

```<code>ef = SingleOutputEcospold1Importer('C:\\...\\EcoSpold01', 'EF', use_mp=False)
ef.apply_strategies()
</code>```

I get the following error :

```<code>Couldn't apply strategy link_technosphere_by_activity_hash:
        Object in source database can't be uniquely linked to target database.
Problematic dataset is:
{'categories': ('End-of-life treatment',),
 'filename': '(missing)',
 'location': 'EU-28+EFTA',
 'name': 'Electronics scrap',
 'unit': 'kilogram'}
Possible targets include (at least one not shown):
[{'categories': ['End-of-life treatment'],
  'filename': 'S:\\...\\EcoSpold01\\process_2fe13aaf-f0b4-4be2-9e8d-fdc27b30ac94.xml',
  'location': 'EU-28+EFTA',
  'name': 'Electronics scrap',
  'unit': 'kilogram'},
+ many many others...
]
Applied 11 strategies in 94.26 seconds
</code>```

Furthermore all (or nearly all) exchanges are unlinked :

```<code>>>> ef.statistics()
3185 datasets
4647753 exchanges
4647752 unlinked exchanges
  Type biosphere: 4101 unique unlinked exchanges
  Type production: 2149 unique unlinked exchanges
  Type technosphere: 133 unique unlinked exchanges
(3185, 4647753, 4647752)
</code>```

Of course, after that write_database() fails.

I checked the list of elementary fluxes, they are very different between EF and Biosphere3. To begin with, there are 7741 fluxes in EF vs 4709 in Biosphere3, and looking for similar names I didn't find many...

I am using :
Windows 10
brightway2                2.4.2                      py_6    cmutel
bw2io                     0.8.8                      py_0    cmutel
OpenLCA 1.11.0 Windows 64 bit

To summarize : how would you import EF database into Brightway2 ?
I did not find the answer in SO existing questions.

Body:
I am trying to import EF database (not just the method) into Brightway2.
EF database is available for Simapro, for GaBi, and for openLCA.
I was able to download the ef_secondarydata_202202.zolca file from openLCA Nexus and import it into openLCA.

But from there, I don't see any path to bring it to Brightway.

It is possible to export processes and methods in EcoSpold1 format from openLCA.
But trying to import them into Brightway using

ef = SingleOutputEcospold1Importer('C:\\...\\EcoSpold01', 'EF', use_mp=False)
ef.apply_strategies()

I get the following error :

Couldn't apply strategy link_technosphere_by_activity_hash:
        Object in source database can't be uniquely linked to target database.
Problematic dataset is:
{'categories': ('End-of-life treatment',),
 'filename': '(missing)',
 'location': 'EU-28+EFTA',
 'name': 'Electronics scrap',
 'unit': 'kilogram'}
Possible targets include (at least one not shown):
[{'categories': ['End-of-life treatment'],
  'filename': 'S:\\...\\EcoSpold01\\process_2fe13aaf-f0b4-4be2-9e8d-fdc27b30ac94.xml',
  'location': 'EU-28+EFTA',
  'name': 'Electronics scrap',
  'unit': 'kilogram'},
+ many many others...
]
Applied 11 strategies in 94.26 seconds

Furthermore all (or nearly all) exchanges are unlinked :

>>> ef.statistics()
3185 datasets
4647753 exchanges
4647752 unlinked exchanges
  Type biosphere: 4101 unique unlinked exchanges
  Type production: 2149 unique unlinked exchanges
  Type technosphere: 133 unique unlinked exchanges
(3185, 4647753, 4647752)

Of course, after that write_database() fails.

I checked the list of elementary fluxes, they are very different between EF and Biosphere3. To begin with, there are 7741 fluxes in EF vs 4709 in Biosphere3, and looking for similar names I didn't find many...

I am using :
Windows 10
brightway2                2.4.2                      py_6    cmutel
bw2io                     0.8.8                      py_0    cmutel
OpenLCA 1.11.0 Windows 64 bit

To summarize : how would you import EF database into Brightway2 ?
I did not find the answer in SO existing questions.


问:
Docker MySQL = exec /usr/local/bin/docker-entrypoint.sh: exec format error
i try to install wordpress with portainer and i have this error message : exec /usr/local/bin/docker-entrypoint.sh: exec format error about the MySQL container.

I new with docker and i'm lost.

Can you help me please ?

I restart de container.
I install new instance.


问:
find_element_by_id/name not working as expected
I'm writing some code to try to open strava.com and log me in.

```<code>from selenium import webdriver

# create a new Chrome webdriver
driver = webdriver.Chrome()

# navigate to the Strava login page
driver.get('https://www.strava.com/login')

# import the time module
import time
time.sleep(3)

# enter your email address and password
email_field = driver.find_element_by_id('email')
email_field.send_keys('Email')
password_field = driver.find_element_by_id('password')
password_field.send_keys('Password')

# click the "Log In" button to log in
login_button = driver.find_element_by_id('login-button')
login_button.click()

# navigate to the explore page
driver.get('https://www.strava.com/explore')
</code>```

and I get the following error after strava opens and the script ends abruptly.

```<code>    email_field = driver.find_element_by_id('email')
AttributeError: 'WebDriver' object has no attribute 'find_element_by_id'
</code>```

Any ideas?

I've tried to find ways to fix the element but am very new to scripting. I can't seem to make it work and log me into strava.

Body:
I'm writing some code to try to open strava.com and log me in.

from selenium import webdriver

# create a new Chrome webdriver
driver = webdriver.Chrome()

# navigate to the Strava login page
driver.get('https://www.strava.com/login')

# import the time module
import time
time.sleep(3)

# enter your email address and password
email_field = driver.find_element_by_id('email')
email_field.send_keys('Email')
password_field = driver.find_element_by_id('password')
password_field.send_keys('Password')

# click the "Log In" button to log in
login_button = driver.find_element_by_id('login-button')
login_button.click()

# navigate to the explore page
driver.get('https://www.strava.com/explore')

and I get the following error after strava opens and the script ends abruptly.

    email_field = driver.find_element_by_id('email')
AttributeError: 'WebDriver' object has no attribute 'find_element_by_id'

Any ideas?

I've tried to find ways to fix the element but am very new to scripting. I can't seem to make it work and log me into strava.


问:
After Gradle upgrade from 7.2 to 7.3 colors resources 'quantum' disapear
After upgrading com.android.tools.build:gradle:7.2.2 to com.android.tools.build:gradle:7.3.1 the color resources of the "quantum" palette disappeared.

Does anyone know if there is any library that adds these palettes to replace the one that was removed from this dependency?

If not, I will have to redo the entire setup of these colors used.


问:
Problem with a code that does not do what it should?
```<code>@events.register(events.NewMessage(chats='tubot'))
async def mi_handler(event):
 client = event.client
 if 'A big' in event.raw_text:
  async for message in client.iter_messages('tubot', limit=1, from_user='tubot'):
   await message.click(0)
  url = event.message.buttons[0][0].url
  print(url)
  await event.client.send_message('mybot', url.split('=')[1])
</code>```

This code does something to me that had never happened to me before:
The code should do is: when the message appears in the ¨tubot¨, it should press the button and unlock the url, then a part of that url will send it to my bot called ¨mybot¨.
BUT:
when the message arrives in ´tubot´ the code click on the button and unlock the url, but it does not forward it to ´mybot´.
however when that message with the button already unlocked I manually forward it to "tubot" the code does forward it perfectly to ´mybot´

I have tried the following:
1- await asyncio.sleep(0.2) put an await between clicking on the button and reading the url and nothing didn't work.
2- even separate the code into two parts, one that clicks the button and another that forwards and nothing did not work
3- I made a group I put the code to click on the 'tubot' message and forward it to the group and another code that reads the message in that group with the button already unlocked and forwards the url to 'mybot' and nothing did not work. Even in the group, if I forward the message with the unlocked button, it reads me the url perfectly and it forwards me perfectly to 'mybot' but if it does the code doesn't work

Body:
@events.register(events.NewMessage(chats='tubot'))
async def mi_handler(event):
 client = event.client
 if 'A big' in event.raw_text:
  async for message in client.iter_messages('tubot', limit=1, from_user='tubot'):
   await message.click(0)
  url = event.message.buttons[0][0].url
  print(url)
  await event.client.send_message('mybot', url.split('=')[1])

This code does something to me that had never happened to me before:
The code should do is: when the message appears in the ¨tubot¨, it should press the button and unlock the url, then a part of that url will send it to my bot called ¨mybot¨.
BUT:
when the message arrives in ´tubot´ the code click on the button and unlock the url, but it does not forward it to ´mybot´.
however when that message with the button already unlocked I manually forward it to "tubot" the code does forward it perfectly to ´mybot´

I have tried the following:
1- await asyncio.sleep(0.2) put an await between clicking on the button and reading the url and nothing didn't work.
2- even separate the code into two parts, one that clicks the button and another that forwards and nothing did not work
3- I made a group I put the code to click on the 'tubot' message and forward it to the group and another code that reads the message in that group with the button already unlocked and forwards the url to 'mybot' and nothing did not work. Even in the group, if I forward the message with the unlocked button, it reads me the url perfectly and it forwards me perfectly to 'mybot' but if it does the code doesn't work


问:
Combine different numerical features with tf-idf
I want to combine multiple numerical feature with tf-idf to train a model with passive agresive classifier but I can't combine tf-idf vector with other numerical features which are array. For example I have a number of words and number of characters for each text. I searched from many sources on the internet but none of the ways I found worked, how can I follow a way?

You can see my code example in the picture above.


问:
KeyError: 'iris'
I'm getting these errors for my Python IDLE Shell code. I have the iris.csv file in the same place as the Lab 5.py file, so I'm not sure what to do next. A fix would be greatly appreciated!

-------------------------------------------------------------------------------------------------------------------------------

```<code>Traceback (most recent call last):
  File "C:\Users\kyle_\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\indexes\base.py", line 3800, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 5745, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 5753, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'iris'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\kyle_\OneDrive\Documents\COIS 4400H\Lab 5.py", line 23, in <module>
    iris_df['iris'].drop_duplicates()
  File "C:\Users\kyle_\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\frame.py", line 3805, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Users\kyle_\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\indexes\base.py", line 3802, in get_loc
    raise KeyError(key) from err
KeyError: 'iris'
>>>
</code>```

This is the code I'm using:

-------------------------------------------------------------------------------------------------------------------------------

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

import datetime as dt

import sklearn
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

from scipy.cluster.hierarchy import linkage
from scipy.cluster.hierarchy import dendrogram
from scipy.cluster.hierarchy import cut_tree

import os
os.chdir('C:\\Users\kyle_\OneDrive\Documents\COIS 4400H')
iris_df = pd.read_csv('iris.csv')

iris_df.head()

iris_df['iris'].drop_duplicates()

iris_df = iris_df.drop('iris',axis=1)

scaler = StandardScaler()

iris_df_scaled = scaler.fit_transform(iris_df)
iris_df_scaled.shape

sse = []
range_n_clusters = [2, 3, 4, 5, 6, 7, 8 , 9 , 10 ]
for num_clusters in range_n_clusters:
    kmeans = KMeans(n_clusters=num_clusters, max_iter=50)
kmeans.fit(iris_df_scaled)

sse.append(kmeans.inertia_)

plt.plot(sse)

# 1. Kmeans with k=3
kmeans = KMeans(n_clusters=3, max_iter=50)
y = kmeans.fit_predict(iris_df_scaled)

y

iris_df['Label'] = kmeans.labels_
iris_df.head()

plt.scatter(iris_df_scaled[y == 0, 0], iris_df_scaled[y == 0, 1], s = 100, c = 'purple', label = 'Iris-setosa')
plt.scatter(iris_df_scaled[y == 1, 0], iris_df_scaled[y == 1, 1], s = 100, c = 'orange', label = 'Iris-versicolour')
plt.scatter(iris_df_scaled[y == 2, 0], iris_df_scaled[y == 2, 1], s = 100, c = 'green', label = 'Iris-virginica')

# 2. Hierarchical clustering
plt.figure(figsize=(15, 5))
mergings = linkage(iris_df_scaled,method='complete',metric='euclidean')
dendrogram(mergings)
plt.show()

cluster_hier = cut_tree(mergings,n_clusters=3).reshape(-1)

iris_df['Label'] = cluster_hier
iris_df.head()

plt.scatter(iris_df_scaled[cluster_hier == 0, 0], iris_df_scaled[cluster_hier == 0, 1], s = 100, c = 'purple', label = 'Iris-setosa')
plt.scatter(iris_df_scaled[cluster_hier == 1, 0], iris_df_scaled[cluster_hier == 1, 1], s = 100, c = 'orange', label = 'Iris-versicolour')
plt.scatter(iris_df_scaled[cluster_hier == 2, 0], iris_df_scaled[cluster_hier == 2, 1], s = 100, c = 'green', label = 'Iris-virginica')
</code>```

Title: KeyError: 'iris'

Body:
I'm getting these errors for my Python IDLE Shell code. I have the iris.csv file in the same place as the Lab 5.py file, so I'm not sure what to do next. A fix would be greatly appreciated!

-------------------------------------------------------------------------------------------------------------------------------

Traceback (most recent call last):
  File "C:\Users\kyle_\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\indexes\base.py", line 3800, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 5745, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 5753, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'iris'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\kyle_\OneDrive\Documents\COIS 4400H\Lab 5.py", line 23, in <module>
    iris_df['iris'].drop_duplicates()
  File "C:\Users\kyle_\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\frame.py", line 3805, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Users\kyle_\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\indexes\base.py", line 3802, in get_loc
    raise KeyError(key) from err
KeyError: 'iris'
>>>

This is the code I'm using:

-------------------------------------------------------------------------------------------------------------------------------

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

import datetime as dt

import sklearn
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

from scipy.cluster.hierarchy import linkage
from scipy.cluster.hierarchy import dendrogram
from scipy.cluster.hierarchy import cut_tree

import os
os.chdir('C:\\Users\kyle_\OneDrive\Documents\COIS 4400H')
iris_df = pd.read_csv('iris.csv')

iris_df.head()

iris_df['iris'].drop_duplicates()

iris_df = iris_df.drop('iris',axis=1)

scaler = StandardScaler()

iris_df_scaled = scaler.fit_transform(iris_df)
iris_df_scaled.shape

sse = []
range_n_clusters = [2, 3, 4, 5, 6, 7, 8 , 9 , 10 ]
for num_clusters in range_n_clusters:
    kmeans = KMeans(n_clusters=num_clusters, max_iter=50)
kmeans.fit(iris_df_scaled)

sse.append(kmeans.inertia_)

plt.plot(sse)

# 1. Kmeans with k=3
kmeans = KMeans(n_clusters=3, max_iter=50)
y = kmeans.fit_predict(iris_df_scaled)

y

iris_df['Label'] = kmeans.labels_
iris_df.head()

plt.scatter(iris_df_scaled[y == 0, 0], iris_df_scaled[y == 0, 1], s = 100, c = 'purple', label = 'Iris-setosa')
plt.scatter(iris_df_scaled[y == 1, 0], iris_df_scaled[y == 1, 1], s = 100, c = 'orange', label = 'Iris-versicolour')
plt.scatter(iris_df_scaled[y == 2, 0], iris_df_scaled[y == 2, 1], s = 100, c = 'green', label = 'Iris-virginica')

# 2. Hierarchical clustering
plt.figure(figsize=(15, 5))
mergings = linkage(iris_df_scaled,method='complete',metric='euclidean')
dendrogram(mergings)
plt.show()

cluster_hier = cut_tree(mergings,n_clusters=3).reshape(-1)

iris_df['Label'] = cluster_hier
iris_df.head()

plt.scatter(iris_df_scaled[cluster_hier == 0, 0], iris_df_scaled[cluster_hier == 0, 1], s = 100, c = 'purple', label = 'Iris-setosa')
plt.scatter(iris_df_scaled[cluster_hier == 1, 0], iris_df_scaled[cluster_hier == 1, 1], s = 100, c = 'orange', label = 'Iris-versicolour')
plt.scatter(iris_df_scaled[cluster_hier == 2, 0], iris_df_scaled[cluster_hier == 2, 1], s = 100, c = 'green', label = 'Iris-virginica')


问:
MDX Sum for an ordered Set
I want to create a measure for the running total of sales.

The customer dimension need to be ordered by their sales amount.
Want I want to get:

H1
Sales
CumSales

B
10
10

C
3
13

A
2
15

Thank you!

If I use

```<code>CREATE MEMBER CURRENTCUBE.[Measures].[CumSales]
AS sum({null: [Kunden].[H1].CurrentMember}, [Measures].[ABSTCK In Mille]),
FORMAT_STRING = "Numeric",
NON_EMPTY_BEHAVIOR = { [ABSTCK In Mille] },
VISIBLE = 1 ,  DISPLAY_FOLDER = 'Calculations' ,  ASSOCIATED_MEASURE_GROUP = 'SAP Sales';
</code>```

(H1 is the customer hierachy name and represents the customer)
I get:

H1
Sales
CumSales

A
2
2

B
10
12

C
3
15

What I also managed (and might be used?) is to create the ordered customer Set ("KundenOrderedByABSTCK") and create a measure for the order index ("KundenOrderedByABSTCK_RowNr")

```<code>CREATE DYNAMIC SET CURRENTCUBE.[KundenOrderedByABSTCK]
 AS order([Kunden].[H1].[H1].Members,[Measures].[ABSTCK In Mille],DESC) ;

//works fine
//Ranking Nr.
CREATE MEMBER CURRENTCUBE.[Measures].[KundenOrderedByABSTCK_RowNr]
AS RANK([Kunden].[H1].CurrentMember, KundenOrderedByABSTCK),
FORMAT_STRING = "0",
NON_EMPTY_BEHAVIOR = { [ABSTCK In Mille] },
VISIBLE = 1 ,  DISPLAY_FOLDER = 'Calculations' ,  ASSOCIATED_MEASURE_GROUP = 'SAP Sales';
</code>```

Title: MDX Sum for an ordered Set

Body:
I want to create a measure for the running total of sales.

The customer dimension need to be ordered by their sales amount.
Want I want to get:

H1
Sales
CumSales

B
10
10

C
3
13

A
2
15

Thank you!

If I use

CREATE MEMBER CURRENTCUBE.[Measures].[CumSales]
AS sum({null: [Kunden].[H1].CurrentMember}, [Measures].[ABSTCK In Mille]),
FORMAT_STRING = "Numeric",
NON_EMPTY_BEHAVIOR = { [ABSTCK In Mille] },
VISIBLE = 1 ,  DISPLAY_FOLDER = 'Calculations' ,  ASSOCIATED_MEASURE_GROUP = 'SAP Sales';

(H1 is the customer hierachy name and represents the customer)
I get:

H1
Sales
CumSales

A
2
2

B
10
12

C
3
15

What I also managed (and might be used?) is to create the ordered customer Set ("KundenOrderedByABSTCK") and create a measure for the order index ("KundenOrderedByABSTCK_RowNr")

CREATE DYNAMIC SET CURRENTCUBE.[KundenOrderedByABSTCK]
 AS order([Kunden].[H1].[H1].Members,[Measures].[ABSTCK In Mille],DESC) ;

//works fine
//Ranking Nr.
CREATE MEMBER CURRENTCUBE.[Measures].[KundenOrderedByABSTCK_RowNr]
AS RANK([Kunden].[H1].CurrentMember, KundenOrderedByABSTCK),
FORMAT_STRING = "0",
NON_EMPTY_BEHAVIOR = { [ABSTCK In Mille] },
VISIBLE = 1 ,  DISPLAY_FOLDER = 'Calculations' ,  ASSOCIATED_MEASURE_GROUP = 'SAP Sales';


问:
CORS: Preflight Missing Allow Origin Header
I am using nginx with PHP and Vue. I`m struggling with CORS error like in a title. I can make normal Fetch requests, however when i want to make some application error from backend (for example, when someone want to create a account, and login is already taken). Im getting Error like in title:

Fetch failed and latern in Network Tab in Dev Tools:
CORS: Preflight Missing Allow Origin Header

Here is my nginx.conf:

```<code>server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    server_tokens off;

    root /app/;
    index index.php;

    add_header "Access-Control-Allow-Origin"  *;
    add_header "Access-Control-Allow-Headers" *;

    location / {

        try_files $uri $uri/ /index.php$is_args$args;

    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}
</code>```

Way i try to send error:

```<code>        header("HTTP/1.0 460 Aplication Error");
        header("Content-Type: application/json");
        json_encode($error);
</code>```

Am i trying to do in proper way at all?

PS Update, i cant change this header, when using calling it by fetch from  Vue CLI Server, when i call it directly for example in browser it works correctly

Body:
I am using nginx with PHP and Vue. I`m struggling with CORS error like in a title. I can make normal Fetch requests, however when i want to make some application error from backend (for example, when someone want to create a account, and login is already taken). Im getting Error like in title:

Fetch failed and latern in Network Tab in Dev Tools:
CORS: Preflight Missing Allow Origin Header

Here is my nginx.conf:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    server_tokens off;

    root /app/;
    index index.php;

    add_header "Access-Control-Allow-Origin"  *;
    add_header "Access-Control-Allow-Headers" *;

    location / {

        try_files $uri $uri/ /index.php$is_args$args;

    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

Way i try to send error:

        header("HTTP/1.0 460 Aplication Error");
        header("Content-Type: application/json");
        json_encode($error);

Am i trying to do in proper way at all?

PS Update, i cant change this header, when using calling it by fetch from  Vue CLI Server, when i call it directly for example in browser it works correctly


问:
Using bisect efficiently with the keys of an OrderedDict

I'm looking for the fastest way to do the following: given a dictionary and a key value, return the lowest key in the dictionary greater than than the value given.  Per this question, the natural way would seem to be to create an OrderedDict, then use bisect on the keys to find the proper key location. The OrderedDict.keys() method doesn't support indexing, so per e.g. this question, one has to convert the keys to a list, before doing bisect or similar.

So once an OrderedDict has been created with its keys in order, in order to access the correct position one has to do the following:

Convert the keys to a list

Do a binary search of the keys with bisect or similar.

Check that this insertion point isn't at the end of the list, before retrieving the key located after this index.

Retrieve the key value in our original OrderedDict.

I'm most concerned about step 1 above, from an efficiency perspective (although all of this looks roundabout to me).  Without knowing the details of how Python does the conversion to list, it seems like it would have to be O(n), completely eliminating the savings of using OrderedDict and binary search.  I'm hoping someone can tell me whether this assumption I have about step 1 is or isn't correct, and regardless whether or not there may be a better method.

As an alternative, I could simply create a list of tuples, sorted by the first element (key), where the second element is the dict value associated with that key.  Then I could pass the key lambda x:x[0] to bisect.  This seems reasonable, but I'd prefer to store my key / value pairs more uniformly (e.g. JSON), since that's how it's done with other dicts in the same project that don't need this specific type of comparison.

Here's some example code for a single lookup.  Edit: But lest anyone think I'm over-optimizing, the actual dictionary has ~3 million keys, and will be accessed ~7 million times in a batch, daily. So I'm very interested in finding a fast way of doing this.

```<code># Single lookup example
from collections import OrderedDict
from bisect import bisect

d = OrderedDict()
d[5] = 'lowest_value'
d[7] = 'middle_value'
d[12] = 'highest_value'

sample_key = 6    # we want to find the value for the key above this in d, e.g. d[7]

list_of_keys = list(d.keys())
key_insertion_index = bisect(list_of_keys,sample_key)

if key_insertion_index < len(list_of_keys):
    next_higher_key = list_of_keys[key_insertion_index]
    v = d[next_higher_key]
</code>```

Body:
I'm looking for the fastest way to do the following: given a dictionary and a key value, return the lowest key in the dictionary greater than than the value given.  Per this question, the natural way would seem to be to create an OrderedDict, then use bisect on the keys to find the proper key location. The OrderedDict.keys() method doesn't support indexing, so per e.g. this question, one has to convert the keys to a list, before doing bisect or similar.

So once an OrderedDict has been created with its keys in order, in order to access the correct position one has to do the following:

Convert the keys to a list

Do a binary search of the keys with bisect or similar.

Check that this insertion point isn't at the end of the list, before retrieving the key located after this index.

Retrieve the key value in our original OrderedDict.

I'm most concerned about step 1 above, from an efficiency perspective (although all of this looks roundabout to me).  Without knowing the details of how Python does the conversion to list, it seems like it would have to be O(n), completely eliminating the savings of using OrderedDict and binary search.  I'm hoping someone can tell me whether this assumption I have about step 1 is or isn't correct, and regardless whether or not there may be a better method.

As an alternative, I could simply create a list of tuples, sorted by the first element (key), where the second element is the dict value associated with that key.  Then I could pass the key lambda x:x[0] to bisect.  This seems reasonable, but I'd prefer to store my key / value pairs more uniformly (e.g. JSON), since that's how it's done with other dicts in the same project that don't need this specific type of comparison.

Here's some example code for a single lookup.  Edit: But lest anyone think I'm over-optimizing, the actual dictionary has ~3 million keys, and will be accessed ~7 million times in a batch, daily. So I'm very interested in finding a fast way of doing this.

# Single lookup example
from collections import OrderedDict
from bisect import bisect

d = OrderedDict()
d[5] = 'lowest_value'
d[7] = 'middle_value'
d[12] = 'highest_value'

sample_key = 6    # we want to find the value for the key above this in d, e.g. d[7]

list_of_keys = list(d.keys())
key_insertion_index = bisect(list_of_keys,sample_key)

if key_insertion_index < len(list_of_keys):
    next_higher_key = list_of_keys[key_insertion_index]
    v = d[next_higher_key]


问:
Node JS Express app, need to wait until postgres notify triggers all execute to load page
I have user files stored on S3 and links to those files in my postgres database. When that row in postgres gets deleted, I have a trigger that notifies my express server to run some code to delete the file from S3 as well. This all works great except for the delete route that caused the trigger, redirects before the code has finished running for deleting from S3 and that causes some problem in the UI that is rendered.

So my objective is to wait until the function on my server that is triggered by postgres completes before redirecting from my route.

How can I wait for a postgres trigger and the notify listener function, before completing the request response cycle of my express route?

Thanks


问:
Android Compose how to test group of Boxes?
I practice writing ui tests. Now for practice, I decided to write tests for HorizontalPagerIndicator (accompanist).

As you can see inside the HorizontalPagerIndicator is drawn n  boxes (https://github.com/google/accompanist/blob/main/pager-indicators/src/main/java/com/google/accompanist/pager/PagerIndicator.kt).

First of all, in my test I would like to check that the number of shapes in the HorizontalPagerIndicator is equal to the number of pages.

I tried the following to see the Semantic tree of a compose node:

```<code>onRoot(useUnmergedTree = true).printToLog("TEST_TAG")
</code>```

And I found that the indicator node does not have any child. So I can't access the ones created inside the indicator boxes and check their number.

I would also like to check that when the pager page changes, the position of the indicator also changes.I don't have any ideas for implementing such a check. Please help me solve this problem. Perhaps I do not understand how to test this component at all.

Body:
I practice writing ui tests. Now for practice, I decided to write tests for HorizontalPagerIndicator (accompanist).

As you can see inside the HorizontalPagerIndicator is drawn n  boxes (https://github.com/google/accompanist/blob/main/pager-indicators/src/main/java/com/google/accompanist/pager/PagerIndicator.kt).

First of all, in my test I would like to check that the number of shapes in the HorizontalPagerIndicator is equal to the number of pages.

I tried the following to see the Semantic tree of a compose node:

onRoot(useUnmergedTree = true).printToLog("TEST_TAG")

And I found that the indicator node does not have any child. So I can't access the ones created inside the indicator boxes and check their number.

I would also like to check that when the pager page changes, the position of the indicator also changes.I don't have any ideas for implementing such a check. Please help me solve this problem. Perhaps I do not understand how to test this component at all.


问:
What is the PYQT6 equivalent of PYQT5 QWinThumbnailToolButton Class?
spotify example of thumbnail button

I'm trying to implement these thumbnail buttons for my pyqt6 application, however, it looks like pyqt6 has made the QWinThumbnailToolButton class obsolete.

In the changes module: https://doc.qt.io/qt-6/extras-changes-qt6.html, it says that there are explicit replacements, so I've tried looking around the pyqt6 QWindow, and QWidget documentation for any leads but its gotten me nowhere. Does anyone know of a possible solution in PYQT6?


问:
I need to assign a custom domain to my nginx server
I have a cloudflare domain and a nginx website with a ported ip so it's like ip:port and I need to assign the domain to the nignx server. I haven't altered the nginx config, but I have the key.pem and cert.pem in the nginx directory. I have looked in lots of places, but I can't find a nginx config for the key.pem and cert.pem and I can't find out how to link the domain to the server since it's a ported ip.

I need to find out how to link my cloudflare domain to a ported ip and i need a new nginx config.


问:
Flutter: non-asset local image
I'd like to include images in my Flutter application which are not asset images.

Let me clarify a bit. I am working with an embedded Unity application inside the Flutter app. I can communicate bidirectionally and part of the communication is sending a file location from Flutter to Unity, such that the Unity app can read that image and do something with it (e.g. a texture). But since assets are not directly accessible by location, I cannot give the path to the Unity part of the application.

So would there be a way to include images in the app and reference them by old school path?

Title: Flutter: non-asset local image


问:
AWS Api gateway Mapping template VTL
I'm trying to configure data mappings from method request data from an API.
VTL as used in AWS API Gateway. Can I use Generic Tools like JsonTool or MathTool in the Mapping Template section?</p>

Title: AWS Api gateway Mapping template VTL


问:
How to set width and height to a richtextbox and do not grow rather hide overflow
I'm using Lexical with React, when use same logic as shown on playground I can see the size of the richtextbox is determined by how big my toolbar is. If I don't want a toolbar, where should I set a width and height for initial richtextbox?
And is there API I can use to update those later?

Another related question is how can I set it to be fix size without auto-grow? I want to see if it can hide the overflow, or stop user from typing

Be able to update the textbox size.
Be able to change to not grow.


问:
Sort simplexml object - without casting to array
Is it possible to sort a simplexml object but keep the object as a simplexml object instead of casting to an array.

There doesnt appear to be a way to do this - and if casted to an array it seems very messy to transform the array(s) back to a simplexml object.

So -

Is it possible to sort a simplexml object by an attribute etc.

For example (sort by the position attribute node):

```<code><test_nodes>
  <node position="1"></node>
  <node position="2"></node>
  <node position="3"></node>
</test_nodes>
</code>```

If not then what is the most painless and efficient way to cast an array to a simple xml object

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to sort a simplexml object but keep the object as a simplexml object instead of casting to an array.

There doesnt appear to be a way to do this - and if casted to an array it seems very messy to transform the array(s) back to a simplexml object.

So -

Is it possible to sort a simplexml object by an attribute etc.

For example (sort by the position attribute node):

<test_nodes>
  <node position="1"></node>
  <node position="2"></node>
  <node position="3"></node>
</test_nodes>

If not then what is the most painless and efficient way to cast an array to a simple xml object


问:
How to make a program return to how it was loaded up? (vb)
I'm trying to code a VB program that when a button is pressed the system returns all text boxes, variables and forms to how they were when the program first loaded up.

I have managed to do it manually but there must be a faster and better way to do it. I'm being graded on this program any help is appreciated


问:
Can I change the field A marked with @id to a different field B in a domain object class in spring jpa?
I have a  Data Access Object class as following :

```<code>public interface UserRepository extends MongoRepository<User, String> {
     Optional<User> findOneByUserName(String userName);
}
</code>```

and the domain object or a POJO class 'User'

```<code>@Document
public class User {

    @Id
    private String name;
    private String email;
    private String password;
}
</code>```

Now I want to change @Id from name to email

```<code>
    private String name;
    @Id
    private String email;
    private String password;
</code>```

But my doubt is If I do that now will it have any drastic or unwanted effect on the existing data in the database??

Body:
I have a  Data Access Object class as following :

public interface UserRepository extends MongoRepository<User, String> {
     Optional<User> findOneByUserName(String userName);
}

and the domain object or a POJO class 'User'

@Document
public class User {

    @Id
    private String name;
    private String email;
    private String password;
}

Now I want to change @Id from name to email

    private String name;
    @Id
    private String email;
    private String password;

But my doubt is If I do that now will it have any drastic or unwanted effect on the existing data in the database??


问:
How can I use REST API to select and show the result in these radio buttons. These aren't working properly yet
```<code>How can I use REST API to select and show the result in these radio buttons. These aren't working properly yet.

<body>
    <form id="user-form">
        <div>
            <input type="radio" name="firstanswer" id="answer1" value="GET">
            <label for="answer1">GET</label><br>
            <input type="radio" name="firstanswer" id="answer2" value="POST">
            <label for="answer2">POST</label><br>
        </div>
        <div>
            <input type="radio" name="secondanswer" id="answer3" value="The">
            <label for="answer3">The</label><br>
            <input type="radio" name="secondanswer" id="answer4" value="Happy">
            <label for="answer4">Happy</label><br>
            <input type="radio" name="secondanswer" id="answer5" value="Sad">
            <label for="answer5">Sad</label><br>
            <input type="radio" name="secondanswer" id="answer6" value="Lazy">
            <label for="answer6">Lazy</label><br>
        </div>
        <div>
            <input type="radio" name="thirdanswer" id="answer7" value="Cat">
            <label for="answer7">Cat</label><br>
            <input type="radio" name="thirdanswer" id="answer8" value="Dog">
            <label for="answer8">Dog</label><br>
            <input type="radio" name="thirdanswer" id="answer9" value="Fox">
            <label for="answer9">Fox</label><br>
            <input type="radio" name="thirdanswer" id="answer10" value="Bear">
            <label for="answer10">Bear</label><br>
        </div>
        <input type="submit" value="Perform Operation">
    </form>
    <h1 id="result"></h1>

    <script>
        var form = document.getElementById("user-form");
        form.addEventListener('submit', function(e){
            e.preventDefault();
            saveResponse();
        })
        async function saveResponse()
        {
            var type = document.getElementById("answer1").value;
            var title = document.getElementById("answer3").value;
            var body = document.getElementById("answer7").value;
            const response = await fetch('https://jsonplaceholder.typicode.com/posts',
            {
                method: 'POST',

                body: JSON.stringify({
                    type: type,
                    title: title,
                    body: body,
                }),

                headers:{
                    'Content-type':'application/json; charset=utf-8'
                },
            })
            if(!response.ok)
            {
                throw new Error("Something went wrong" + response.statusText)
            }
                const data = await response.json()
                console.log(data)
                var serverresponse = "Type: " + data.type + "<br/>" + "Body: " + data.title + " " +data.body
                document.getElementById("result").innerHTML = serverresponse
        }

    </script>
</body>
</code>```

How can I use REST API to select and show the result in these radio buttons. These aren't working properly yet.How can I use REST API to select and show the result in these radio buttons. These aren't working properly yet.How can I use REST API to select and show the result in these radio buttons. These aren't working properly yet.

API must be used
Example of output must be

Type: GET
Body: Lazy Cat

Type: GET
Body: The Dog

Type: POST
Body: Sad Fox

Body:
How can I use REST API to select and show the result in these radio buttons. These aren't working properly yet.

    <form id="user-form">

            <input type="radio" name="firstanswer" id="answer1" value="GET">
            GET

            <input type="radio" name="firstanswer" id="answer2" value="POST">
            POST

            <input type="radio" name="secondanswer" id="answer3" value="The">
            The

            <input type="radio" name="secondanswer" id="answer4" value="Happy">
            Happy

            <input type="radio" name="secondanswer" id="answer5" value="Sad">
            Sad

            <input type="radio" name="secondanswer" id="answer6" value="Lazy">
            Lazy

            <input type="radio" name="thirdanswer" id="answer7" value="Cat">
            Cat

            <input type="radio" name="thirdanswer" id="answer8" value="Dog">
            Dog

            <input type="radio" name="thirdanswer" id="answer9" value="Fox">
            Fox

            <input type="radio" name="thirdanswer" id="answer10" value="Bear">
            Bear

        <input type="submit" value="Perform Operation">
    </form>

How can I use REST API to select and show the result in these radio buttons. These aren't working properly yet.How can I use REST API to select and show the result in these radio buttons. These aren't working properly yet.How can I use REST API to select and show the result in these radio buttons. These aren't working properly yet.

API must be used
Example of output must be

Type: GET
Body: Lazy Cat

Type: GET
Body: The Dog

Type: POST
Body: Sad Fox


问:
A tip on the way forward for using many sprite sheets in a 2D video game
What would you advise me to do to properly manage the loading and management of more animations and where can I find some code C++ examples ?</p>


问:
PySpark with io.github.spark-redshift-community: BasicAWSCredentialsProvider not found
I'm trying to load data from my redshift database using PySpark.

I'm using "io.github.spark-redshift-community" as connector. It's requires a "tempdir" parameter to use a S3. My code looks like the following:

```<code>import findspark
findspark.add_packages("io.github.spark-redshift-community:spark-redshift_2.12:5.0.3")
findspark.add_packages("com.amazonaws:aws-java-sdk-bundle:1.12.262")
findspark.add_packages("org.apache.hadoop:hadoop-aws:3.3.4")
findspark.init()

spark = SparkSession.builder.master("local[8]").appName("Dim_Customer").getOrCreate()

spark._jsc.hadoopConfiguration().set("fs.s3a.access.key", S3_ACCESS_KEY)
spark._jsc.hadoopConfiguration().set("fs.s3a.secret.key", S3_SECRET_KEY)
spark._jsc.hadoopConfiguration().set("fs.s3a.impl","org.apache.hadoop.fs.s3a.S3AFileSystem")
spark._jsc.hadoopConfiguration().set("com.amazonaws.services.s3a.enableV4", "true")
spark._jsc.hadoopConfiguration().set("fs.s3a.aws.credentials.provider","org.apache.hadoop.fs.s3a.BasicAWSCredentialsProvider")
spark._jsc.hadoopConfiguration().set("fs.s3a.connection.ssl.enabled", "true")

df_read_1 = spark.read \
        .format("io.github.spark_redshift_community.spark.redshift") \
        .option("url", "jdbc:redshift://IP/DATABASE?user=USER&password=PASS") \
        .option("dbtable", "table") \
        .option("tempdir", "s3a://url/")\
        .option("forward_spark_s3_credentials", "true") \
        .load()
</code>```

But I'm getting an error: Class org.apache.hadoop.fs.s3a.BasicAWSCredentialsProvider not found

I've fond some sources saying to change BasicAWSCredentialsProvider to SimpleAWSCredentialsProvider, but I get another error: NoSuchMethodError.

Could someone help me, please?
Is that any problem with the hadoop and aws-java-sdk versions?

Thank you in advance!

Body:
I'm trying to load data from my redshift database using PySpark.

I'm using "io.github.spark-redshift-community" as connector. It's requires a "tempdir" parameter to use a S3. My code looks like the following:

import findspark
findspark.add_packages("io.github.spark-redshift-community:spark-redshift_2.12:5.0.3")
findspark.add_packages("com.amazonaws:aws-java-sdk-bundle:1.12.262")
findspark.add_packages("org.apache.hadoop:hadoop-aws:3.3.4")
findspark.init()

spark = SparkSession.builder.master("local[8]").appName("Dim_Customer").getOrCreate()

spark._jsc.hadoopConfiguration().set("fs.s3a.access.key", S3_ACCESS_KEY)
spark._jsc.hadoopConfiguration().set("fs.s3a.secret.key", S3_SECRET_KEY)
spark._jsc.hadoopConfiguration().set("fs.s3a.impl","org.apache.hadoop.fs.s3a.S3AFileSystem")
spark._jsc.hadoopConfiguration().set("com.amazonaws.services.s3a.enableV4", "true")
spark._jsc.hadoopConfiguration().set("fs.s3a.aws.credentials.provider","org.apache.hadoop.fs.s3a.BasicAWSCredentialsProvider")
spark._jsc.hadoopConfiguration().set("fs.s3a.connection.ssl.enabled", "true")

df_read_1 = spark.read \
        .format("io.github.spark_redshift_community.spark.redshift") \
        .option("url", "jdbc:redshift://IP/DATABASE?user=USER&password=PASS") \
        .option("dbtable", "table") \
        .option("tempdir", "s3a://url/")\
        .option("forward_spark_s3_credentials", "true") \
        .load()

But I'm getting an error: Class org.apache.hadoop.fs.s3a.BasicAWSCredentialsProvider not found

I've fond some sources saying to change BasicAWSCredentialsProvider to SimpleAWSCredentialsProvider, but I get another error: NoSuchMethodError.

Could someone help me, please?
Is that any problem with the hadoop and aws-java-sdk versions?

Thank you in advance!


问:
How to save state of a page after getting data from a route
Image, title, price and description are saved in the database (SQlite

i send the saved data to the listing screen with navigation

const sendMeToNewList=()=>{
        return(
            <View>
                {
                    dataFromDatabase &&
                    navigation.navigate('listings',{image:image, title:title, price:price, description:description})
                }

            </View>

        )
    }```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function ListingScreen({navigation}, props) {
    const route = useRoute();
    const myroute = route.params

    return (
        <View style={{flex: 1}}>
         <ScrollView>
            <View style={styles.container}>
                <View style={styles.cardContainer}>
                    {
                        !myroute &&
                        <View>
                        <TouchableOpacity activeOpacity="0.6" onPress ={()=> navigation.navigate("listingdetail")}>
                <Image style={styles.image}
                       source={require('../assets/redphone.jpg')}
                />
                </TouchableOpacity>
                <Text style={styles.productTitle}>RedIphone for Sale</Text>
                <Text style={styles.productPrice}>$950</Text>
                        </View>

                    }
                    {
                        myroute &&
                        <View>
                            <TouchableOpacity activeOpacity="0.6" onPress ={()=> navigation.navigate("listingdetail")}>
                                <Image style={styles.image}source={{ uri: myroute.image }} />
                            </TouchableOpacity>
                            <Text style={styles.productTitle}>{myroute.title}</Text>
                            <Text style={styles.productPrice}>{myroute.price}</Text>
                            <Text style={styles.productDescription}>{myroute.description}</Text>
                        </View>
                    }</code>```

)
The above snippet will display the data with the image but once I refresh the page it vanishes. How can I save the data and pass it through to another screen?

Body:
Image, title, price and description are saved in the database (SQlite

i send the saved data to the listing screen with navigation

const sendMeToNewList=()=>{
        return(
            <View>
                {
                    dataFromDatabase &&
                    navigation.navigate('listings',{image:image, title:title, price:price, description:description})
                }

            </View>

        )
    }

function ListingScreen({navigation}, props) {
    const route = useRoute();
    const myroute = route.params

    return (
        <View style={{flex: 1}}>
         <ScrollView>
            <View style={styles.container}>
                <View style={styles.cardContainer}>
                    {
                        !myroute &&
                        <View>
                        <TouchableOpacity activeOpacity="0.6" onPress ={()=> navigation.navigate("listingdetail")}>
                <Image style={styles.image}
                       source={require('../assets/redphone.jpg')}
                />
                </TouchableOpacity>
                <Text style={styles.productTitle}>RedIphone for Sale</Text>
                <Text style={styles.productPrice}>$950</Text>
                        </View>

                    }
                    {
                        myroute &&
                        <View>
                            <TouchableOpacity activeOpacity="0.6" onPress ={()=> navigation.navigate("listingdetail")}>
                                <Image style={styles.image}source={{ uri: myroute.image }} />
                            </TouchableOpacity>
                            <Text style={styles.productTitle}>{myroute.title}</Text>
                            <Text style={styles.productPrice}>{myroute.price}</Text>
                            <Text style={styles.productDescription}>{myroute.description}</Text>
                        </View>
                    }

)
The above snippet will display the data with the image but once I refresh the page it vanishes. How can I save the data and pass it through to another screen?


问:
Fluent NHibernate foreign key is null
I have two tables - master-detail with relation one-to-many.

Here are definitions and mappings:

```<code>public class Employee
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual IList<Project> Projects { get; set; }

    public Employee()
    {
        Projects = new List<Project>();
    }
}

public class Project
{
    public virtual int Id { get; protected set; }
    public virtual string Name { get; set; }
    public virtual double EstimatedHours { get; set; }
    public virtual Employee Employee { get; set; }
}

public EmployeeMap()
{
    Id(x => x.Id);
    Map(x => x.FirstName);
    Map(x => x.LastName);

    HasMany<Project>(x => x.Projects)
        .KeyColumn("Id_emp")
        .Cascade.All()
        .Inverse()
        .LazyLoad();
}

public ProjectMap()
{
   Id(x => x.Id);
   Map(x => x.Name);
   Map(x => x.EstimatedHours);

   References(x => x.Employee).Class<Employee>().Columns("Id_emp").ForeignKey();
}
</code>```

When I save data both employee and project tables are filled with data but in project table field Id_emp is null instead to have Id of employee.

What am I missing in mappings and referencing?

Title: Fluent NHibernate foreign key is null

Body:
I have two tables - master-detail with relation one-to-many.

Here are definitions and mappings:

public class Employee
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual IList<Project> Projects { get; set; }

    public Employee()
    {
        Projects = new List<Project>();
    }
}

public class Project
{
    public virtual int Id { get; protected set; }
    public virtual string Name { get; set; }
    public virtual double EstimatedHours { get; set; }
    public virtual Employee Employee { get; set; }
}

public EmployeeMap()
{
    Id(x => x.Id);
    Map(x => x.FirstName);
    Map(x => x.LastName);

    HasMany<Project>(x => x.Projects)
        .KeyColumn("Id_emp")
        .Cascade.All()
        .Inverse()
        .LazyLoad();
}

public ProjectMap()
{
   Id(x => x.Id);
   Map(x => x.Name);
   Map(x => x.EstimatedHours);

   References(x => x.Employee).Class<Employee>().Columns("Id_emp").ForeignKey();
}

When I save data both employee and project tables are filled with data but in project table field Id_emp is null instead to have Id of employee.

What am I missing in mappings and referencing?


问:
Make search result in lazy column clickable
I have an hymn book app with a search button on button click it opens a search bar page. This page goes through the data class and returns the result of the text if it is found in the list of items in the data class. The search bar produces the required result of the string in a new lazy column but it doesn't go to hymnscreen.

```<code>val viewModel: SearchViewModel = viewModel()
val songList = viewModel.list.observeAsState().value

LazyColumn {
    if (!songList.isNullOrEmpty()) {
        items(songList) { song ->
            Card(modifier = Modifier
.clickable(onClick ={
HymnActivity:class.java).apply{
                         putExtra("SONG_KEY",song)
})
.fillMaxWidth(),
shape = RoundedShape(10.dp))
{
Text(
                text = song.title,
                style = MaterialTheme.typography.h6,
                color = MaterialTheme.colors.onBackground,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 12.dp)
                    .wrapContentWidth(Alignment.Start)
            )
        }
}
    }
}
</code>```

I tried making the card in the lazy column clickable

```<code>context.startActivity(Intent(HymnActivity::class.java))
</code>```

It didn't work. There are multiple Items in the list. And a view model that goes through the items in that list. That should connect to a composable and show a screen title = song.title

lyrics = song.lyrics

Body:
I have an hymn book app with a search button on button click it opens a search bar page. This page goes through the data class and returns the result of the text if it is found in the list of items in the data class. The search bar produces the required result of the string in a new lazy column but it doesn't go to hymnscreen.

val viewModel: SearchViewModel = viewModel()
val songList = viewModel.list.observeAsState().value

LazyColumn {
    if (!songList.isNullOrEmpty()) {
        items(songList) { song ->
            Card(modifier = Modifier
.clickable(onClick ={
HymnActivity:class.java).apply{
                         putExtra("SONG_KEY",song)
})
.fillMaxWidth(),
shape = RoundedShape(10.dp))
{
Text(
                text = song.title,
                style = MaterialTheme.typography.h6,
                color = MaterialTheme.colors.onBackground,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 12.dp)
                    .wrapContentWidth(Alignment.Start)
            )
        }
}
    }
}

I tried making the card in the lazy column clickable

context.startActivity(Intent(HymnActivity::class.java))

It didn't work. There are multiple Items in the list. And a view model that goes through the items in that list. That should connect to a composable and show a screen title = song.title

lyrics = song.lyrics


问:
I've updated CF9 mail server settings but my application is still trying to use the old mail server
We changed our exchange mail server so I've update the mail server in CF9 admin settings. I've verified that it can connect to the new server and it can. But when I test sending an email it keeps failing because it is trying to connect to the old mail server. When I look in the mail.log it clearly lists the old server as the SMTP host it is trying to connect to and it fails.

Where else could CF9 be pulling the old mail server from?
Are there other places where my predecessor could have coded in the old mail server?

I've looked in various .cfm files for any reference to the old exchange server but have found none.

Thanks,
Dan

Ok so what I ended up doing was to actually hard code the new server into the one location we are actually using a cfmail tag. That fixed it. Not much of a chance this app will ever do anything other than this so should be fine.

Dan


问:
I can't fully read and output a xml file
In line 81, I get an error: 'str' object has no attribute 'getCode'
but then I don't understand why lines 80-83 work fine.
I need to implement reading and writing an xml file.
The deliveries class has 2 fields of other classes (parts and providers).
I don't understand how to make a mistake, please give me a hint.

```<code>import os,xml.dom.minidom
from data import data

class dataxml(data):
    def read(self):
        dom=xml.dom.minidom.parse(self.getInp())
        dom.normalize()
        for node in dom.childNodes[0].childNodes:
            if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='providers'):
                code,provider,title,adres,telephone=0,"","","",""
                for t in node.attributes.items():
                    if t[0]=="code":code=int(t[1])
                    if t[0]=="provider":provider=t[1]
                    if t[0]=="title":title=t[1]
                    if t[0]=="adres":adres=t[1]
                    if t[0]=="telephone":telephone=t[1]
                self.getLib().createProviders(code,provider,title,adres,telephone)

            if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='parts'):
                code,title,articule,price,note=0,"",0,0,""
                for t in node.attributes.items():
                    if t[0]=="code":code=int(t[1])
                    if t[0]=="title":title=t[1]
                    if t[0]=="articule":articule=int(t[1])
                    if t[0]=="price":price=int(t[1])
                    if t[0]=="note":note=t[1]
                self.getLib().createParts(code, title, articule, price, note)

            if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='deliveries'):
                code,providers,parts,guantity,date=0,None,None,0,""
                for t in node.attributes.items():
                    if t[0]=="code":code=int(t[1])
                    if t[0]=="guantity":guantity=int(t[1])
                    if t[0]=="providers":
                        providers=self.getLib().getProviders(int(t[1]))
                    if t[0]=="parts":
                        parts=self.getLib().getParts(int(t[1]))
                    if t[0]=="date":date=t[1]
                self.getLib().createDeliveries(code,providers,parts,guantity,date)

    def write(self):
        dom=xml.dom.minidom.Document()
        root=dom.createElement("shop")
        dom.appendChild(root)

        for a in self.getLib().getProvidersList():
            pro=dom.createElement("providers")
            pro.setAttribute('code',str(a.getCode()))
            pro.setAttribute('provider',a.getProvider())
            pro.setAttribute('title',a.getTitle())
            pro.setAttribute('adres',a.getAdres())
            pro.setAttribute('telephone',a.getTelephone())
            root.appendChild(pro)

        for p in self.getLib().getPartsList():
            par=dom.createElement("parts")
            par.setAttribute('code',str(p.getCode()))
            par.setAttribute('title',p.getTitle())
            par.setAttribute('articule',str(p.getArticule()))
            par.setAttribute('price',str(p.getPrice()))
            par.setAttribute('note',p.getNote())
            root.appendChild(par)

        for b in self.getLib().getDeliveriesList():
            de=dom.createElement("deliveries")
            de.setAttribute('code',str(b.getCode()))
            de.setAttribute('guantity',str(b.getGuantity()))
            de.setAttribute('date',b.getDate())

            if b.getProviders():
                pc=b.getProviders().getCode()
            else:pc=""
            de.setAttribute('providers',str(pc))

            if b.getParts():
                ppc=b.getParts().getCode()          #'str' object has no attribute 'getCode'
            else:ppc=""
            de.setAttribute('parts',str(ppc))

            root.appendChild(de)

        f = open(self.getOut(),"w")
        #f.write(dom.toprettyxml(encoding='utf-8'))
        f.write(dom.toprettyxml())

</code>```

I tried to do this, but there were only more mistakes.

```<code>for b in self.getLib().getDeliveriesList():
            de=dom.createElement("deliveries")
            de.setAttribute('code',str(b.getCode()))
            de.setAttribute('guantity',str(b.getGuantity()))
            de.setAttribute('date',b.getDate())
            de.setAttribute('providers',b.getProviders()) #
            de.setAttribute('parts',b.getParts()) #

</code>```

Body:
In line 81, I get an error: 'str' object has no attribute 'getCode'
but then I don't understand why lines 80-83 work fine.
I need to implement reading and writing an xml file.
The deliveries class has 2 fields of other classes (parts and providers).
I don't understand how to make a mistake, please give me a hint.

import os,xml.dom.minidom
from data import data

class dataxml(data):
    def read(self):
        dom=xml.dom.minidom.parse(self.getInp())
        dom.normalize()
        for node in dom.childNodes[0].childNodes:
            if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='providers'):
                code,provider,title,adres,telephone=0,"","","",""
                for t in node.attributes.items():
                    if t[0]=="code":code=int(t[1])
                    if t[0]=="provider":provider=t[1]
                    if t[0]=="title":title=t[1]
                    if t[0]=="adres":adres=t[1]
                    if t[0]=="telephone":telephone=t[1]
                self.getLib().createProviders(code,provider,title,adres,telephone)

            if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='parts'):
                code,title,articule,price,note=0,"",0,0,""
                for t in node.attributes.items():
                    if t[0]=="code":code=int(t[1])
                    if t[0]=="title":title=t[1]
                    if t[0]=="articule":articule=int(t[1])
                    if t[0]=="price":price=int(t[1])
                    if t[0]=="note":note=t[1]
                self.getLib().createParts(code, title, articule, price, note)

            if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='deliveries'):
                code,providers,parts,guantity,date=0,None,None,0,""
                for t in node.attributes.items():
                    if t[0]=="code":code=int(t[1])
                    if t[0]=="guantity":guantity=int(t[1])
                    if t[0]=="providers":
                        providers=self.getLib().getProviders(int(t[1]))
                    if t[0]=="parts":
                        parts=self.getLib().getParts(int(t[1]))
                    if t[0]=="date":date=t[1]
                self.getLib().createDeliveries(code,providers,parts,guantity,date)

    def write(self):
        dom=xml.dom.minidom.Document()
        root=dom.createElement("shop")
        dom.appendChild(root)

        for a in self.getLib().getProvidersList():
            pro=dom.createElement("providers")
            pro.setAttribute('code',str(a.getCode()))
            pro.setAttribute('provider',a.getProvider())
            pro.setAttribute('title',a.getTitle())
            pro.setAttribute('adres',a.getAdres())
            pro.setAttribute('telephone',a.getTelephone())
            root.appendChild(pro)

        for p in self.getLib().getPartsList():
            par=dom.createElement("parts")
            par.setAttribute('code',str(p.getCode()))
            par.setAttribute('title',p.getTitle())
            par.setAttribute('articule',str(p.getArticule()))
            par.setAttribute('price',str(p.getPrice()))
            par.setAttribute('note',p.getNote())
            root.appendChild(par)

        for b in self.getLib().getDeliveriesList():
            de=dom.createElement("deliveries")
            de.setAttribute('code',str(b.getCode()))
            de.setAttribute('guantity',str(b.getGuantity()))
            de.setAttribute('date',b.getDate())

            if b.getProviders():
                pc=b.getProviders().getCode()
            else:pc=""
            de.setAttribute('providers',str(pc))

            if b.getParts():
                ppc=b.getParts().getCode()          #'str' object has no attribute 'getCode'
            else:ppc=""
            de.setAttribute('parts',str(ppc))

            root.appendChild(de)

        f = open(self.getOut(),"w")
        #f.write(dom.toprettyxml(encoding='utf-8'))
        f.write(dom.toprettyxml())

I tried to do this, but there were only more mistakes.

for b in self.getLib().getDeliveriesList():
            de=dom.createElement("deliveries")
            de.setAttribute('code',str(b.getCode()))
            de.setAttribute('guantity',str(b.getGuantity()))
            de.setAttribute('date',b.getDate())
            de.setAttribute('providers',b.getProviders()) #
            de.setAttribute('parts',b.getParts()) #


问:
ME function and margin Function from twopm package rstudio
I ran my twopart model and I have tried following the but the margins and the AME commands to get the marginal effects on all the variables, but I am running into a really weird issue with the data frame for some reason.

```<code>> margin(tpmodel1)
Error in `[.data.frame`(newdata, , term) : undefined columns selected
</code>```

But when looking at the guide for the twopm package, it says that all I need to do is just AME(tpmodel1) or margin(tpmodel1) to get all the marginal effects and it is still giving that error. so then i did

```<code>> margin(tpmodel1, newdata = NULL, term = NULL, se=TRUE)
Error in `[.data.frame`(newdata, , term) : undefined columns selected
</code>```

And

```<code> > margin(tpmodel1, newdata = dfasthma, term = NULL, se=TRUE)
Error in margin(tpmodel1, newdata = dfasthma, term = NULL, se = TRUE) :
</code>```

some of independent variables of the two-part model are not available in the newdata set

of which doesnt make sense cause The data set i created for the variables I am using is dfasthma.

the code from the package:

```<code>margin(object, newdata = NULL, term = NULL, value = NULL,
se = TRUE, se.method = c("delta","bootstrap"), CI = TRUE, CI.boots = FALSE,
level = 0.95,eps = 1e-7,na.action = na.pass, iter = 50)
</code>```

The image attached is a guide to the margin command from the package

Body:
I ran my twopart model and I have tried following the but the margins and the AME commands to get the marginal effects on all the variables, but I am running into a really weird issue with the data frame for some reason.

> margin(tpmodel1)
Error in `[.data.frame`(newdata, , term) : undefined columns selected

But when looking at the guide for the twopm package, it says that all I need to do is just AME(tpmodel1) or margin(tpmodel1) to get all the marginal effects and it is still giving that error. so then i did

> margin(tpmodel1, newdata = NULL, term = NULL, se=TRUE)
Error in `[.data.frame`(newdata, , term) : undefined columns selected

And

 > margin(tpmodel1, newdata = dfasthma, term = NULL, se=TRUE)
Error in margin(tpmodel1, newdata = dfasthma, term = NULL, se = TRUE) :

some of independent variables of the two-part model are not available in the newdata set

of which doesnt make sense cause The data set i created for the variables I am using is dfasthma.

the code from the package:

margin(object, newdata = NULL, term = NULL, value = NULL,
se = TRUE, se.method = c("delta","bootstrap"), CI = TRUE, CI.boots = FALSE,
level = 0.95,eps = 1e-7,na.action = na.pass, iter = 50)

The image attached is a guide to the margin command from the package


问:
How to column filter data from multiple subobjects using PrimeNG Table?
I want to column filter multiple collection of data using PrimeNG table. The JSON response example below that every object have at least one of the three subobjects, leaving the other two subobjects null or not existant depending of a foreign key from the subobject model:

```<code>{
   "object": [
      {
         "id": 1,
         "name": "Object 1",
         "objType_1_id": 1,
         "objType_2_id": null,
         "objType_3_id": null,
         "objType_1": {
            "id": 1,
            "name": "Object type 1-1"
      },
      {
         "id": 2,
         "name": "Object 2",
         "objType_1_id": null,
         "objType_2_id": 1,
         "objType_3_id": null,
         "objType_2": {
            "id": 1,
            "name": "Object type 2-1"
      },
      {
         "id": 3,
         "name": "Object 3",
         "objType_1_id": null,
         "objType_2_id": null,
         "objType_3_id": 1,
         "objType_3": {
            "id": 1,
            "name": "Object type 3-1"
      },
      {
         "id": 4,
         "name": "Object 4",
         "objType_1_id": null,
         "objType_2_id": 2,
         "objType_3_id": null,
         "objType_3": {
            "id": 1,
            "name": "Object type 2-2"
      },
      {
         "id": 5,
         "name": "Object 4",
         "objType_1_id": 1,
         "objType_2_id": null,
         "objType_3_id": null,
         "objType_3": {
            "id": 1,
            "name": "Object type 1-1"
      }
   ]
}
</code>```

And so on. On the body of the p-table, I listed the subobject type of each object using 3 subobject "GETs" for each one on the samecolumn:

```<code><p-table [value]="objects">
   <ng-template pTemplate="header">
      <tr>
         <th>
            <p-columnFilter type="text" field=**The desired subobject names filter**></p-columnFilter>
         </th>
      </tr>
   <ng-template>
   <ng-template pTemplate="body" let-object>
      <tr>
         <th>
            {{object.objType_1?.name}}
            {{object.objType_2?.name}}
            {{object.objType_3?.name}}
         </th>
      </tr>
<p-table>
</code>```

As "the desired subject names filter" say above, I want to get filter the name of the three "object types" subobjects from each object. Any help is welcome.

Body:
I want to column filter multiple collection of data using PrimeNG table. The JSON response example below that every object have at least one of the three subobjects, leaving the other two subobjects null or not existant depending of a foreign key from the subobject model:

{
   "object": [
      {
         "id": 1,
         "name": "Object 1",
         "objType_1_id": 1,
         "objType_2_id": null,
         "objType_3_id": null,
         "objType_1": {
            "id": 1,
            "name": "Object type 1-1"
      },
      {
         "id": 2,
         "name": "Object 2",
         "objType_1_id": null,
         "objType_2_id": 1,
         "objType_3_id": null,
         "objType_2": {
            "id": 1,
            "name": "Object type 2-1"
      },
      {
         "id": 3,
         "name": "Object 3",
         "objType_1_id": null,
         "objType_2_id": null,
         "objType_3_id": 1,
         "objType_3": {
            "id": 1,
            "name": "Object type 3-1"
      },
      {
         "id": 4,
         "name": "Object 4",
         "objType_1_id": null,
         "objType_2_id": 2,
         "objType_3_id": null,
         "objType_3": {
            "id": 1,
            "name": "Object type 2-2"
      },
      {
         "id": 5,
         "name": "Object 4",
         "objType_1_id": 1,
         "objType_2_id": null,
         "objType_3_id": null,
         "objType_3": {
            "id": 1,
            "name": "Object type 1-1"
      }
   ]
}

And so on. On the body of the p-table, I listed the subobject type of each object using 3 subobject "GETs" for each one on the samecolumn:

   <ng-template pTemplate="header">

   <ng-template>
   <ng-template pTemplate="body" let-object>

            {{object.objType_1?.name}}
            {{object.objType_2?.name}}
            {{object.objType_3?.name}}

As "the desired subject names filter" say above, I want to get filter the name of the three "object types" subobjects from each object. Any help is welcome.