问:
How to apply sort in mongoose in populated fields at last before passing actual result
suppose i have a response like this

```<code>let response=[{
 name:"pranavrajsinh",
 id:1,
hobbies:{sirname:'vyassir',game:'cricket',sirId:'222',position:"batsman"},(POPULATED FIELD THROUGH MONGOOSE)
email:"pranavzala5689@gmail.com",
permissions:{ispublic:true,isprivatetominimum:true}(POPULATED FIELD THROUGH MONGOOSE)
},
{
 name:"NIKITEN",
 id:2,
hobbies:{sirname:'Prabhusir',game:'football',sirId:'344',position:"allrounder"},(POPULATED FIELD THROUGH MONGOOSE)
email:"prabhu@gmail.com",
permissions:{ispublic:true,isprivatetominimum:false}(POPULATED FIELD THROUGH MONGOOSE)
}]
</code>```

// do sorting now after getting response to the hobbies sir id which has been come form mongoose population

how to apply sort function on this populated fields means i have to sort on basis of  sirId present in hobbies object which is populated from above
Here i have to do sorting after population in the populated fields

we have seen that all we are doing sorting at the time of population
means like these

```<code>Group
  .find({})
  .populate({path: 'Members', options: { sort: { 'created_at': -1 } } })
</code>```

but i want to sort in populated field after getting response

Body:
suppose i have a response like this

let response=[{
 name:"pranavrajsinh",
 id:1,
hobbies:{sirname:'vyassir',game:'cricket',sirId:'222',position:"batsman"},(POPULATED FIELD THROUGH MONGOOSE)
email:"pranavzala5689@gmail.com",
permissions:{ispublic:true,isprivatetominimum:true}(POPULATED FIELD THROUGH MONGOOSE)
},
{
 name:"NIKITEN",
 id:2,
hobbies:{sirname:'Prabhusir',game:'football',sirId:'344',position:"allrounder"},(POPULATED FIELD THROUGH MONGOOSE)
email:"prabhu@gmail.com",
permissions:{ispublic:true,isprivatetominimum:false}(POPULATED FIELD THROUGH MONGOOSE)
}]

// do sorting now after getting response to the hobbies sir id which has been come form mongoose population

how to apply sort function on this populated fields means i have to sort on basis of  sirId present in hobbies object which is populated from above
Here i have to do sorting after population in the populated fields

we have seen that all we are doing sorting at the time of population
means like these

Group
  .find({})
  .populate({path: 'Members', options: { sort: { 'created_at': -1 } } })

but i want to sort in populated field after getting response


来源: stackexchange

问:
Expression-support workaround for older Apache httpd Versions (2.4.8)
I am in the unfortunate situation to use an older Apache httpd 2.4.8, and want to use expressions such as base64 encoding with mod_headers.

According to the documentation expr=value support was added to mod_headers in 2.4.10. What might be a viable solution to get the following configuration running on 2.4.8?

```<code>Header add Set-Cookie "expr=MYCOOKIE=%{base64:%{env:SOMEENVIRONMENT}}; path=/; Expires=Tue, 19 Jan 2038 04:14:00 GMT;"
</code>```

This example is over-simplified. The real expression involves additional unescape and unbase64 functions. It would be cool if someone could give me a hint about if this is possible with 2.4.8 at all and what might be a feasible way implement this.

Thank you!

Mirko

Configuration works perfectly on 2.4.54, but due to platform restrictions I have to use 2.4.8.

ContentLicense: CC BY-SA 4.0

Body:
I am in the unfortunate situation to use an older Apache httpd 2.4.8, and want to use expressions such as base64 encoding with mod_headers.

According to the documentation expr=value support was added to mod_headers in 2.4.10. What might be a viable solution to get the following configuration running on 2.4.8?

Header add Set-Cookie "expr=MYCOOKIE=%{base64:%{env:SOMEENVIRONMENT}}; path=/; Expires=Tue, 19 Jan 2038 04:14:00 GMT;"

This example is over-simplified. The real expression involves additional unescape and unbase64 functions. It would be cool if someone could give me a hint about if this is possible with 2.4.8 at all and what might be a feasible way implement this.

Thank you!

Mirko

Configuration works perfectly on 2.4.54, but due to platform restrictions I have to use 2.4.8.


问:
./start-all.sh is not working to start all the nodes in single hadoop cluster
./start-all.sh is only starting resource manager and for namenode,datanode and secondarynamenode i need to cd hadoop-daemon.sh and start each of them separately and same with the node manager need to start with ./yarn-daemon.sh start nodemanager I am not able to start all these nodes with ./start-all.sh, how can we make all node to start with the single command ./start-all.sh

And I set the path in .bashrc as --> PATH=$PATH:/home/kirankathe/hadoop-3.3.0/sbin
can anyone help me in getting out of this, Thanks in advance


问:
Triggering Prometheus alerts within specific time ranges
I'm setting up prometheus alerts for when there is 0 throughput for an API. But I want the alert to only be triggered only between 2pm UTC to 2am UTC (next day). What should be the syntax for this.

```<code>  - name: API zero throughput alert
    rules:
      - alert: api-zero-throughput
        annotations:
          message: API throughput for the last 15m is zero
        expr: sum by(path) (rate(http_request_duration_seconds_count{path="<api endpoint>",status=~"2.*|4.*"}[2m])) == 0
        for: 30m
        labels:
          severity: warning
</code>```

from my research I found out that hour() method is used for this purpose. But I can't seem to make it work in my case.

Body:
I'm setting up prometheus alerts for when there is 0 throughput for an API. But I want the alert to only be triggered only between 2pm UTC to 2am UTC (next day). What should be the syntax for this.

  - name: API zero throughput alert
    rules:
      - alert: api-zero-throughput
        annotations:
          message: API throughput for the last 15m is zero
        expr: sum by(path) (rate(http_request_duration_seconds_count{path="<api endpoint>",status=~"2.*|4.*"}[2m])) == 0
        for: 30m
        labels:
          severity: warning

from my research I found out that hour() method is used for this purpose. But I can't seem to make it work in my case.


问:
Spring JPA partial update by non primary key causing issue(Closed)
My entity has 15 fields, where Id is the UUID. I want to update them by non-primary key(field2 is unique).

Entity

```<code>Id
field1
.
.
field15
</code>```

MyRepository

```<code>
public interface myrepo extends JpaRepository<mymodel, UUID> {

  Optional<MyModel> findByField2(String value);

}
</code>```

My service

```<code>    MyModel MyModel =
        repo
            .findByField2(val)
            .orElseThrow(
                () ->
                    new RunTimeException());

// mapstruct to override the non-null fields
MyMapper.update(request,myModel);

------------> Upto this step everything is fine

repo.save(myModel) ---> This step is getting failed with the following exception.

</code>```

Stack trace:

```<code>2023-01-02 15:37:54.777  WARN 122623 --- [nio-8090-exec-7] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.orm.ObjectOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; statement executed: update my_model set field1=? where id=? and version=?;
</code>```

can't we execute the partial update by non-primary key?

Body:
My entity has 15 fields, where Id is the UUID. I want to update them by non-primary key(field2 is unique).

Entity

Id
field1
.
.
field15

MyRepository

public interface myrepo extends JpaRepository<mymodel, UUID> {

  Optional<MyModel> findByField2(String value);

}

My service

    MyModel MyModel =
        repo
            .findByField2(val)
            .orElseThrow(
                () ->
                    new RunTimeException());

// mapstruct to override the non-null fields
MyMapper.update(request,myModel);

------------> Upto this step everything is fine

repo.save(myModel) ---> This step is getting failed with the following exception.

Stack trace:

2023-01-02 15:37:54.777  WARN 122623 --- [nio-8090-exec-7] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.orm.ObjectOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; statement executed: update my_model set field1=? where id=? and version=?;

can't we execute the partial update by non-primary key?


问:
NextJs mqtt app client does not update context in event handlers
I am developing mqtt web client for an IOT project using NextJs and mqtt package. In order to allow the client object to be shared among all components, I implemented a context API in which I defined some states as seen in the code below. The issue I am having here is, anytime I make update to msg state using setMsg function in the 'message' event handler, the msg does not get updated.

If I also try to publish a message by clicking a button, the message is not published. The only I was able to publish is by calling the client.publish intermittently inside setInterval

I am using the shiftr.io mqtt broker and I see an error stating that connection failed even though the shiftr.io dashboard indicated that connection is established by showing the client with its ID.

Thank you in advance.

** index.js file:**

```<code>
import Car from '../components/Car';
import CarList from '../components/CarList';
import Board from '../components/Board';
import Notification from '../components/Notification';
import { useState, useEffect } from 'react';
import { useGlobalContext } from '../lib/context';
import mqtt from 'mqtt'
import Head from 'next/head'

export default function Home() {

  // console.log(JSON.parse(client).connected)
  const client = mqtt.connect('mqtt://tatwo:K1FADvdffhfff@tatwo.cloud.shiftr.io', {
    clientId: 'client1'
  })

  const [freeSpace, setFreeState] = useState(1)
  const {setSpaceStatus, setMqttClient, mqttClient, setMsg, msg} = useGlobalContext()
  const [spaceMessageString, setSpaceMessageString] = useState(['0','0','0'])

  const publishStatus = (msg, clt)=>{
      client.publish('/reservation', msg)
  }

  if(client){
    setMqttClient(client)
  }

  client.on('connect', function(){
    console.log('connected')
    client.subscribe('space')
  })

  client.on('message', function(topic, message){
    console.log('receieved: ', message.toString().split(','))
    // setSpaceMessageString(message.toString().split(','))
    setMsg(message.toString())
    // setSpaceStatus(message.toString().split(','))
  })

  useEffect(() => {
    return ()=>{
        if(mqttClient){
          mqttClient.end()
        }
    }

  }, [spaceMessageString])

  return (
    <div className='flex flex-col items-center justify-center'>
      <h1 className='text-white text-3xl md:text-5xl font-extrabold text-center'>Parking without stress</h1>
      <p className='text-amber-500 text-lg my-5'>Use smart parking system to check for parking space before you drive. </p>
      <Board />
      <p>{msg}: {mqttClient?.connected == true ? 'Onlined': 'offline'}</p>
      {
        freeSpace === 0 ?
        // <Notification /> : <CarList spaceMessageString={spaceMessageString} />
        <Notification /> : (
          <div className='grid grid-cols-1 md:grid-cols-3 gap-4 my-5 w-full'>
            {
              spaceMessageString.map((space, index)=>
                <Car
                  name={`Space ${index + 1}`}
                  message={spaceMessageString[index]}
                  key={index}
                  identity={index + 1}
                  publishStatus={publishStatus}
                />
              )
            }
        </div>
        )
      }
    </div>
  )

}

</code>```

** context.js: **

```<code>import React from 'react'
import { createContext, useContext, useState } from 'react'

const AppContext = createContext({});

const AppProvider = ({children}) => {

    const [user, setUser] = useState(null)
    const [reservations, setReservations] = useState([])
    const [spaceStatus, setSpaceStatus] = useState([1, 0, 0])
    const [connected, setConnected] = useState(false)
    const [mqttClient, setMqttClient] = useState(null)
    const [msg, setMsg] = useState('no message')

    const client = null;

    return (
        <AppContext.Provider value={
            {
                user,
                setUser,
                spaceStatus,
                setSpaceStatus,
                reservations,
                setReservations,
                connected,
                setConnected,
                client,
                setMqttClient,
                mqttClient,
                setMsg,
                msg
            }
        }>
            {children}
        </AppContext.Provider>
    )
}

export const useGlobalContext = () => useContext(AppContext);

export default AppProvider
</code>```

** _app.js: **

```<code>import Layout from '../components/Layout'
import '../styles/globals.css'
import AppProvider from '../lib/context';

export default function App({ Component, pageProps }) {
  return (

    <AppProvider>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </AppProvider>
  )
}

</code>```

Body:
I am developing mqtt web client for an IOT project using NextJs and mqtt package. In order to allow the client object to be shared among all components, I implemented a context API in which I defined some states as seen in the code below. The issue I am having here is, anytime I make update to msg state using setMsg function in the 'message' event handler, the msg does not get updated.

If I also try to publish a message by clicking a button, the message is not published. The only I was able to publish is by calling the client.publish intermittently inside setInterval

I am using the shiftr.io mqtt broker and I see an error stating that connection failed even though the shiftr.io dashboard indicated that connection is established by showing the client with its ID.

Thank you in advance.

** index.js file:**

import Car from '../components/Car';
import CarList from '../components/CarList';
import Board from '../components/Board';
import Notification from '../components/Notification';
import { useState, useEffect } from 'react';
import { useGlobalContext } from '../lib/context';
import mqtt from 'mqtt'
import Head from 'next/head'

export default function Home() {

  // console.log(JSON.parse(client).connected)
  const client = mqtt.connect('mqtt://tatwo:K1FADvdffhfff@tatwo.cloud.shiftr.io', {
    clientId: 'client1'
  })

  const [freeSpace, setFreeState] = useState(1)
  const {setSpaceStatus, setMqttClient, mqttClient, setMsg, msg} = useGlobalContext()
  const [spaceMessageString, setSpaceMessageString] = useState(['0','0','0'])

  const publishStatus = (msg, clt)=>{
      client.publish('/reservation', msg)
  }

  if(client){
    setMqttClient(client)
  }

  client.on('connect', function(){
    console.log('connected')
    client.subscribe('space')
  })

  client.on('message', function(topic, message){
    console.log('receieved: ', message.toString().split(','))
    // setSpaceMessageString(message.toString().split(','))
    setMsg(message.toString())
    // setSpaceStatus(message.toString().split(','))
  })

  useEffect(() => {
    return ()=>{
        if(mqttClient){
          mqttClient.end()
        }
    }

  }, [spaceMessageString])

  return (

Parking without stress

Use smart parking system to check for parking space before you drive.

      <Board />

{msg}: {mqttClient?.connected == true ? 'Onlined': 'offline'}

      {
        freeSpace === 0 ?
        // <Notification /> : <CarList spaceMessageString={spaceMessageString} />
        <Notification /> : (

            {
              spaceMessageString.map((space, index)=>
                <Car
                  name={`Space ${index + 1}`}
                  message={spaceMessageString[index]}
                  key={index}
                  identity={index + 1}
                  publishStatus={publishStatus}
                />
              )
            }

        )
      }

  )

}

** context.js: **

import React from 'react'
import { createContext, useContext, useState } from 'react'

const AppContext = createContext({});

const AppProvider = ({children}) => {

    const [user, setUser] = useState(null)
    const [reservations, setReservations] = useState([])
    const [spaceStatus, setSpaceStatus] = useState([1, 0, 0])
    const [connected, setConnected] = useState(false)
    const [mqttClient, setMqttClient] = useState(null)
    const [msg, setMsg] = useState('no message')

    const client = null;

    return (
        <AppContext.Provider value={
            {
                user,
                setUser,
                spaceStatus,
                setSpaceStatus,
                reservations,
                setReservations,
                connected,
                setConnected,
                client,
                setMqttClient,
                mqttClient,
                setMsg,
                msg
            }
        }>
            {children}
        </AppContext.Provider>
    )
}

export const useGlobalContext = () => useContext(AppContext);

export default AppProvider

** _app.js: **

import Layout from '../components/Layout'
import '../styles/globals.css'
import AppProvider from '../lib/context';

export default function App({ Component, pageProps }) {
  return (

    <AppProvider>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </AppProvider>
  )
}


问:
How to add function pointer in a tailq in C
I need to hold *char title and **int (callback)(void , unsigned int) variables pair in a tailq. Because there is another thread mechanism in my full code and it checks this global 'identifier' variable when triggered. I used memcpy but it did not work.

How can I do that?

The code snip is below.

```<code>struct callback_list_entry {
    int (*callback)(void *, unsigned int);
    char *title;
    TAILQ_ENTRY(callback_list_entry) entries;
};
TAILQ_HEAD(callback_list, callback_list_entry);
struct sipc_identifier
{
    unsigned int port;
    int (*broadcast_callback)(void *, unsigned int);
    struct callback_list callback_list;
};

typedef struct sipc_identifier _sipc_identifier;

static _sipc_identifier identifier;

int my_callback(void *prm, unsigned int len)
{
    printf("here is %s: %s len: %d\n", __func__, (char *)prm, len);

    return OK;
}
static int add_callback_to_callback_list(int (*callback)(void *, unsigned int), char *title, _sipc_identifier *identifier)
{
    struct callback_list_entry *entry = NULL;

    if (!callback || !identifier) {
        errorf("args cannot be NULL\n");
        return NOK;
    }

    entry = (struct callback_list_entry *)calloc(1, sizeof(struct callback_list_entry));
    if (!entry) {
        errorf("calloc failed\n");
        return NOK;
    }

debugf("%p and size %d  title: %s  %p\n", callback, (int)sizeof(callback), title, &callback);

    entry->callback = (void *)calloc(1, sizeof(callback));
    if (!entry->callback) {
        errorf("calloc failed\n");
        FREE(entry);
        return NOK;
    }
    memcpy(entry->callback, callback, sizeof(callback));

debugf("entry->callback %p  %p\n", entry->callback, *(entry->callback));

    entry->title = (char *)calloc(1, strlen(title) + 1);
    if (!entry->title) {
        errorf("calloc failed\n");
        FREE(entry->callback);
        FREE(entry);
        return NOK;
    }
    strcpy(entry->title, title);

    TAILQ_INSERT_HEAD(&identifier->callback_list, entry, entries);

    return OK;
}

static int register(char *title, int (*callback)(void *, unsigned int))
{
    if (!title || !callback) {
        errorf("args cannot be NULL\n");
        return NOK;
    }

    return add_callback_to_callback_list(callback, title, &identifier);
}

int main(int argc, char **argv)
{
    TAILQ_INIT(&identifier->callback_list);

    register("App_A_Registered_title", &my_callback);

    return OK;
}

</code>```

Thanks for the help.

Body:
I need to hold *char title and **int (callback)(void , unsigned int) variables pair in a tailq. Because there is another thread mechanism in my full code and it checks this global 'identifier' variable when triggered. I used memcpy but it did not work.

How can I do that?

The code snip is below.

struct callback_list_entry {
    int (*callback)(void *, unsigned int);
    char *title;
    TAILQ_ENTRY(callback_list_entry) entries;
};
TAILQ_HEAD(callback_list, callback_list_entry);
struct sipc_identifier
{
    unsigned int port;
    int (*broadcast_callback)(void *, unsigned int);
    struct callback_list callback_list;
};

typedef struct sipc_identifier _sipc_identifier;

static _sipc_identifier identifier;

int my_callback(void *prm, unsigned int len)
{
    printf("here is %s: %s len: %d\n", __func__, (char *)prm, len);

    return OK;
}
static int add_callback_to_callback_list(int (*callback)(void *, unsigned int), char *title, _sipc_identifier *identifier)
{
    struct callback_list_entry *entry = NULL;

    if (!callback || !identifier) {
        errorf("args cannot be NULL\n");
        return NOK;
    }

    entry = (struct callback_list_entry *)calloc(1, sizeof(struct callback_list_entry));
    if (!entry) {
        errorf("calloc failed\n");
        return NOK;
    }

debugf("%p and size %d  title: %s  %p\n", callback, (int)sizeof(callback), title, &callback);

    entry->callback = (void *)calloc(1, sizeof(callback));
    if (!entry->callback) {
        errorf("calloc failed\n");
        FREE(entry);
        return NOK;
    }
    memcpy(entry->callback, callback, sizeof(callback));

debugf("entry->callback %p  %p\n", entry->callback, *(entry->callback));

    entry->title = (char *)calloc(1, strlen(title) + 1);
    if (!entry->title) {
        errorf("calloc failed\n");
        FREE(entry->callback);
        FREE(entry);
        return NOK;
    }
    strcpy(entry->title, title);

    TAILQ_INSERT_HEAD(&identifier->callback_list, entry, entries);

    return OK;
}

static int register(char *title, int (*callback)(void *, unsigned int))
{
    if (!title || !callback) {
        errorf("args cannot be NULL\n");
        return NOK;
    }

    return add_callback_to_callback_list(callback, title, &identifier);
}

int main(int argc, char **argv)
{
    TAILQ_INIT(&identifier->callback_list);

    register("App_A_Registered_title", &my_callback);

    return OK;
}

Thanks for the help.


问:
Dynamically Use Spring Annotations for Redis and Elasticsearch
Consider the following class

```<code>import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.redis.core.RedisHash;

@Document(indexName = "index_name")
@RedisHash("filter_name")

class Index {

}
</code>```

I have a usecase where in usage of elasticsearch or redis would be by the user's choice, one way of implementation is having separate class for each, which works, but isn't elegent.
Is it possible to disable a specific annotation in runtime.

Body:
Consider the following class

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.redis.core.RedisHash;

@Document(indexName = "index_name")
@RedisHash("filter_name")

class Index {

}

I have a usecase where in usage of elasticsearch or redis would be by the user's choice, one way of implementation is having separate class for each, which works, but isn't elegent.
Is it possible to disable a specific annotation in runtime.


问:
What can i do for Pagination infer arguments error
`Hi i am using pagination to display data but i got an error showing cannot infer arguments ...can anyone help me through it.Thanks in advance

```<code><sub>```
private Paginator<OrganizationInfo> getOrganizationInfoPaginator(
        Organization organizationAlias,
         SelectConditionStep<Record> selectConditionStep) {

    return new Paginator<GETTING ERROR HERE>(selectConditionStep, List.of( new SortableField<>(OrganizationSortable.NAME.toString(), organizationAlias.getName()),
                            new SortableField<>(OrganizationSortable.KEY.toString(), organizationAlias.getKeys())),
            new IdField<>(organizationAlias.ID, organizationAlias.getIdentity().toString()), records ->
            records.stream().map(org -> {
                        var orgId = org.get(organizationAlias.ID);

                return new OrganizationInfo(orgId,
                       // org.get(organizationAlias.ID),
                       org.get(organizationAlias.NAME),
                         org.get(organizationAlias.ORGANIZATION_KEY),
                       org.get(organizationAlias.ADDRESS_ID),
                     org.get(organizationAlias.CONTACT_NO),

                        org.get(organizationAlias.CREATED_AT),
                        org.get(organizationAlias.FAX_NO),
                        org.get(organizationAlias.WEBSITE),

                        org.get(organizationAlias.STATUS_ID),
                        org.get(ORGANIZATION_STATUS_TRANSLATION.NAME),
                         org.get(USER.EMAIL),
                         org.get(USER.PHONE));

            }).collect(Collectors.toList()));
}
```</sub>
</code>```

I need to display  10 data for each page but it is showing error in pagination

Body:
`Hi i am using pagination to display data but i got an error showing cannot infer arguments ...can anyone help me through it.Thanks in advance

```
private Paginator<OrganizationInfo> getOrganizationInfoPaginator(
        Organization organizationAlias,
         SelectConditionStep<Record> selectConditionStep) {

    return new Paginator<GETTING ERROR HERE>(selectConditionStep, List.of( new SortableField<>(OrganizationSortable.NAME.toString(), organizationAlias.getName()),
                            new SortableField<>(OrganizationSortable.KEY.toString(), organizationAlias.getKeys())),
            new IdField<>(organizationAlias.ID, organizationAlias.getIdentity().toString()), records ->
            records.stream().map(org -> {
                        var orgId = org.get(organizationAlias.ID);

                return new OrganizationInfo(orgId,
                       // org.get(organizationAlias.ID),
                       org.get(organizationAlias.NAME),
                         org.get(organizationAlias.ORGANIZATION_KEY),
                       org.get(organizationAlias.ADDRESS_ID),
                     org.get(organizationAlias.CONTACT_NO),

                        org.get(organizationAlias.CREATED_AT),
                        org.get(organizationAlias.FAX_NO),
                        org.get(organizationAlias.WEBSITE),

                        org.get(organizationAlias.STATUS_ID),
                        org.get(ORGANIZATION_STATUS_TRANSLATION.NAME),
                         org.get(USER.EMAIL),
                         org.get(USER.PHONE));

            }).collect(Collectors.toList()));
}
```

I need to display  10 data for each page but it is showing error in pagination


问:
My celery-beat works locally but not in production?
my task:

```<code>@shared_task
def my_test():
    # Executes every 2 minutes

    UserStatisticStatus.objects.filter(id=1).update(loot_boxes=+234)

    print('Hello from celery')

app.conf.beat_schedule = {
    'my-task-every-10-seconds': {
        'task': 'user_statistic_status.tasks.my_test',
        'schedule': timedelta(seconds=10)
    }
}
</code>```

my settings:

```<code>if 'RDS_DB_NAME' in os.environ:
    CELERY_BROKER_URL = 'redis://<myurl>/0'
    CELERY_ACCEPT_CONTENT = ['application/json']
    CELERY_RESULT_SERIALIZER = 'json'
    CELERY_TASK_SERIALIZER = 'json'
    CELERY_BROKER_TRANSPORT_OPTIONS = {
        'region': 'eu-central-1',
        'polling_interval': 20,
    }
    CELERY_RESULT_BACKEND = 'redis://<myurl>/1'
    CELERY_ENABLE_REMOTE_CONTROL = False
    CELERY_SEND_EVENTS = False
    CELERY_TASK_ROUTES = {
            'my_test': {'queue': 'default'},
        }
</code>```

my celery.py :

```<code>import os
from celery import Celery

from project import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

app = Celery('celery_app')

app.conf.task_routes = {
    'my_test': {'queue': 'default'},
}
app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

</code>```
```<code>[2023-01-06 09:13:32,581: DEBUG/MainProcess] | Worker: Starting Beat
[2023-01-06 09:13:32,584: DEBUG/MainProcess] ^-- substep ok
[2023-01-06 09:13:32,585: DEBUG/MainProcess] | Worker: Starting Hub
[2023-01-06 09:13:32,585: DEBUG/MainProcess] ^-- substep ok
[2023-01-06 09:13:32,586: DEBUG/MainProcess] | Worker: Starting Pool
[2023-01-06 09:13:32,856: DEBUG/MainProcess] ^-- substep ok
[2023-01-06 09:13:32,864: DEBUG/MainProcess] | Worker: Starting Consumer
[2023-01-06 09:13:32,864: DEBUG/MainProcess] | Consumer: Starting Connection
[2023-01-06 09:13:32,901: INFO/Beat] beat: Starting...
[2023-01-06 09:13:32,972: DEBUG/Beat] Current schedule:
<ScheduleEntry: my-task-every-10-seconds user_statistic_status.tasks.my_test() <freq: 10.00 seconds>
[2023-01-06 09:13:32,972: DEBUG/Beat] beat: Ticking with max interval->5.00 minutes
[2023-01-06 09:13:32,973: DEBUG/Beat] beat: Waking up in 9.99 seconds.
[2023-01-06 09:13:42,969: DEBUG/Beat] beat: Synchronizing schedule...

</code>```

It gets stuck here and task never executes !!!

The worker connects and shows the tasks correctly and the beat starts too but nothing happening. I've tested it with the local redis server and everything works fine.

Any help will be much appreciated

Thank you

Body:
my task:

@shared_task
def my_test():
    # Executes every 2 minutes

    UserStatisticStatus.objects.filter(id=1).update(loot_boxes=+234)

    print('Hello from celery')

app.conf.beat_schedule = {
    'my-task-every-10-seconds': {
        'task': 'user_statistic_status.tasks.my_test',
        'schedule': timedelta(seconds=10)
    }
}

my settings:

if 'RDS_DB_NAME' in os.environ:
    CELERY_BROKER_URL = 'redis://<myurl>/0'
    CELERY_ACCEPT_CONTENT = ['application/json']
    CELERY_RESULT_SERIALIZER = 'json'
    CELERY_TASK_SERIALIZER = 'json'
    CELERY_BROKER_TRANSPORT_OPTIONS = {
        'region': 'eu-central-1',
        'polling_interval': 20,
    }
    CELERY_RESULT_BACKEND = 'redis://<myurl>/1'
    CELERY_ENABLE_REMOTE_CONTROL = False
    CELERY_SEND_EVENTS = False
    CELERY_TASK_ROUTES = {
            'my_test': {'queue': 'default'},
        }

my celery.py :

import os
from celery import Celery

from project import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

app = Celery('celery_app')

app.conf.task_routes = {
    'my_test': {'queue': 'default'},
}
app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

[2023-01-06 09:13:32,581: DEBUG/MainProcess] | Worker: Starting Beat
[2023-01-06 09:13:32,584: DEBUG/MainProcess] ^-- substep ok
[2023-01-06 09:13:32,585: DEBUG/MainProcess] | Worker: Starting Hub
[2023-01-06 09:13:32,585: DEBUG/MainProcess] ^-- substep ok
[2023-01-06 09:13:32,586: DEBUG/MainProcess] | Worker: Starting Pool
[2023-01-06 09:13:32,856: DEBUG/MainProcess] ^-- substep ok
[2023-01-06 09:13:32,864: DEBUG/MainProcess] | Worker: Starting Consumer
[2023-01-06 09:13:32,864: DEBUG/MainProcess] | Consumer: Starting Connection
[2023-01-06 09:13:32,901: INFO/Beat] beat: Starting...
[2023-01-06 09:13:32,972: DEBUG/Beat] Current schedule:
<ScheduleEntry: my-task-every-10-seconds user_statistic_status.tasks.my_test() <freq: 10.00 seconds>
[2023-01-06 09:13:32,972: DEBUG/Beat] beat: Ticking with max interval->5.00 minutes
[2023-01-06 09:13:32,973: DEBUG/Beat] beat: Waking up in 9.99 seconds.
[2023-01-06 09:13:42,969: DEBUG/Beat] beat: Synchronizing schedule...

It gets stuck here and task never executes !!!

The worker connects and shows the tasks correctly and the beat starts too but nothing happening. I've tested it with the local redis server and everything works fine.

Any help will be much appreciated

Thank you


问:
How to add a logo from classpathresoure to email body using MimeMessage in springboot
```<code>public String emailOnRNew(EmailStructureDTO emailStructure, byte\[\] overhaulPdfContent, String contactNumber,
String fromList) {

        String sender = fromList;
        String bcc = CommonConstant.INSP_EMAIL_BCC;
        String content = emailStructure.getEmailBody();
        String subject = emailStructure.getEmailSub();

        Properties properties = new Properties();
        properties.put("mail.smtp.host", environment.getProperty("spring.mail.host"));
        properties.put("mail.smtp.port", environment.getProperty("spring.mail.port"));

        Session session = Session.getDefaultInstance(properties, null);

        try {
            //*********************************added new part

            MimeBodyPart logoPart = new MimeBodyPart();
            ClassPathResource classPathResource = new ClassPathResource("image/logo1.jpg");
            logoPart.setContent(classPathResource.getInputStream(), "image/png");
            logoPart.setHeader("Content-ID", "logo1");

            //*********************************

            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setContent(content,"text/html;charset=utf-8");

            // write the PDF content to the output stream

            ByteArrayDataSource dataSource = new ByteArrayDataSource(overhaulPdfContent, "application/pdf");
            MimeBodyPart pdfBodyPart = new MimeBodyPart();
            pdfBodyPart.setDataHandler(new DataHandler(dataSource));
            pdfBodyPart.setFileName("Overhaul & Repair.pdf");

            MimeMultipart mimeMultipart = new MimeMultipart();
            mimeMultipart.addBodyPart(textBodyPart);
            mimeMultipart.addBodyPart(pdfBodyPart);
            mimeMultipart.addBodyPart(logoPart);

            InternetAddress iaSender = new InternetAddress(sender);
            InternetAddress iaBcc = new InternetAddress(bcc);
            String[] to = emailStructure.getEmailTo();
            String[] cc = emailStructure.getCcList();

            InternetAddress[] addressTo = new InternetAddress[to.length];
            if (to.length > 0) {
                for (int i = 0; i < to.length; i++) {
                    addressTo[i] = new InternetAddress(to[i]);
                }
            }
            InternetAddress[] addressCc = new InternetAddress[cc.length];
            if (cc.length > 0) {
                for (int i = 0; i < cc.length; i++) {
                    addressCc[i] = new InternetAddress(cc[i]);
                }
            }
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(iaSender);
            mimeMessage.setSubject(subject);
            mimeMessage.setRecipients(Message.RecipientType.TO, addressTo);
            mimeMessage.setRecipients(Message.RecipientType.CC, addressCc);
            mimeMessage.setRecipient(Message.RecipientType.BCC, iaBcc);
            mimeMessage.setContent(mimeMultipart);

            Transport.send(mimeMessage);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new DAOException(ex.getMessage(), ex);
        }

        return CommonConstant.STATUS_OK;

}
</code>```

ERROR : javax.activation.UnsupportedDataTypeException: no object DCH for MIME type image/png

I'm attempting to add a logo to the email body's signature, but it appears above the message.

Also HTML is

Body:
public String emailOnRNew(EmailStructureDTO emailStructure, byte\[\] overhaulPdfContent, String contactNumber,
String fromList) {

        String sender = fromList;
        String bcc = CommonConstant.INSP_EMAIL_BCC;
        String content = emailStructure.getEmailBody();
        String subject = emailStructure.getEmailSub();

        Properties properties = new Properties();
        properties.put("mail.smtp.host", environment.getProperty("spring.mail.host"));
        properties.put("mail.smtp.port", environment.getProperty("spring.mail.port"));

        Session session = Session.getDefaultInstance(properties, null);

        try {
            //*********************************added new part

            MimeBodyPart logoPart = new MimeBodyPart();
            ClassPathResource classPathResource = new ClassPathResource("image/logo1.jpg");
            logoPart.setContent(classPathResource.getInputStream(), "image/png");
            logoPart.setHeader("Content-ID", "logo1");

            //*********************************

            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setContent(content,"text/html;charset=utf-8");

            // write the PDF content to the output stream

            ByteArrayDataSource dataSource = new ByteArrayDataSource(overhaulPdfContent, "application/pdf");
            MimeBodyPart pdfBodyPart = new MimeBodyPart();
            pdfBodyPart.setDataHandler(new DataHandler(dataSource));
            pdfBodyPart.setFileName("Overhaul & Repair.pdf");

            MimeMultipart mimeMultipart = new MimeMultipart();
            mimeMultipart.addBodyPart(textBodyPart);
            mimeMultipart.addBodyPart(pdfBodyPart);
            mimeMultipart.addBodyPart(logoPart);

            InternetAddress iaSender = new InternetAddress(sender);
            InternetAddress iaBcc = new InternetAddress(bcc);
            String[] to = emailStructure.getEmailTo();
            String[] cc = emailStructure.getCcList();

            InternetAddress[] addressTo = new InternetAddress[to.length];
            if (to.length > 0) {
                for (int i = 0; i < to.length; i++) {
                    addressTo[i] = new InternetAddress(to[i]);
                }
            }
            InternetAddress[] addressCc = new InternetAddress[cc.length];
            if (cc.length > 0) {
                for (int i = 0; i < cc.length; i++) {
                    addressCc[i] = new InternetAddress(cc[i]);
                }
            }
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(iaSender);
            mimeMessage.setSubject(subject);
            mimeMessage.setRecipients(Message.RecipientType.TO, addressTo);
            mimeMessage.setRecipients(Message.RecipientType.CC, addressCc);
            mimeMessage.setRecipient(Message.RecipientType.BCC, iaBcc);
            mimeMessage.setContent(mimeMultipart);

            Transport.send(mimeMessage);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new DAOException(ex.getMessage(), ex);
        }

        return CommonConstant.STATUS_OK;

}

ERROR : javax.activation.UnsupportedDataTypeException: no object DCH for MIME type image/png

I'm attempting to add a logo to the email body's signature, but it appears above the message.

Also HTML is


问:
How Js through the NPM covert to use for Xampp Server
I lake a Js project make through Npm (Pakage.json). I want to run the project in Xampp server

How can I change the project for Xampp Server

Eg : https://stackblitz.com/edit/js-kzebuu?file=index.js

I lake a Js project make through Npm (Pakage.json). I want to run the project in Xampp server

How can I change the project for Xampp Server

Eg : https://stackblitz.com/edit/js-kzebuu?file=index.js


问:
Python- Can't get form data to transfer to python from HTML using flask
I am trying to activated an output using a button click on a HTML page. But it's currently not giving me any errors but just isn't working. I'm new to Python and HTML so maybe I'm missing something. I've lost countless hours trying to search for a solution but have found nothing.

<meta name="viewport" content="width=device-width">

<form action="/" method="post" id="garageform">
<input ="post" id="garagecode" name="garagecode" type="text "pattern="[0-9]*" value="12345678" STYLE="background-color:white;">
</form>
<button width="90%" onclick="document.forms['garageform'].submit();">Submit</button>

Click for Log File

```
<pre class="lang-py prettyprint-override"><code># Call flask function, template function and request function
from flask import Flask, render_template, request
print('Test')

# Import sys, datetime and time
import sys
import datetime
import time

# Imports the GPIO library for use
import RPi.GPIO as GPIO

# Turns off warning for GPIO in use
GPIO.setwarnings(False)

# Sets the GPIO use as board numbers
GPIO.setmode(GPIO.BOARD)

# Setup of the I/O's
GPIO.setup(7, GPIO.OUT)
GPIO.setup(3, GPIO.OUT)
GPIO.setup(5, GPIO.OUT)
GPIO.setup(40, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(38, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(8, GPIO.OUT)

app = Flask(__name__)

# Create route to page on flask server
@app.route('/', methods=['POST','GET'])
def index():
    if GPIO.input(40) == GPIO.HIGH:
        name1=('\n Door fully closed ' + str(datetime.datetime.now()))
        GPIO.output(5, 0)
        name = name1
        return render_template('index.html', name=name)

    if GPIO.input(40) == GPIO.LOW and GPIO.input(38) == GPIO.LOW:
        name1=('\n Door in transition' + str(datetime.datetime.now()))
        GPIO.output(5, 1)
        output = request.form.to_dict()
        name =name1
        return render_template('index.html', name=name)

    if GPIO.input(38) == GPIO.HIGH:
        name1=('\n Door fully open ' + str(datetime.datetime.now()))
        GPIO.output(3, 1)
        output = request.form.to_dict()
        name =name1
        return render_template('index.html', name=name)

@app.route('/', methods=['GET', 'POST'])
def Garage():
    name = request.form['garagecode']
    if name == '12345678':
        GPIO.output(8, 0)
        time.sleep(1)

if __name__ == '__main__':
    app.run(debug=True, host='192.168.10.141')
</code>```

The page loads but the input doesn't register back in Python.

Body:
I am trying to activated an output using a button click on a HTML page. But it's currently not giving me any errors but just isn't working. I'm new to Python and HTML so maybe I'm missing something. I've lost countless hours trying to search for a solution but have found nothing.

<meta name="viewport" content="width=device-width">

<form action="/" method="post" id="garageform">
<input ="post" id="garagecode" name="garagecode" type="text "pattern="[0-9]*" value="12345678" STYLE="background-color:white;">
</form>
<button width="90%" onclick="document.forms['garageform'].submit();">Submit</button>

Click for Log File

# Call flask function, template function and request function
from flask import Flask, render_template, request
print('Test')

# Import sys, datetime and time
import sys
import datetime
import time

# Imports the GPIO library for use
import RPi.GPIO as GPIO

# Turns off warning for GPIO in use
GPIO.setwarnings(False)

# Sets the GPIO use as board numbers
GPIO.setmode(GPIO.BOARD)

# Setup of the I/O's
GPIO.setup(7, GPIO.OUT)
GPIO.setup(3, GPIO.OUT)
GPIO.setup(5, GPIO.OUT)
GPIO.setup(40, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(38, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(8, GPIO.OUT)

app = Flask(__name__)

# Create route to page on flask server
@app.route('/', methods=['POST','GET'])
def index():
    if GPIO.input(40) == GPIO.HIGH:
        name1=('\n Door fully closed ' + str(datetime.datetime.now()))
        GPIO.output(5, 0)
        name = name1
        return render_template('index.html', name=name)

    if GPIO.input(40) == GPIO.LOW and GPIO.input(38) == GPIO.LOW:
        name1=('\n Door in transition' + str(datetime.datetime.now()))
        GPIO.output(5, 1)
        output = request.form.to_dict()
        name =name1
        return render_template('index.html', name=name)

    if GPIO.input(38) == GPIO.HIGH:
        name1=('\n Door fully open ' + str(datetime.datetime.now()))
        GPIO.output(3, 1)
        output = request.form.to_dict()
        name =name1
        return render_template('index.html', name=name)

@app.route('/', methods=['GET', 'POST'])
def Garage():
    name = request.form['garagecode']
    if name == '12345678':
        GPIO.output(8, 0)
        time.sleep(1)

if __name__ == '__main__':
    app.run(debug=True, host='192.168.10.141')

The page loads but the input doesn't register back in Python.


问:
How can i unwrap Promise in morgan token?
I want to unwrap Promise Object in morgan token

```<code>morgan.token("from", async(req) =>  async{
  const user = await getUserByKey(key);
  return user;
});
</code>```

But it just log '[object Promise] as output in console.

How can i use the real value in Promise?

Body:
I want to unwrap Promise Object in morgan token

morgan.token("from", async(req) =>  async{
  const user = await getUserByKey(key);
  return user;
});

But it just log '[object Promise] as output in console.

How can i use the real value in Promise?


问:
Cadvisor Stops detecting other running containers status and gives container down alerts
I have 3-4 containers and Cadvisor running on a same ubuntu 22.04 EC2 instance.
But after upgrading docker and cadvisor, Cadvisor is not detecting the Other container status(such as high CPU,RAM, which is configure for alerts on prometheus dashboard) and always giving container down alerts.
But all the 3-4 containers along with cadvisor are running.

Cadvisor version before upgrade: v0.32.0 --> google/cadvisor
Cadvisor version Currenly Using: v0.38.6 --> gcr.io/cadvisor/cadvisor
Please suggest a solution,
Thanks in Advance!

I have tried to reinstall Cadvisor container. but not worked.

All the container and cadvisor is running but in prometheus getting alerts all the containers are down.

After checking /metrics from prometheus it is showing below response
-->

ubuntu@ip-:~$ curl http://IP_Address:8010/metrics

HELP cadvisor_version_info A metric with a constant '1' value labeled by kernel version, OS version, docker version, cadvisor version & cadvisor revision.

TYPE cadvisor_version_info gauge
cadvisor_version_info{cadvisorRevision="30515557",cadvisorVersion="v0.38.6",dockerVersion="Unknown",kernelVersion="5.15.0-1026-aws",osVersion="Alpine Linux v3.12"} 1

===> As per my view, dont know why it is giving dockerVersion="Unknown" if it is already installed and running with container and cadvisor. On Other working instance i have found dockerVersion and they are working fine.
But this instance is not detecting docker version. I thought this may help you to investigate.

Please Suggest a solution!


问:
How to limit some endpoints w.r.t logged in user in swagger `drf-yasg`?
I have setup drf-yasg, but unable to limit some endpoints for specific users only. Tried using public=False, but how to tell it that which users should see which of the endpoints ?</p>
```<code>schema_view = get_schema_view(openapi.Info(
        title="API Documentation",
        default_version='v1',
    ), public=False, permission_classes=(permissions.AllowAny,), ).with_ui("swagger", cache_timeout=0)
    return schema_view
</code>```

Body:
I have setup drf-yasg, but unable to limit some endpoints for specific users only. Tried using public=False, but how to tell it that which users should see which of the endpoints ?

schema_view = get_schema_view(openapi.Info(
        title="API Documentation",
        default_version='v1',
    ), public=False, permission_classes=(permissions.AllowAny,), ).with_ui("swagger", cache_timeout=0)
    return schema_view


问:
NEXT JS reloads page and redirect user to home page
My user is in www.domain.com/product/details page and when it click on reload page button on the browser.

The NEXT JS app reloads and redirect user to the home page with www.domain.com/. is there any way that when ever user reload or refresh the app reloads but the user stay on the same page as it was on before refreshing. I do not want to add any 'refresh' button on my app.

I want the app to reload as normal but user should stay on the same page when app is fully loaded. Like for example on amazon.com when I am on a product's page amazon.com/product/details and I click on refresh page on browser's tab, the page reloads and I am still on the same page amazon.com/product/details.


问:
Detect movement with an android device
I'm developing an Android 2.2 application.

I want to know when user moves device up or down, and when it moves to the left or to the right. The device will be at rest when mounted vertically. In other words, using the camera (Y axis along the camera's axis) for an augmented reality application where the rotation angles are needed:

```<code>remapCoordinateSystem(inR, AXIS_X, AXIS_Z, outR);
</code>```

This is my code:

```<code>public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
        accelValues = event.values;
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
        magneValues = event.values;

  updateOrientation(calculateOrientation());
}

private float[] calculateOrientation() {
    float[] values = new float[3];
    float[] R = new float[9];
    float[] outR = new float[9];

    SensorManager.getRotationMatrix(R, null, accelValues, magneValues);
    SensorManager.remapCoordinateSystem(R,
                                          SensorManager.AXIS_X,
                                          SensorManager.AXIS_Z,
                                          outR);

    SensorManager.getOrientation(outR, values);

    // Convert from Radians to Degrees.
    values[0] = (float) Math.toDegrees(values[0]); // Azimuth, rotation around Z
    values[1] = (float) Math.toDegrees(values[1]); // Pitch, rotation around X
    values[2] = (float) Math.toDegrees(values[2]); // Roll, rotation around Y

    return values;
}
</code>```

but I'm not sure how can I know if user moves device to the left or to the right.

And, how can I know if user walk?

There is an Azimuth, a Pitch and a Roll, but I don't know how can I use these values.

Any advice?

ContentLicense: CC BY-SA 3.0

Title: Detect movement with an android device

Body:
I'm developing an Android 2.2 application.

I want to know when user moves device up or down, and when it moves to the left or to the right. The device will be at rest when mounted vertically. In other words, using the camera (Y axis along the camera's axis) for an augmented reality application where the rotation angles are needed:

remapCoordinateSystem(inR, AXIS_X, AXIS_Z, outR);

This is my code:

public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
        accelValues = event.values;
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
        magneValues = event.values;

  updateOrientation(calculateOrientation());
}

private float[] calculateOrientation() {
    float[] values = new float[3];
    float[] R = new float[9];
    float[] outR = new float[9];

    SensorManager.getRotationMatrix(R, null, accelValues, magneValues);
    SensorManager.remapCoordinateSystem(R,
                                          SensorManager.AXIS_X,
                                          SensorManager.AXIS_Z,
                                          outR);

    SensorManager.getOrientation(outR, values);

    // Convert from Radians to Degrees.
    values[0] = (float) Math.toDegrees(values[0]); // Azimuth, rotation around Z
    values[1] = (float) Math.toDegrees(values[1]); // Pitch, rotation around X
    values[2] = (float) Math.toDegrees(values[2]); // Roll, rotation around Y

    return values;
}

but I'm not sure how can I know if user moves device to the left or to the right.

And, how can I know if user walk?

There is an Azimuth, a Pitch and a Roll, but I don't know how can I use these values.

Any advice?


问:
Python post products with variants from csv to shopify api
i have the following problem. I want to import products to Shopify using the API. The body of the request should look like this:

```<code>{
"product": {
    "id": "100",
    "title": "Burton Custom Freestyle 151",
    "body_html": "<strong>Good snowboard!<\/strong>",
    "vendor": "Burton",
    "product_type": "Snowboard",
    "variants": [
    {
        "option1": "First",
        "price": "10.00",
        "sku": "1000"
    },
    {
        "option1": "Second",
        "price": "20.00",
        "sku": "1001"
    }
    ]
}
}
}
</code>```

My CSV file now contains these values (of course the real one has a lot more values)
example CSV

so every product should only contain one product id with the right variant id's.
I don't have any clue how to loop through all rows and put them in the right format.
The script should check if the product id is the same as in the row before and then add it as a variant to the product.

P.S: obviously i'm new to python and coding.

Thanks for any help in advance!

Body:
i have the following problem. I want to import products to Shopify using the API. The body of the request should look like this:

{
"product": {
    "id": "100",
    "title": "Burton Custom Freestyle 151",
    "body_html": "Good snowboard!<\/strong>",
    "vendor": "Burton",
    "product_type": "Snowboard",
    "variants": [
    {
        "option1": "First",
        "price": "10.00",
        "sku": "1000"
    },
    {
        "option1": "Second",
        "price": "20.00",
        "sku": "1001"
    }
    ]
}
}
}

My CSV file now contains these values (of course the real one has a lot more values)
example CSV

so every product should only contain one product id with the right variant id's.
I don't have any clue how to loop through all rows and put them in the right format.
The script should check if the product id is the same as in the row before and then add it as a variant to the product.

P.S: obviously i'm new to python and coding.

Thanks for any help in advance!


问:
The page options.php in wordpress gives 403 error
The options.php file inside wp-admin which was working fine few days ago is now giving me 403 error suddenly. There was no change made and it gives me this error out of nowhere.

Here are few things I tried

Checking and regenerating .htaccess file.

Checking file permissions(wp-admin has 755 and options.php has 644) and ownership details which all seemed to be fine.

Deactivating and activating plugins one by one.

Checked user permissions in wordpress database. I made sure to have administrator role.

None of these helped me resolve the issue. It would be of great help if something can be suggested on solving this issue.

Note that I'm able to access other files within wp-admin folder except for options.php, Thanks.


问:
project.assets.json file references 2 different versions of a package for the same framework
I have a project that is multi-targeted net472 & net6.0-windows. For net6.0-windows there is a transient package reference with 2 different versions.

4.0.0
MyProject -> SSH.NET/2016.1.0 -> System.Net.NameResolution/4.0.0

4.3.0
MyProject -> Rebex.Elliptic.Ed25519/1.2.1 -> NETStandard.Library/1.6.1 -> runtime.win.System.Net.Sockets/4.3.0 -> System.Net.NameResolution/4.3.0

Now project.assets.json states all the target frameworks and it's dependencies. But for this project it states 2 different versions for the same framework.

```<code>  "targets": {
      ".NETFramework,Version=v4.7.2": { //not relevant },
      ".NETFramework,Version=v4.7.2/win7-x64": { //not relevant },
      "net6.0-windows7.0": {
          System.Net.NameResolution/4.0.0
      },
      "net6.0-windows7.0/win7-x64": {
          System.Net.NameResolution/4.3.0
      }

</code>```

In our team we have some custom build tools, that ran into this and failed, and I want to understand why did it happen, and why only for this project since we have multiple multi-targeted projects. How is this project.assets.json generated? Why did it state 2 different version for the same framework?

Body:
I have a project that is multi-targeted net472 & net6.0-windows. For net6.0-windows there is a transient package reference with 2 different versions.

4.0.0
MyProject -> SSH.NET/2016.1.0 -> System.Net.NameResolution/4.0.0

4.3.0
MyProject -> Rebex.Elliptic.Ed25519/1.2.1 -> NETStandard.Library/1.6.1 -> runtime.win.System.Net.Sockets/4.3.0 -> System.Net.NameResolution/4.3.0

Now project.assets.json states all the target frameworks and it's dependencies. But for this project it states 2 different versions for the same framework.

  "targets": {
      ".NETFramework,Version=v4.7.2": { //not relevant },
      ".NETFramework,Version=v4.7.2/win7-x64": { //not relevant },
      "net6.0-windows7.0": {
          System.Net.NameResolution/4.0.0
      },
      "net6.0-windows7.0/win7-x64": {
          System.Net.NameResolution/4.3.0
      }

In our team we have some custom build tools, that ran into this and failed, and I want to understand why did it happen, and why only for this project since we have multiple multi-targeted projects. How is this project.assets.json generated? Why did it state 2 different version for the same framework?


问:
Unable to load the service index for source https://api.nuget.org/v3/index.json in mac M1 docker build
I am trying to create a docker image for my dotnetcore application. but i am getting

Unable to load the service index for source
https://api.nuget.org/v3/index.json
error on step RUN dotnet restore.

Things i have tried so far.

tried nuget restore from visual studio -its working

tried accessing https://api.nuget.org/v3/index.json in browser - able to browse

tried editing docker json DNS value to "8.8.8.8"

verified PING google.com from docker container and ping is successful

So i am not sure anything related to my M1 processor or any proxy issue. I have gone through lot of online links but all are related to windows. Any help on this is appreciated. Below is my ~/nuget/Nuget/Nuget.config file and

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
</configuration>
</code>```

Docker file

```<code>FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY . .
RUN dotnet restore  "myapplication.Web/myapplication.Web.csproj"
COPY . .
WORKDIR "/src/myapplication.Web"
RUN dotnet build "myapplication.Web.csproj" -c Release -o /app/build

FROM build AS publish
WORKDIR "/src/myapplication.Web"
RUN dotnet publish "myapplication.Web.csproj" -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "myapplication.Web.dll"]
</code>```

Body:
I am trying to create a docker image for my dotnetcore application. but i am getting

Unable to load the service index for source
https://api.nuget.org/v3/index.json
error on step RUN dotnet restore.

Things i have tried so far.

tried nuget restore from visual studio -its working

tried accessing https://api.nuget.org/v3/index.json in browser - able to browse

tried editing docker json DNS value to "8.8.8.8"

verified PING google.com from docker container and ping is successful

So i am not sure anything related to my M1 processor or any proxy issue. I have gone through lot of online links but all are related to windows. Any help on this is appreciated. Below is my ~/nuget/Nuget/Nuget.config file and

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
</configuration>

Docker file

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY . .
RUN dotnet restore  "myapplication.Web/myapplication.Web.csproj"
COPY . .
WORKDIR "/src/myapplication.Web"
RUN dotnet build "myapplication.Web.csproj" -c Release -o /app/build

FROM build AS publish
WORKDIR "/src/myapplication.Web"
RUN dotnet publish "myapplication.Web.csproj" -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "myapplication.Web.dll"]


问:
How to get notifications into panel in ReactJs with AWS Graphql Subscriptions
Have created a website mainly using react, amplify, AppSync and GraphQL and AWS services. I have three buttons on react app's header to open 3 ant modals. each modal has different forms to submit data. 1st modal is Employee details adding form.Employee Information Adding Form Code
. The submitted data saves in a DynamoDB table. In Schema.graphql, I have 3 @models Scheme.graphql. In header.js file, I have use (import Notifications from "react-notification-menu-2") to display notification bell icon. (when clicking the bell icon, it displays notification panel with no data in it. because initially data = "" in Notifications code).Notification Library Code. I have created GraphQL API GraphQL API and subscription Mutation-Subscription and v2-auto creating subscription here. I want to pass a simple notification (userName added to the system) on header's notification pannel when Employee Information form Submitted. Information Submit Function

Simply I want to show a simple notification 'userName added to the system' when a user submit employee information form. I have given all the codes with images. If you have any further clarification, ask me. please anyone answer my question?


问:
Mount physical folder to SQL Server docker container using WSL2 base
I'm trying to create a container of SQL Server in Docker Desktop based on WSL2 but my container can't start (exited 1 after start). In logs tab show permission denied. Here is the content of the log file.

```<code>2023-01-02 17:31:56 /opt/mssql/bin/permissions_check.sh: line 4: [: : integer expression expected
2023-01-02 17:31:56 /opt/mssql/bin/permissions_check.sh: line 59: [: : integer expression expected
2023-01-02 17:31:56 SQL Server 2022 will run as non-root by default.
2023-01-02 17:31:56 This container is running as user mssql.
2023-01-02 17:31:56 To learn more visit https://go.microsoft.com/fwlink/?linkid=2099216.
2023-01-02 17:32:59 ** ERROR: [AppLoader] Failed to load LSA: 0xc0070102
2023-01-02 17:32:59 AppLoader: Exiting with status=0xc0070102
2023-01-02 17:32:59 This program has encountered a fatal error and cannot continue running at Mon Jan  2 10:32:59 2023
2023-01-02 17:32:59 The following diagnostic information is available:
2023-01-02 17:32:59
2023-01-02 17:32:59          Reason: 0x00000006
2023-01-02 17:32:59         Message: Termination of \SystemRoot\system32\AppLoader.exe was due to fatal error 0xC0000001
2023-01-02 17:32:59         Address: 0x3fff9c66a3ec
2023-01-02 17:32:59     Stack Trace:
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x0000000000209902
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x0000000000207E7A
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x000000000026A554
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x000000000026A3EC
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x0000000000268D28
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x0000000000201F5E
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x000000000039F6D8
2023-01-02 17:32:59                  file:///windows/system32/AppLoader.exe+0x0000000000002ED7
2023-01-02 17:32:59                  file:///windows/system32/AppLoader.exe+0x000000000000301D
2023-01-02 17:32:59                  file:///windows/system32/AppLoader.exe+0x000000000000303D
2023-01-02 17:32:59                  file:///windows/system32/AppLoader.exe+0x000000000000A378
2023-01-02 17:32:59                  file:///Windows/SYSTEM32/KERNEL32.DLL+0x0000000000017DF4
2023-01-02 17:32:59                  file:///windows/system32/ntdll.dll+0x000000000005B7C1
2023-01-02 17:32:59         Process: 9 - sqlservr
2023-01-02 17:32:59          Thread: 84 (application thread 0x128)
2023-01-02 17:32:59     Instance Id: 380bb4ed-2d23-4baa-8762-3d22ee32eb0d
2023-01-02 17:32:59        Crash Id: 10065506-dab0-4d16-849d-e327ed0a3da5
2023-01-02 17:32:59     Build stamp: d81e9b6de06534e649bd57dd609aa3050f5e380f361b7f8a80a80eeb71e7422c
2023-01-02 17:32:59    Distribution: Ubuntu 20.04.5 LTS
2023-01-02 17:32:59      Processors: 20
2023-01-02 17:32:59    Total Memory: 29440778240 bytes
2023-01-02 17:32:59       Timestamp: Mon Jan  2 10:32:59 2023
2023-01-02 17:32:59 Capturing a dump of 9
2023-01-02 17:33:07 Executing: /opt/mssql/bin/handle-crash.sh with parameters
2023-01-02 17:33:07      handle-crash.sh
2023-01-02 17:33:07      /opt/mssql/bin/sqlservr
2023-01-02 17:33:07      9
2023-01-02 17:33:07      /opt/mssql/bin
2023-01-02 17:33:07      /var/opt/mssql/log/
2023-01-02 17:33:07
2023-01-02 17:33:07      380bb4ed-2d23-4baa-8762-3d22ee32eb0d
2023-01-02 17:33:07      10065506-dab0-4d16-849d-e327ed0a3da5
2023-01-02 17:33:07
2023-01-02 17:33:07      /var/opt/mssql/log/core.sqlservr.1_2_2023_10_32_59.9
2023-01-02 17:33:07 Successfully captured dump: /var/opt/mssql/log/core.sqlservr.1_2_2023_10_32_59.9
2023-01-02 17:33:07
2023-01-02 17:33:08 Ubuntu 20.04.5 LTS
2023-01-02 17:33:08 Capturing core dump and information to /var/opt/mssql/log...
2023-01-02 17:33:08 /bin/cat: /proc/9/maps: Permission denied
2023-01-02 17:33:09 /bin/cat: /proc/9/environ: Permission denied
2023-01-02 17:33:09 /usr/bin/find: '/proc/9/map_files': Permission denied
2023-01-02 17:33:09 /usr/bin/find: '/proc/9/map_files': Permission denied
2023-01-02 17:33:09 /usr/bin/find: '/proc/9/map_files': Permission denied
2023-01-02 17:33:09 /usr/bin/find: '/proc/9/map_files': Permission denied
2023-01-02 17:33:10 dmesg: read kernel buffer failed: Operation not permitted
2023-01-02 17:33:10 /usr/bin/timeout: failed to run command '/bin/journalctl': No such file or directory
2023-01-02 17:33:10 /usr/bin/timeout: failed to run command '/bin/journalctl': No such file or directory
2023-01-02 17:33:10 Mon Jan  2 10:33:10 UTC 2023 Capturing program information
2023-01-02 17:33:10 Dump already generated: /var/opt/mssql/log/core.sqlservr.1_2_2023_10_32_59.9, moving to /var/opt/mssql/log/core.sqlservr.9.temp/core.sqlservr.9.gdmp
2023-01-02 17:33:10 Moving logs to /var/opt/mssql/log/core.sqlservr.9.temp/log/paldumper-debug.log
2023-01-02 17:33:10 Mon Jan  2 10:33:10 UTC 2023 Capturing program binaries
2023-01-02 17:33:12 Mon Jan  2 10:33:12 UTC 2023 Not compressing the dump files, moving instead to: /var/opt/mssql/log/core.sqlservr.01_02_2023_10_33_08.9.d
</code>```

And here is the command I'm trying to create a container

```<code>docker run --name SQLServer2022Test --restart always -v D:\Docker\SQL\2022\SQLTest:/var/opt/mssql -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=Aa@123456" -e "MSSQL_PID=Developer" -p 3341:1433 -d 9e28798be691
</code>```

I'm granted full control permission for docker-users in folder D:\Docker\SQL\2022\SQLTest but not effectively.

In my older server (run Windows Server 2019 datacenter and run docker desktop with Hyper-v), it runs very well!

My new server run Windows Server 2022 datacenter and runs docker desktop base WSL2.

Is there any solution to my problem?

Thank you for reading!

Body:
I'm trying to create a container of SQL Server in Docker Desktop based on WSL2 but my container can't start (exited 1 after start). In logs tab show permission denied. Here is the content of the log file.

2023-01-02 17:31:56 /opt/mssql/bin/permissions_check.sh: line 4: [: : integer expression expected
2023-01-02 17:31:56 /opt/mssql/bin/permissions_check.sh: line 59: [: : integer expression expected
2023-01-02 17:31:56 SQL Server 2022 will run as non-root by default.
2023-01-02 17:31:56 This container is running as user mssql.
2023-01-02 17:31:56 To learn more visit https://go.microsoft.com/fwlink/?linkid=2099216.
2023-01-02 17:32:59 ** ERROR: [AppLoader] Failed to load LSA: 0xc0070102
2023-01-02 17:32:59 AppLoader: Exiting with status=0xc0070102
2023-01-02 17:32:59 This program has encountered a fatal error and cannot continue running at Mon Jan  2 10:32:59 2023
2023-01-02 17:32:59 The following diagnostic information is available:
2023-01-02 17:32:59
2023-01-02 17:32:59          Reason: 0x00000006
2023-01-02 17:32:59         Message: Termination of \SystemRoot\system32\AppLoader.exe was due to fatal error 0xC0000001
2023-01-02 17:32:59         Address: 0x3fff9c66a3ec
2023-01-02 17:32:59     Stack Trace:
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x0000000000209902
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x0000000000207E7A
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x000000000026A554
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x000000000026A3EC
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x0000000000268D28
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x0000000000201F5E
2023-01-02 17:32:59                  file://package5/windows/system32/sqlpal.dll+0x000000000039F6D8
2023-01-02 17:32:59                  file:///windows/system32/AppLoader.exe+0x0000000000002ED7
2023-01-02 17:32:59                  file:///windows/system32/AppLoader.exe+0x000000000000301D
2023-01-02 17:32:59                  file:///windows/system32/AppLoader.exe+0x000000000000303D
2023-01-02 17:32:59                  file:///windows/system32/AppLoader.exe+0x000000000000A378
2023-01-02 17:32:59                  file:///Windows/SYSTEM32/KERNEL32.DLL+0x0000000000017DF4
2023-01-02 17:32:59                  file:///windows/system32/ntdll.dll+0x000000000005B7C1
2023-01-02 17:32:59         Process: 9 - sqlservr
2023-01-02 17:32:59          Thread: 84 (application thread 0x128)
2023-01-02 17:32:59     Instance Id: 380bb4ed-2d23-4baa-8762-3d22ee32eb0d
2023-01-02 17:32:59        Crash Id: 10065506-dab0-4d16-849d-e327ed0a3da5
2023-01-02 17:32:59     Build stamp: d81e9b6de06534e649bd57dd609aa3050f5e380f361b7f8a80a80eeb71e7422c
2023-01-02 17:32:59    Distribution: Ubuntu 20.04.5 LTS
2023-01-02 17:32:59      Processors: 20
2023-01-02 17:32:59    Total Memory: 29440778240 bytes
2023-01-02 17:32:59       Timestamp: Mon Jan  2 10:32:59 2023
2023-01-02 17:32:59 Capturing a dump of 9
2023-01-02 17:33:07 Executing: /opt/mssql/bin/handle-crash.sh with parameters
2023-01-02 17:33:07      handle-crash.sh
2023-01-02 17:33:07      /opt/mssql/bin/sqlservr
2023-01-02 17:33:07      9
2023-01-02 17:33:07      /opt/mssql/bin
2023-01-02 17:33:07      /var/opt/mssql/log/
2023-01-02 17:33:07
2023-01-02 17:33:07      380bb4ed-2d23-4baa-8762-3d22ee32eb0d
2023-01-02 17:33:07      10065506-dab0-4d16-849d-e327ed0a3da5
2023-01-02 17:33:07
2023-01-02 17:33:07      /var/opt/mssql/log/core.sqlservr.1_2_2023_10_32_59.9
2023-01-02 17:33:07 Successfully captured dump: /var/opt/mssql/log/core.sqlservr.1_2_2023_10_32_59.9
2023-01-02 17:33:07
2023-01-02 17:33:08 Ubuntu 20.04.5 LTS
2023-01-02 17:33:08 Capturing core dump and information to /var/opt/mssql/log...
2023-01-02 17:33:08 /bin/cat: /proc/9/maps: Permission denied
2023-01-02 17:33:09 /bin/cat: /proc/9/environ: Permission denied
2023-01-02 17:33:09 /usr/bin/find: '/proc/9/map_files': Permission denied
2023-01-02 17:33:09 /usr/bin/find: '/proc/9/map_files': Permission denied
2023-01-02 17:33:09 /usr/bin/find: '/proc/9/map_files': Permission denied
2023-01-02 17:33:09 /usr/bin/find: '/proc/9/map_files': Permission denied
2023-01-02 17:33:10 dmesg: read kernel buffer failed: Operation not permitted
2023-01-02 17:33:10 /usr/bin/timeout: failed to run command '/bin/journalctl': No such file or directory
2023-01-02 17:33:10 /usr/bin/timeout: failed to run command '/bin/journalctl': No such file or directory
2023-01-02 17:33:10 Mon Jan  2 10:33:10 UTC 2023 Capturing program information
2023-01-02 17:33:10 Dump already generated: /var/opt/mssql/log/core.sqlservr.1_2_2023_10_32_59.9, moving to /var/opt/mssql/log/core.sqlservr.9.temp/core.sqlservr.9.gdmp
2023-01-02 17:33:10 Moving logs to /var/opt/mssql/log/core.sqlservr.9.temp/log/paldumper-debug.log
2023-01-02 17:33:10 Mon Jan  2 10:33:10 UTC 2023 Capturing program binaries
2023-01-02 17:33:12 Mon Jan  2 10:33:12 UTC 2023 Not compressing the dump files, moving instead to: /var/opt/mssql/log/core.sqlservr.01_02_2023_10_33_08.9.d

And here is the command I'm trying to create a container

docker run --name SQLServer2022Test --restart always -v D:\Docker\SQL\2022\SQLTest:/var/opt/mssql -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=Aa@123456" -e "MSSQL_PID=Developer" -p 3341:1433 -d 9e28798be691

I'm granted full control permission for docker-users in folder D:\Docker\SQL\2022\SQLTest but not effectively.

In my older server (run Windows Server 2019 datacenter and run docker desktop with Hyper-v), it runs very well!

My new server run Windows Server 2022 datacenter and runs docker desktop base WSL2.

Is there any solution to my problem?

Thank you for reading!


问:
Is there a way of defining a own domain of a concrete number of values for a variable in pyomo?
i want to define a variable that just accept a specific set of numbers.

Right now i solved my problem, by using a one set with my numbers and one binary set to get my solution.

```<code>import pyomo.environ as pyo

### DATA

domain = [0.0216, 0.0285]

#### MODEL
model = pyo.ConcreteModel('oddball domain')

### SETS
model.I = pyo.Set(initialize=range(2))   # x index
model.DI = pyo.Set(initialize=[0, 1])   # domain index

### PARAMETERS
model.vals = pyo.Param(model.DI, initialize=domain)

### VARIABLES
model.x = pyo.Var(model.I, model.DI, domain=pyo.Binary)

### OBJ
model.obj = pyo.Objective(expr=sum(model.x[i, di]*model.vals[di]
                            for i in model.I
                            for di in model.DI), sense=pyo.maximize)

### CONSTRAINTS

def only_one(m, i):
    return sum(m.x[i, di] for di in m.DI) <= 1
model.C1 = pyo.Constraint(model.I, rule=only_one)

model.pprint()

solver = pyo.SolverFactory('couenne')
results = solver.solve(model)
print(results)

for i in model.I:
    for di in model.DI:
        if model.x[i,di].value:
            print(f'x[{i}] = {model.vals[di]}')
</code>```

I wonder if I could derectly define something like domain={5, 8, 9, 20} instead of using a binary variable.

In this case i get the error: TypeError: Invalid domain type for variable with name '%s'. Variable is not continuous, integer, or binary.

Body:
i want to define a variable that just accept a specific set of numbers.

Right now i solved my problem, by using a one set with my numbers and one binary set to get my solution.

import pyomo.environ as pyo

### DATA

domain = [0.0216, 0.0285]

#### MODEL
model = pyo.ConcreteModel('oddball domain')

### SETS
model.I = pyo.Set(initialize=range(2))   # x index
model.DI = pyo.Set(initialize=[0, 1])   # domain index

### PARAMETERS
model.vals = pyo.Param(model.DI, initialize=domain)

### VARIABLES
model.x = pyo.Var(model.I, model.DI, domain=pyo.Binary)

### OBJ
model.obj = pyo.Objective(expr=sum(model.x[i, di]*model.vals[di]
                            for i in model.I
                            for di in model.DI), sense=pyo.maximize)

### CONSTRAINTS

def only_one(m, i):
    return sum(m.x[i, di] for di in m.DI) <= 1
model.C1 = pyo.Constraint(model.I, rule=only_one)

model.pprint()

solver = pyo.SolverFactory('couenne')
results = solver.solve(model)
print(results)

for i in model.I:
    for di in model.DI:
        if model.x[i,di].value:
            print(f'x[{i}] = {model.vals[di]}')

I wonder if I could derectly define something like domain={5, 8, 9, 20} instead of using a binary variable.

In this case i get the error: TypeError: Invalid domain type for variable with name '%s'. Variable is not continuous, integer, or binary.


问:
Django: How to show a message in a custom admin action with a download?
I'm defining a custom admin action called Download CSV. In this action I want to download a .csv file and show a message to the user. I have not been able to make both happen.

I tried this way:

```<code>@admin.action(description=gettext_lazy("Download CSV"))
def download_csv(self, request, queryset):
    self.message_user(request=request, message=gettext_lazy("Downloaded"))

    return self.create_csv()

@staticmethod
def create_csv() -> HttpResponse:
    headers = {'Content-Disposition': f'attachment; filename="download.csv"'}
    response = HttpResponse(content_type='text/csv', headers=headers)
    response.write(codecs.BOM_UTF8)
    csv.writer(response).writerows([['example']])
    return response

actions = [download_csv]
</code>```

Does anyone know how to do it correctly?

Thanks.

Body:
I'm defining a custom admin action called Download CSV. In this action I want to download a .csv file and show a message to the user. I have not been able to make both happen.

I tried this way:

@admin.action(description=gettext_lazy("Download CSV"))
def download_csv(self, request, queryset):
    self.message_user(request=request, message=gettext_lazy("Downloaded"))

    return self.create_csv()

@staticmethod
def create_csv() -> HttpResponse:
    headers = {'Content-Disposition': f'attachment; filename="download.csv"'}
    response = HttpResponse(content_type='text/csv', headers=headers)
    response.write(codecs.BOM_UTF8)
    csv.writer(response).writerows([['example']])
    return response

actions = [download_csv]

Does anyone know how to do it correctly?

Thanks.


问:
Found interface org.apache.poi.util.POILogger, but class was expected
I am trying to read my excel file using following method:

```<code>public static String readDataFromExcel(String fileName, int rowNumber,
    int columnNumber) throws IOException {
    String valueOfCell;
    XSSFWorkbook sheetWorkBook = null;
    try {
        FileInputStream fis = new FileInputStream(fileName);
        sheetWorkBook = new XSSFWorkbook(fis);
    } catch (IOException e) {
        e.printStackTrace();
    }
    assert sheetWorkBook != null;
    Sheet sheet = sheetWorkBook.getSheetAt(0);
    Row row = sheet.getRow(rowNumber);
    Cell cell = row.getCell(columnNumber);
    valueOfCell = cell.getStringCellValue();
    return valueOfCell;
}

public static void main(String [] args) throws IOException {
    System.out.println(readDataFromExcel(filePathInString, 1, 0));
}
</code>```

Upon executing, I am getting this message:

Exception in thread "main" java.lang.IncompatibleClassChangeError:
Found interface org.apache.poi.util.POILogger, but class was expected

I need to know what I am doing wrong.

Body:
I am trying to read my excel file using following method:

public static String readDataFromExcel(String fileName, int rowNumber,
    int columnNumber) throws IOException {
    String valueOfCell;
    XSSFWorkbook sheetWorkBook = null;
    try {
        FileInputStream fis = new FileInputStream(fileName);
        sheetWorkBook = new XSSFWorkbook(fis);
    } catch (IOException e) {
        e.printStackTrace();
    }
    assert sheetWorkBook != null;
    Sheet sheet = sheetWorkBook.getSheetAt(0);
    Row row = sheet.getRow(rowNumber);
    Cell cell = row.getCell(columnNumber);
    valueOfCell = cell.getStringCellValue();
    return valueOfCell;
}

public static void main(String [] args) throws IOException {
    System.out.println(readDataFromExcel(filePathInString, 1, 0));
}

Upon executing, I am getting this message:

Exception in thread "main" java.lang.IncompatibleClassChangeError:
Found interface org.apache.poi.util.POILogger, but class was expected

I need to know what I am doing wrong.


问:
Java : UnsupportedOperationException : ASM8 and ASM9 required

Spring boot application 3.0. Hello world application

war created

Deploying on Glassfish 7

Open JDK 17

This is an exception which is being received from glassfish server logs.

Exception while visiting org/springframework/aot/hint/predicate/ResourceHintsPredicates$AggregatedResourcePatternHints.class of size 3983
java.lang.UnsupportedOperationException: Record requires ASM8
at org.objectweb.asm.ClassVisitor.visitRecordComponent(ClassVisitor.java:323)
at org.objectweb.asm.ClassReader.readRecordComponent(ClassReader.java:953)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:731)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:424)
at org.glassfish.hk2.classmodel.reflect.Parser$5.on(Parser.java:336)
at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.handleEntry(ReadableArchiveScannerAdapter.java:137)
at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.onSelectedEntries(ReadableArchiveScannerAdapter.java:100)
at org.glassfish.hk2.classmodel.reflect.Parser.doJob(Parser.java:321)
at org.glassfish.hk2.classmodel.reflect.Parser.access$300(Parser.java:44)
at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:280)
at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:269)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)

java.lang.UnsupportedOperationException: PermittedSubclasses requires ASM9
at org.objectweb.asm.ClassVisitor.visitPermittedSubclass(ClassVisitor.java:281)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:706)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:424)
at org.glassfish.hk2.classmodel.reflect.Parser$5.on(Parser.java:336)
at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.handleEntry(ReadableArchiveScannerAdapter.java:137)
at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.onSelectedEntries(ReadableArchiveScannerAdapter.java:100)
at org.glassfish.hk2.classmodel.reflect.Parser.doJob(Parser.java:321)
at org.glassfish.hk2.classmodel.reflect.Parser.access$300(Parser.java:44)
at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:280)
at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:269)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <packaging>war</packaging>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>demo</description>
    <properties>
        <java.version>17</java.version>

    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api -->
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.0.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <!--            <plugin>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-maven-plugin</artifactId>
                        </plugin>-->
        </plugins>
    </build>

</project>
</code>```

@GetMapping("/hello")
public String sayHello(@RequestParam(value = "myName", defaultValue = "World") String name) {
    return String.format("Hello %s!", name);
}
```

Body:
Spring boot application 3.0. Hello world application

war created

Deploying on Glassfish 7

Open JDK 17

This is an exception which is being received from glassfish server logs.

Exception while visiting org/springframework/aot/hint/predicate/ResourceHintsPredicates$AggregatedResourcePatternHints.class of size 3983
java.lang.UnsupportedOperationException: Record requires ASM8
at org.objectweb.asm.ClassVisitor.visitRecordComponent(ClassVisitor.java:323)
at org.objectweb.asm.ClassReader.readRecordComponent(ClassReader.java:953)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:731)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:424)
at org.glassfish.hk2.classmodel.reflect.Parser$5.on(Parser.java:336)
at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.handleEntry(ReadableArchiveScannerAdapter.java:137)
at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.onSelectedEntries(ReadableArchiveScannerAdapter.java:100)
at org.glassfish.hk2.classmodel.reflect.Parser.doJob(Parser.java:321)
at org.glassfish.hk2.classmodel.reflect.Parser.access$300(Parser.java:44)
at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:280)
at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:269)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)

java.lang.UnsupportedOperationException: PermittedSubclasses requires ASM9
at org.objectweb.asm.ClassVisitor.visitPermittedSubclass(ClassVisitor.java:281)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:706)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:424)
at org.glassfish.hk2.classmodel.reflect.Parser$5.on(Parser.java:336)
at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.handleEntry(ReadableArchiveScannerAdapter.java:137)
at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.onSelectedEntries(ReadableArchiveScannerAdapter.java:100)
at org.glassfish.hk2.classmodel.reflect.Parser.doJob(Parser.java:321)
at org.glassfish.hk2.classmodel.reflect.Parser.access$300(Parser.java:44)
at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:280)
at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:269)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/>
    </parent>
    <packaging>war</packaging>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>demo</description>
    <properties>
        <java.version>17</java.version>

    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.0.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>

        </plugins>
    </build>

</project>

@GetMapping("/hello")
public String sayHello(@RequestParam(value = "myName", defaultValue = "World") String name) {
    return String.format("Hello %s!", name);
}


问:
i am hitting this keepa api but data is coming like this
```<code>public function CallAPI($method, $url, $data = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication:
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);

    curl_close($curl);

    return $result;
}
</code>```

```<code>$res = CallAPI('GET',
        'https://api.keepa.com/product?key=786fc09u868cl88g4llvppn511v5ihdbld3tjqq8mom28rtac4crijm5u4rerk43&asin=0134472098&domain=1'
       );
</code>```

��ĝɮuKvV��7(��v��,AǢgѰ���3-g~y4ƌXk���q���;�b�,��?���~��������_�e��[�{~����o�����?��_�^�_�������ۿ��/���g��˿��o�����������o����O�����5��tK�7�����~�O���?���?��o~������~�w�������u�g~��_~����o���~������1wJ�2RI��gMi}J�u}j���rieռǧ�6˧��ˈ/��V^Zm���h�ҧ��K�h5�h,PO�/kmQi�F�����K+y�% �:HZ-���F���oڨy}J���ZM�R�ܢ-��EC�gMP�c���dk�M�s����-��.�L���w�d�2wI��+c]�J�Z���7%�b)�V�Q,eY_��RV�z�(eX�Q��#���0���m}�0�N.�c���5K��Wz����F�R�m�1��ޖգ��}wJ��5Uj�R����)�&{[K��������.zԭ�&VQIӶ��E1#ef3�Č�x�]�u���]�-U��R���d-��7�<��>A����v-���������0��6����7h�s��]d)u�"j�Rf�/�q��E#P|9�_m�/��j�R�k}j����O�f������fcvJu��j��RG��F T���Η3h��ל�e�����R{�kQ�v�AK�����Ҋ����=�鵩o�Xg�ܞ%%���Z�rv}m{���/g��^i{��h�@��^�>��1�%��^%{��kp�(űΕӭ�T,�rN��j�����iK�~�v����8�r�쥯����r}i5'��K�� ���]+�����\��z�5ѥu�����U_��Ї6��d��>�YX��� �yQ��>礝�1}�2���Uw��r�l���;�͙�Q�k0�9>uԶ�re��:'7WΜR�9��w3i�98����̢��Ν/ӮTg��ae�=G���Lym�ڝytz���:K���V��� �u��e��]PRgngM���:{s�<����k�Z�VPu}�2k_ T8[g���Ou�%��>����R�哻k~��ݟ�����>�����'�-E�R�cľ�䕸��Nm�O;S�ޮ��8wW���.�U@+�z��U���W��c�����2�����{h}�/��A������Ъ|ȥ�������5n���m٥������И�����y;ݾ��<_�B;Zߴ��i��Z����Y�_4n؇������C�zh��w�{%��*Y�.��A}��r�2gH��+���

Body:
public function CallAPI($method, $url, $data = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication:
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);

    curl_close($curl);

    return $result;
}

$res = CallAPI('GET',
        'https://api.keepa.com/product?key=786fc09u868cl88g4llvppn511v5ihdbld3tjqq8mom28rtac4crijm5u4rerk43&asin=0134472098&domain=1'
       );

��ĝɮuKvV��7(��v��,AǢgѰ���3-g~y4ƌXk���q���;�b�,��?���~��������_�e��[�{~����o�����?��_�^�_�������ۿ��/���g��˿��o�����������o����O�����5��tK�7�����~�O���?���?��o~������~�w�������u�g~��_~����o���~������1wJ�2RI��gMi}J�u}j���rieռǧ�6˧��ˈ/��V^Zm���h�ҧ��K�h5�h,PO�/kmQi�F�����K+y�% �:HZ-���F���oڨy}J���ZM�R�ܢ-��EC�gMP�c���dk�M�s����-��.�L���w�d�2wI��+c]�J�Z���7%�b)�V�Q,eY_��RV�z�(eX�Q��#���0���m}�0�N.�c���5K��Wz����F�R�m�1��ޖգ��}wJ��5Uj�R����)�&{[K��������.zԭ�&VQIӶ��E1#ef3�Č�x�]�u���]�-U��R���d-��7�<��>A����v-���������0��6����7h�s��]d)u�"j�Rf�/�q��E#P|9�_m�/��j�R�k}j����O�f������fcvJu��j��RG��F T���Η3h��ל�e�����R{�kQ�v�AK�����Ҋ����=�鵩o�Xg�ܞ%%���Z�rv}m{���/g��^i{��h�@��^�>��1�%��^%{��kp�(űΕӭ�T,�rN��j�����iK�~�v����8�r�쥯����r}i5'��K�� ���]+�����\��z�5ѥu�����U_��Ї6��d��>�YX��� �yQ��>礝�1}�2���Uw��r�l���;�͙�Q�k0�9>uԶ�re��:'7WΜR�9��w3i�98����̢��Ν/ӮTg��ae�=G���Lym�ڝytz���:K���V��� �u��e��]PRgngM���:{s�<����k�Z�VPu}�2k_ T8[g���Ou�%��>����R�哻k~��ݟ�����>�����'�-E�R�cľ�䕸��Nm�O;S�ޮ��8wW���.�U@+�z��U���W��c�����2�����{h}�/��A������Ъ|ȥ�������5n���m٥������И�����y;ݾ��<_�B;Zߴ��i��Z����Y�_4n؇������C�zh��w�{%��*Y�.��A}��r�2gH��+���


问:
Using SQL Server spatial with ADO, char set failure
I'm working with Delphi 10.4, ADO, SQL Server, using  spatial features (SQL Server spatial ).

Reading the text from the  database is based on this code:

```<code>    type TDatabaserecord = record
              ...
              NameStr : String;
              OutLineStr : String;
              ...
         end;
    type TTabRecordList = class(TList<TDatabaserecord>)

         private
         ...
         public
         procedure SavetoFile(Filename: String);

         end;

        procedure ReadDBConent ( ....., MYDatabaserecord : TDatabaserecord );
        begin
             ....
             MyDatabaserecord.NameStr := Fieldbyname('Name').AsString;
             MyDatabaserecord.OutLineStr := Fieldbyname('Geom').AsString;
             ...

        end;

        procedure  TTabRecordList.SaveDBConent ( ..... );
        var
          i: Integer;
          ds: TDatabaserecord;
          Content: TStringlist;
        begin
          Content := TStringlist.create;
          try

            for i := 0 to self.Count - 1 do
            begin
              ds := self.Items[i];
              ...
              ...
              Content.add('Name=' + ds.NameStr);
              Content.add('OutLine=' + ds.OutLineStr);

            end;

            Content.SavetoFile(Filename);

          finally
            Content.Free;
          end;
        end;
</code>```

Running this code twice at different locations in my code, using the same database I get different  results

```<code>    (pass , getting correct data)
    Name=NameofObject
    OutLine=POLYGON ((330692534935335 323094130298054, 347882368377054 323094130298054, 347907281179144 319182820370010, 330717447737425 319108081963742, 330692534935335 323094130298054))

    (fail, getting wrong char set ???)
    Name=NameofObject
    OutLine=       €3þÕW¦ÅBp8çŠŸ,úB bM³ÁÈB ]M(Y-úB JHÿÏÈB0Î©1¿øB€È–K>©ÅB`*4Gë¿øB€3þÕW¦ÅBp8çŠŸ,úB          ÿÿÿÿ
</code>```

Failures is only linked  on reading the spatial field 'geom'
Question: do I need to specify the char set while reading data from a SQL Server database? How to do this?

Additional Information on table definition , SQL Statement

```<code>create table TableName ( Name varchar(50) NULL,
...
                         Geom geometry)
</code>```

Body:
I'm working with Delphi 10.4, ADO, SQL Server, using  spatial features (SQL Server spatial ).

Reading the text from the  database is based on this code:

    type TDatabaserecord = record
              ...
              NameStr : String;
              OutLineStr : String;
              ...
         end;
    type TTabRecordList = class(TList<TDatabaserecord>)

         private
         ...
         public
         procedure SavetoFile(Filename: String);

         end;

        procedure ReadDBConent ( ....., MYDatabaserecord : TDatabaserecord );
        begin
             ....
             MyDatabaserecord.NameStr := Fieldbyname('Name').AsString;
             MyDatabaserecord.OutLineStr := Fieldbyname('Geom').AsString;
             ...

        end;

        procedure  TTabRecordList.SaveDBConent ( ..... );
        var
          i: Integer;
          ds: TDatabaserecord;
          Content: TStringlist;
        begin
          Content := TStringlist.create;
          try

            for i := 0 to self.Count - 1 do
            begin
              ds := self.Items[i];
              ...
              ...
              Content.add('Name=' + ds.NameStr);
              Content.add('OutLine=' + ds.OutLineStr);

            end;

            Content.SavetoFile(Filename);

          finally
            Content.Free;
          end;
        end;

Running this code twice at different locations in my code, using the same database I get different  results

    (pass , getting correct data)
    Name=NameofObject
    OutLine=POLYGON ((330692534935335 323094130298054, 347882368377054 323094130298054, 347907281179144 319182820370010, 330717447737425 319108081963742, 330692534935335 323094130298054))

    (fail, getting wrong char set ???)
    Name=NameofObject
    OutLine=       €3þÕW¦ÅBp8çŠŸ,úB bM³ÁÈB ]M(Y-úB JHÿÏÈB0Î©1¿øB€È–K>©ÅB`*4Gë¿øB€3þÕW¦ÅBp8çŠŸ,úB          ÿÿÿÿ

Failures is only linked  on reading the spatial field 'geom'
Question: do I need to specify the char set while reading data from a SQL Server database? How to do this?

Additional Information on table definition , SQL Statement

create table TableName ( Name varchar(50) NULL,
...
                         Geom geometry)