问:
Issue with nested Ajax calls
I am having a series of nested Ajax calls to create and update data into the database as well as calling the updated list once data are successfully submitted.

This is how the code works:

(1) A list of transaction is shown when the page is rendered, each row can be edited by the user.

(2) When clicking a specific row, I run an Ajax call to retrive the form filled with the data to be updated

(3) The form is then submitted via Ajax as well.

(4) If successfully submitted it perform another Ajax call to get the table updated.

First problem: when the table is loaded via Ajax the "edit" button is not working anymore.
Second problem: The form displayed to update and to create is the same, except when updating the form is pre-filled. I would like to avoid duplicating the Ajax call but I had to do it otherwise I wasn't able to submit the form after it was loaded from the first Ajax call (pt 1). Is there a way to make a more clean code?

Here it is the javascript code, server side all works just fine:

```<code>$(".edit-transaction").click(function () {
  // obtain the object id to load the correct form
  const object_id = $(this).data('object-id');

  // request the form via AJAX Get request
  $.ajax({
    type: 'GET',
    url: "/transaction/",
    data: {
      'slug': object_id
    },
    success: function(response) {
      // Get the form for the requested object
      $("#display-form").html(response.html); // this code retrive the form
      $("#transaction-form").submit(function (e) {
        // preventing from page reload and default actions
        e.preventDefault();

        let serializedData = $(this).serialize();

        // Update the form via AJAX
        $.ajax({
          type: 'POST',
          url: "/transaction/",
          data: serializedData,
          success: function (response) {
            console.log('updated successfully')

            // load the table with the new content updated
            $.ajax({
              type: 'GET',
              url: "/get-transactions-list/",
              success: function (data) {
                $("#display-transaction-list").html(data.html);
              },
            });
          },
          error: function (response) {
            let error = response ["responseJSON"]["error"];
            $.each(error, function (code, message) {
              alert('message');
            });
          }
        })
      })
    },
    error: function (response) {
      let error = response ["responseJSON"]["error"];
      $.each(error, function (code, message) {
        alert('message');
      });
    }
  })

});
$("#transaction-form").submit(function (e) {
  // preventing from page reload and default actions
  e.preventDefault();
  let serializedData = $(this).serialize();

  // Create a new transaction via AJAX
  $.ajax({
    type: 'POST',
    url: "/transaction/",
    data: serializedData,
    success: function (response) {
      console.log('created successfully')
      // load the table with the new content updated
      $.ajax({
        type: 'GET',
        url: "/get-transactions-list/",
        success: function (data) {
          $("#display-transaction-list").html(data.html);
        },
      });
    },
    error: function (response) {
      let error = response ["responseJSON"]["error"];
      $.each(error, function (code, message) {
        alert('message');
      });
    }
  })
})
</code>```

Thanks for any help

答:
Since some of the elements are added asynchronously, this means that the event listeners which were added at runtime will not affect those elements. You should instead listen to events on them via "events delegation".

You can also create a custom event for loading the table content. So to update the table, you just .trigger() your custom event. This is useful when you want to implement other functionalities which will need a table update like, delete, etc.

// custom event for loading the table content
$(document).on('load.table', '#display-transaction-list', function () {
    const $table = $(this);
    $.ajax({
        type: 'GET',
        url: "/get-transactions-list/",
        success: (data) => $table.html(data.html)
    });
});
// edit transaction event
$(document).on('click', '.edit-transaction', function () {
    // obtain the object id to load the correct form
    const object_id = $(this).data('object-id');

    // request the form via AJAX Get request
    $.ajax({
            type: 'GET',
            url: "/transaction/",
            data: {
                'slug': object_id
            },
            success: function(response) {
                // Get the form for the requested object
                $("#display-form").html(response.html); // this code retrive the form
            },
            error: function (response) {
                let error = response ["responseJSON"]["error"];
                $.each(error, function (code, message) {
                alert('message');
            });
        }
    })
});
// save transaction event
$(document).on('submit', '#transaction-form', function (e) {
    // preventing from page reload and default actions
    e.preventDefault();

    let serializedData = $(this).serialize();

    // Update the form via AJAX
    $.ajax({
        type: 'POST',
        url: "/transaction/",
        data: serializedData,
        success: function (response) {
            // you can add some data to the response
            // to differentiate between created and updated. Eg response.actionType
            console.log('created or updated successfully')

            // load the table with the new content updated
            $("#display-transaction-list").trigger('load.table');
        },
        error: function (response) {
            let error = response ["responseJSON"]["error"];
            $.each(error, function (code, message) {
                alert('message');
            });
        }
    })
})```

Title: Issue with nested Ajax calls

Body:
I am having a series of nested Ajax calls to create and update data into the database as well as calling the updated list once data are successfully submitted.

This is how the code works:

(1) A list of transaction is shown when the page is rendered, each row can be edited by the user.

(2) When clicking a specific row, I run an Ajax call to retrive the form filled with the data to be updated

(3) The form is then submitted via Ajax as well.

(4) If successfully submitted it perform another Ajax call to get the table updated.

First problem: when the table is loaded via Ajax the "edit" button is not working anymore.
Second problem: The form displayed to update and to create is the same, except when updating the form is pre-filled. I would like to avoid duplicating the Ajax call but I had to do it otherwise I wasn't able to submit the form after it was loaded from the first Ajax call (pt 1). Is there a way to make a more clean code?

Here it is the javascript code, server side all works just fine:

$(".edit-transaction").click(function () {
  // obtain the object id to load the correct form
  const object_id = $(this).data('object-id');

  // request the form via AJAX Get request
  $.ajax({
    type: 'GET',
    url: "/transaction/",
    data: {
      'slug': object_id
    },
    success: function(response) {
      // Get the form for the requested object
      $("#display-form").html(response.html); // this code retrive the form
      $("#transaction-form").submit(function (e) {
        // preventing from page reload and default actions
        e.preventDefault();

        let serializedData = $(this).serialize();

        // Update the form via AJAX
        $.ajax({
          type: 'POST',
          url: "/transaction/",
          data: serializedData,
          success: function (response) {
            console.log('updated successfully')

            // load the table with the new content updated
            $.ajax({
              type: 'GET',
              url: "/get-transactions-list/",
              success: function (data) {
                $("#display-transaction-list").html(data.html);
              },
            });
          },
          error: function (response) {
            let error = response ["responseJSON"]["error"];
            $.each(error, function (code, message) {
              alert('message');
            });
          }
        })
      })
    },
    error: function (response) {
      let error = response ["responseJSON"]["error"];
      $.each(error, function (code, message) {
        alert('message');
      });
    }
  })

});
$("#transaction-form").submit(function (e) {
  // preventing from page reload and default actions
  e.preventDefault();
  let serializedData = $(this).serialize();

  // Create a new transaction via AJAX
  $.ajax({
    type: 'POST',
    url: "/transaction/",
    data: serializedData,
    success: function (response) {
      console.log('created successfully')
      // load the table with the new content updated
      $.ajax({
        type: 'GET',
        url: "/get-transactions-list/",
        success: function (data) {
          $("#display-transaction-list").html(data.html);
        },
      });
    },
    error: function (response) {
      let error = response ["responseJSON"]["error"];
      $.each(error, function (code, message) {
        alert('message');
      });
    }
  })
})

Thanks for any help


来源: stackexchange

问:
implicit declaration of function 'getaddrinfo' on Windows with Mingw
I'm trying to create a really basic client application, based on the code on msdn but i get the error in the title.
Here is the complete code:

```<code>#include <tchar.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment (lib, "Ws2_32.lib")
#define DEBUG 1

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "9001"

void CreateSocket();
int main(int argc, char* argv[])
{
    CreateSocket();

    return 0;
}

void CreateSocket()
{
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
                    *ptr = NULL,
                    hints;
    char *sendbuf = "this is a test";
    int iResult;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);

    ZeroMemory( &hints, sizeof(hints) );

    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
    ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
            ptr->ai_protocol);

    iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);

    freeaddrinfo(result);
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );

    closesocket(ConnectSocket);
    WSACleanup();

}
</code>```

I'm on Windows 10, with MinGW.
This the complete compile and error:

```<code>gcc -Wall -o "test" "test.c" -lws2_32 (nel direttorio: C:\Users\FedericoPonzi\Google Drive\Programmazione\C\ProgrammazioneDiSistema\FedericoPonzi-programmazionedisistema-40c332bcd001\FedericoPonzi-programmazionedisistema-40c332bcd001\Prove)
test.c:10:0: warning: ignoring #pragma comment  [-Wunknown-pragmas]
 #pragma comment (lib, "Ws2_32.lib")
 ^
test.c: In function 'CreateSocket':
test.c:46:2: warning: implicit declaration of function 'getaddrinfo' [-Wimplicit-function-declaration]
  iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
  ^
test.c:52:2: warning: implicit declaration of function 'freeaddrinfo' [-Wimplicit-function-declaration]
  freeaddrinfo(result);
  ^
test.c:35:6: warning: variable 'iResult' set but not used [-Wunused-but-set-variable]
  int iResult;
      ^
C:\Users\FEDERI~1\AppData\Local\Temp\ccAW2c9I.o:test.c:(.text+0xbb): undefined reference to `getaddrinfo'
C:\Users\FEDERI~1\AppData\Local\Temp\ccAW2c9I.o:test.c:(.text+0x11b): undefined reference to `freeaddrinfo'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: C:\Users\FEDERI~1\AppData\Local\Temp\ccAW2c9I.o: bad reloc address 0x20 in section `.eh_frame'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link failed: Invalid operation
collect2.exe: error: ld returned 1 exit status
Compilazione fallita.
</code>```

I'm using Geany as IDE.

Also: why do i get the "ignoring pragma" error? Thanks.

答:
#pragma comment (lib, "Ws2_32.lib")
is Microsoft speciofic (as LPs answered). It means "link this library." E.g. in case of gcc add this linking request -l (lowercase minus L with name of library) to command line, e.g.
gcc yoursource.c ... -lWs2_32</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a really basic client application, based on the code on msdn but i get the error in the title.
Here is the complete code:

#include <tchar.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment (lib, "Ws2_32.lib")
#define DEBUG 1

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "9001"

void CreateSocket();
int main(int argc, char* argv[])
{
    CreateSocket();

    return 0;
}

void CreateSocket()
{
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
                    *ptr = NULL,
                    hints;
    char *sendbuf = "this is a test";
    int iResult;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);

    ZeroMemory( &hints, sizeof(hints) );

    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
    ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
            ptr->ai_protocol);

    iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);

    freeaddrinfo(result);
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );

    closesocket(ConnectSocket);
    WSACleanup();

}

I'm on Windows 10, with MinGW.
This the complete compile and error:

gcc -Wall -o "test" "test.c" -lws2_32 (nel direttorio: C:\Users\FedericoPonzi\Google Drive\Programmazione\C\ProgrammazioneDiSistema\FedericoPonzi-programmazionedisistema-40c332bcd001\FedericoPonzi-programmazionedisistema-40c332bcd001\Prove)
test.c:10:0: warning: ignoring #pragma comment  [-Wunknown-pragmas]
 #pragma comment (lib, "Ws2_32.lib")
 ^
test.c: In function 'CreateSocket':
test.c:46:2: warning: implicit declaration of function 'getaddrinfo' [-Wimplicit-function-declaration]
  iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
  ^
test.c:52:2: warning: implicit declaration of function 'freeaddrinfo' [-Wimplicit-function-declaration]
  freeaddrinfo(result);
  ^
test.c:35:6: warning: variable 'iResult' set but not used [-Wunused-but-set-variable]
  int iResult;
      ^
C:\Users\FEDERI~1\AppData\Local\Temp\ccAW2c9I.o:test.c:(.text+0xbb): undefined reference to `getaddrinfo'
C:\Users\FEDERI~1\AppData\Local\Temp\ccAW2c9I.o:test.c:(.text+0x11b): undefined reference to `freeaddrinfo'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: C:\Users\FEDERI~1\AppData\Local\Temp\ccAW2c9I.o: bad reloc address 0x20 in section `.eh_frame'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link failed: Invalid operation
collect2.exe: error: ld returned 1 exit status
Compilazione fallita.

I'm using Geany as IDE.

Also: why do i get the "ignoring pragma" error? Thanks.

ContentLicense: CC BY-SA 4.0


问:
Are there good reasons to wrap a single property in a #region in c#?
I recently inherited some C# code where nearly every item in a file was wrapped in an individual #region/#endregion block -- every class, every function, every property, every enum, but not the fields.  Each of these was in turn wrapped in a "grouping" #region (e.g. "Properties", "Constructor", "Methods", etc.).  There are multiple overloads of a single function with different argument lists, but they're each wrapped in individual regions with the same name, rather than a single region for all three overloads.  The person who wrote this code is no longer with the company, and from the history in source control, it appears that these were present in the initial submission, and the practice continues through successive versions of the code as new properties and methods are added.

Any idea why this might be done?  Some thoughts:

An overzealous VS feature (or code-cleanup tool) automatically inserted the #region/#endregion blocks, and the author didn't remove them.

There's an IDE that folds regions but not functions, so this was necessary to get syntax folding.

This is a method of stubbing out the structure of your code prior to implementing it.

EDIT: I chose Jonathan's answer because it contributed a new reason why someone might have chosen to do this.  Thanks for the discussion!

答:
This seems like the result of a developer who doesn't understand how to use the IDE effectively (ie: code folding of methods, using the navigation features in the editor, etc).  I would, personally, remove most (all?) of these regions, as they actually work against you in many ways.

Wrapping things in regions does have its place, but I'd argue that it's actually often counter-productive as a general practice.  It's hiding code - and I often find makes it easier for developers to leave in inappropriate code, miss good refactoring opportunities, allow complex methods (that should be split up) to creep in over time, and let types get all together too large.

That being said - regions are a feature, and it's very much personal preference whether and how much to use them, as they have no impact on the compiled code.


问:
I want to make dynamic titles like in WordPress
there is an option in wordpress in which inside brackets "{}" the word changes depending on the search term, how can I do the same on my page? without using wordpress</p>

答:
i don't think you want to do that with pure html and css. take at look at this sample.

Happy coding :)


问:
How to pass/type react-hook-form `setValue` to custom react hook (typescript)?
How can i pass setValue to a react hook?

I have a custom react hook, where I would like to set values in a form, by passing react-hook-form's setValue. However, since the migration from v6->v7 i can't for the life of me figure out the typing.

The hook looks like:

```<code>export function useUnselectOnChange(
  id: UUID,
  setValue: any // TODO: How to type this properly
  options?: Partial<UseUnselectOnChangeOptions>,
): void {
  const { current: optionsRef } = useRef<UseUnselectOnChangeOptions>({
    fallbackValue: ReorderEnum.Top,
    fieldName: 'place',
    ...options,
  });
  const previousUuid = useRef(id);

  useLayoutEffect(() => {
    if (previousUuid.current !== id) {
      setValue(optionsRef.fieldName, optionsRef.fallbackValue);
    }

    previousUuid.current = id;
  }, [id, setValue, optionsRef]);
}
</code>```

Used like this:

```<code>useUnselectOnChange(id, setValue, {
  fallbackValue: '',
  fieldName: 'component',
});
</code>```

Previously setValue: UseFormMethods<Record<string, string>>['setValue'] worked but UseFormMethods does not exist  anymore.
I use useFrom<FormValues>() to get the form methods (setValue ++). This is how I do it in every component. FormValues is the where I specify the members and types of each form (so every FormValues is different). I can't figure out a generic typing in my hook that will accept setValue. Ideas?

答:
It looks like you'll need to use a generic and the UseFormSetValue type that your custom hook takes.
So it'll be

```<code>function customHook<T>(setValue:UseFormSetValue<T>){
  return []
}
</code>```

then used like

```<code>const [] = customHook<IFormInput>(setValue)
</code>```

Body:
How can i pass setValue to a react hook?

I have a custom react hook, where I would like to set values in a form, by passing react-hook-form's setValue. However, since the migration from v6->v7 i can't for the life of me figure out the typing.

The hook looks like:

export function useUnselectOnChange(
  id: UUID,
  setValue: any // TODO: How to type this properly
  options?: Partial<UseUnselectOnChangeOptions>,
): void {
  const { current: optionsRef } = useRef<UseUnselectOnChangeOptions>({
    fallbackValue: ReorderEnum.Top,
    fieldName: 'place',
    ...options,
  });
  const previousUuid = useRef(id);

  useLayoutEffect(() => {
    if (previousUuid.current !== id) {
      setValue(optionsRef.fieldName, optionsRef.fallbackValue);
    }

    previousUuid.current = id;
  }, [id, setValue, optionsRef]);
}

Used like this:

useUnselectOnChange(id, setValue, {
  fallbackValue: '',
  fieldName: 'component',
});

Previously setValue: UseFormMethods<Record<string, string>>['setValue'] worked but UseFormMethods does not exist  anymore.
I use useFrom<FormValues>() to get the form methods (setValue ++). This is how I do it in every component. FormValues is the where I specify the members and types of each form (so every FormValues is different). I can't figure out a generic typing in my hook that will accept setValue. Ideas?

Body:
It looks like you'll need to use a generic and the UseFormSetValue type that your custom hook takes.
So it'll be

function customHook<T>(setValue:UseFormSetValue<T>){
  return []
}

then used like

const [] = customHook<IFormInput>(setValue)


答:
Good reasons?  Probably not.

More like overzealous commenting, or possibley a tool that did that.

My regions typically consist of:

```<code>#region - Public Methods
#region - Private Methods
#region - Protected Methods
#region - Data Members
#region - Properties
</code>```

Perhaps they were using an "auto generated help" type of document which looked for region instead of comments to build the "help document?"

Title: Are there good reasons to wrap a single property in a #region in c#?

Body:
I recently inherited some C# code where nearly every item in a file was wrapped in an individual #region/#endregion block -- every class, every function, every property, every enum, but not the fields.  Each of these was in turn wrapped in a "grouping" #region (e.g. "Properties", "Constructor", "Methods", etc.).  There are multiple overloads of a single function with different argument lists, but they're each wrapped in individual regions with the same name, rather than a single region for all three overloads.  The person who wrote this code is no longer with the company, and from the history in source control, it appears that these were present in the initial submission, and the practice continues through successive versions of the code as new properties and methods are added.

Any idea why this might be done?  Some thoughts:

An overzealous VS feature (or code-cleanup tool) automatically inserted the #region/#endregion blocks, and the author didn't remove them.

There's an IDE that folds regions but not functions, so this was necessary to get syntax folding.

This is a method of stubbing out the structure of your code prior to implementing it.

EDIT: I chose Jonathan's answer because it contributed a new reason why someone might have chosen to do this.  Thanks for the discussion!

Body:
Good reasons?  Probably not.

More like overzealous commenting, or possibley a tool that did that.

My regions typically consist of:

#region - Public Methods
#region - Private Methods
#region - Protected Methods
#region - Data Members
#region - Properties

Perhaps they were using an "auto generated help" type of document which looked for region instead of comments to build the "help document?"


问:
spring boot mvc - Content type 'application/json;charset=UTF-8' not supported
In this spring boot project I get an error when POSTing (using Postman) a new Item resource

```<code>Resolving exception from handler
     [public com.example.demo.resource.Item com.example.demo.controller.ItemController.addItem(com.example.demo.resource.Item)]:
     org.springframework.web.HttpMediaTypeNotSupportedException:
     Content type 'application/json;charset=UTF-8' not supported
</code>```

In the request body I copied one of the existing Items that I got from a GET request (and changed the id and itemName)

```<code>    // Request body:
    {
        "id": 10, // also tried without id field as it's autogenerated
        "itemName": "milk",
        "cart": {
            "id": 1
        }
    }
</code>```

I made sure that I have the correct getters and setters in the Item class (as this is a known issue)

```<code>@Entity
@Table(name="items")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
@JsonIdentityInfo(
          generator = ObjectIdGenerators.PropertyGenerator.class,
          property = "id")
public class Item
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "item_id")
    private long id;

    @Column(name="item_name")
    private String itemName;

    @ManyToOne
    @JoinColumn(name = "cart_id", nullable=false)
    @JsonManagedReference
    private Cart cart;

   //setters and getters
}
</code>```

Here is also the Cart class to which Item has a many-to-one relationship

```<code>@Entity
@Table(name="carts")
@JsonIdentityInfo(
          generator = ObjectIdGenerators.PropertyGenerator.class,
          property = "id")
public class Cart
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "cart_id")
    private long id;

    @OneToMany(mappedBy = "cart")
    @JsonBackReference
    private Set<Item> items;

    //setters and getters
}
</code>```

This is the ItemController

```<code>@RestController
public class ItemController
{
    private static final Logger LOG = LoggerFactory.getLogger(ItemController.class);

    @Autowired ItemDao dao;

    @GetMapping("items")
    public List<Item> getAll()
    {
        List<Item> res = new ArrayList<>();
        dao.findAll().forEach(res::add);
        return res;
    }

    @PostMapping("items")
    public Item addItem(@RequestBody Item item)
    {
        return dao.save(item);
    }

    @GetMapping("items/{item_id}")
    public Item getItemById(@PathVariable("item_id") long item_id)
    {
        Item item = dao.findById(item_id).get();
        LOG.info(" ---------------- Retrieved item: {}", item.toString());
        return item;
    }
}
</code>```

EDIT

I just noticed that there seems to be another error preceding:

```<code>Failed to evaluate Jackson deserialization for type [[simple type, class com.example.demo.resource.Item]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.Set) not compatible with managed type (com.example.demo.resource.Item)
</code>```

Here is the full error:

```<code>2018-02-27 11:03:09.836  WARN 9640 --- [nio-9200-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.demo.resource.Item]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.Set) not compatible with managed type (com.example.demo.resource.Item)
2018-02-27 11:03:09.837  WARN 9640 --- [nio-9200-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.demo.resource.Item]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.Set) not compatible with managed type (com.example.demo.resource.Item)
2018-02-27 11:03:09.838 DEBUG 9640 --- [nio-9200-exec-1] .w.s.m.m.a.ServletInvocableHandlerMethod : Failed to resolve argument 0 of type 'com.example.demo.resource.Item'

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported
</code>```

Thanks for the help

答: try replacing Content type from 'application/json;charset=UTF-8' to 'application/json'. I had the same issue and that fixed mine.

Body:
In this spring boot project I get an error when POSTing (using Postman) a new Item resource

Resolving exception from handler
     [public com.example.demo.resource.Item com.example.demo.controller.ItemController.addItem(com.example.demo.resource.Item)]:
     org.springframework.web.HttpMediaTypeNotSupportedException:
     Content type 'application/json;charset=UTF-8' not supported

In the request body I copied one of the existing Items that I got from a GET request (and changed the id and itemName)

    // Request body:
    {
        "id": 10, // also tried without id field as it's autogenerated
        "itemName": "milk",
        "cart": {
            "id": 1
        }
    }

I made sure that I have the correct getters and setters in the Item class (as this is a known issue)

@Entity
@Table(name="items")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
@JsonIdentityInfo(
          generator = ObjectIdGenerators.PropertyGenerator.class,
          property = "id")
public class Item
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "item_id")
    private long id;

    @Column(name="item_name")
    private String itemName;

    @ManyToOne
    @JoinColumn(name = "cart_id", nullable=false)
    @JsonManagedReference
    private Cart cart;

   //setters and getters
}

Here is also the Cart class to which Item has a many-to-one relationship

@Entity
@Table(name="carts")
@JsonIdentityInfo(
          generator = ObjectIdGenerators.PropertyGenerator.class,
          property = "id")
public class Cart
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "cart_id")
    private long id;

    @OneToMany(mappedBy = "cart")
    @JsonBackReference
    private Set<Item> items;

    //setters and getters
}

This is the ItemController

@RestController
public class ItemController
{
    private static final Logger LOG = LoggerFactory.getLogger(ItemController.class);

    @Autowired ItemDao dao;

    @GetMapping("items")
    public List<Item> getAll()
    {
        List<Item> res = new ArrayList<>();
        dao.findAll().forEach(res::add);
        return res;
    }

    @PostMapping("items")
    public Item addItem(@RequestBody Item item)
    {
        return dao.save(item);
    }

    @GetMapping("items/{item_id}")
    public Item getItemById(@PathVariable("item_id") long item_id)
    {
        Item item = dao.findById(item_id).get();
        LOG.info(" ---------------- Retrieved item: {}", item.toString());
        return item;
    }
}

EDIT

I just noticed that there seems to be another error preceding:

Failed to evaluate Jackson deserialization for type [[simple type, class com.example.demo.resource.Item]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.Set) not compatible with managed type (com.example.demo.resource.Item)

Here is the full error:

2018-02-27 11:03:09.836  WARN 9640 --- [nio-9200-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.demo.resource.Item]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.Set) not compatible with managed type (com.example.demo.resource.Item)
2018-02-27 11:03:09.837  WARN 9640 --- [nio-9200-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.demo.resource.Item]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.Set) not compatible with managed type (com.example.demo.resource.Item)
2018-02-27 11:03:09.838 DEBUG 9640 --- [nio-9200-exec-1] .w.s.m.m.a.ServletInvocableHandlerMethod : Failed to resolve argument 0 of type 'com.example.demo.resource.Item'

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported

Thanks for the help


问:
Should I be using break; to exit my while loop?
I am in need of exiting my while loop, I have attempted using break; however, my next output does not align correctly. Here is my current output (without break;):

```<code>List of Gamers:
-----------------------------------------------------------------------------------------------------
Adelie, Carden, Cora, Lada, Mario, Mich, Sally, Xavier-----------------------------------------------------------------------------------------------------
</code>```

The desired output should be:

```<code>List of Gamers:
-----------------------------------------------------------------------------------------------
Adelie, Bob, Carden, Chang, Cora, Jonas, Lada, Lev, Mario, Mason, Mich, Raffi, Sally, Sergio, Xavier
-----------------------------------------------------------------------------------------------
</code>```

Here is my code:

```<code>public class luis_ramirez_game_scores {

    public static void main(String[] args) {
        String connectionString = "********/game_scores?serverTimezone=UTC";
            String dbLogin = "*****";
            String dbPassword = "******";
            Connection conn = null;
            System.out.println("-----------------------------------------------------------------------------------------------------");
            System.out.println("List of Gamers:");
            System.out.println("-----------------------------------------------------------------------------------------------------");
         // The sql variable has been added to store the SQL statement
            // that we will send to MySQL. This SQL statement asks MySQL
            // for all first names from the gamers table. By default, it
            // will return them in the order in which they are stored in
            // the table (not ordered, in other words).
            String sql = "SELECT first_name FROM gamers ORDER BY first_name";
            // Here are a couple of variations you can try that sorts
            // our list of names ascending and descending
            //String sql = "SELECT first_name FROM gamers ORDER BY first_name";
            //String sql = "SELECT first_name FROM gamers ORDER BY first_name DESC";
            try
            {
              conn = DriverManager.getConnection(connectionString, dbLogin, dbPassword);
              if (conn != null)
              {
                // This nested try-catch structure was added which uses two
                // interfaces from the java.sql package: Statement, which
                // creates a statement object and a ResultSet object which
                // contains the results of the sql statement declared above,
                // and is executed in MySQL using the executeQuery method.
                try (Statement stmt = conn.createStatement(
                ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
                ResultSet rs = stmt.executeQuery(sql))
                {
                  // If the try is successful, then we should have a
                  // result set (rs) and we can use a while look to
                  // loop through the result set and print the
                  // first names of the gamers. The next() method of
                  // the rs object will return each row in the result
                  // set until there are no more rows left.
                  while (rs.next())
                  {
                    System.out.print(rs.getString("first_name"));
                    if (rs.next()) {
                    System.out.print(", ");
                  }
                }
                }
                // If the try fails then the catch will run, which in
                // this example it captures any exceptions thrown by
                // SQL and prints those exceptions.
                catch (SQLException ex)
                {
                  System.out.println(ex.getMessage());
                }
                System.out.println("-----------------------------------------------------------------------------------------------------");
              }
            }
            catch (Exception e)
            {
            System.out.println("Database connection failed.");
            e.printStackTrace();
            }

          }
}
</code>```

I have added break; below System.out.print(", "); but the output results the same. Any insight you can provide would be greatly appreciated.

Body:
I am in need of exiting my while loop, I have attempted using break; however, my next output does not align correctly. Here is my current output (without break;):

List of Gamers:
-----------------------------------------------------------------------------------------------------
Adelie, Carden, Cora, Lada, Mario, Mich, Sally, Xavier-----------------------------------------------------------------------------------------------------

The desired output should be:

List of Gamers:
-----------------------------------------------------------------------------------------------
Adelie, Bob, Carden, Chang, Cora, Jonas, Lada, Lev, Mario, Mason, Mich, Raffi, Sally, Sergio, Xavier
-----------------------------------------------------------------------------------------------

Here is my code:

public class luis_ramirez_game_scores {

    public static void main(String[] args) {
        String connectionString = "********/game_scores?serverTimezone=UTC";
            String dbLogin = "*****";
            String dbPassword = "******";
            Connection conn = null;
            System.out.println("-----------------------------------------------------------------------------------------------------");
            System.out.println("List of Gamers:");
            System.out.println("-----------------------------------------------------------------------------------------------------");
         // The sql variable has been added to store the SQL statement
            // that we will send to MySQL. This SQL statement asks MySQL
            // for all first names from the gamers table. By default, it
            // will return them in the order in which they are stored in
            // the table (not ordered, in other words).
            String sql = "SELECT first_name FROM gamers ORDER BY first_name";
            // Here are a couple of variations you can try that sorts
            // our list of names ascending and descending
            //String sql = "SELECT first_name FROM gamers ORDER BY first_name";
            //String sql = "SELECT first_name FROM gamers ORDER BY first_name DESC";
            try
            {
              conn = DriverManager.getConnection(connectionString, dbLogin, dbPassword);
              if (conn != null)
              {
                // This nested try-catch structure was added which uses two
                // interfaces from the java.sql package: Statement, which
                // creates a statement object and a ResultSet object which
                // contains the results of the sql statement declared above,
                // and is executed in MySQL using the executeQuery method.
                try (Statement stmt = conn.createStatement(
                ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
                ResultSet rs = stmt.executeQuery(sql))
                {
                  // If the try is successful, then we should have a
                  // result set (rs) and we can use a while look to
                  // loop through the result set and print the
                  // first names of the gamers. The next() method of
                  // the rs object will return each row in the result
                  // set until there are no more rows left.
                  while (rs.next())
                  {
                    System.out.print(rs.getString("first_name"));
                    if (rs.next()) {
                    System.out.print(", ");
                  }
                }
                }
                // If the try fails then the catch will run, which in
                // this example it captures any exceptions thrown by
                // SQL and prints those exceptions.
                catch (SQLException ex)
                {
                  System.out.println(ex.getMessage());
                }
                System.out.println("-----------------------------------------------------------------------------------------------------");
              }
            }
            catch (Exception e)
            {
            System.out.println("Database connection failed.");
            e.printStackTrace();
            }

          }
}

I have added break; below System.out.print(", "); but the output results the same. Any insight you can provide would be greatly appreciated.

Body:
To print dashed line on a new line, just insert \n (new line character) here:

System.out.println("\n-----------------------------------------------------------------------------------------------------");


问:
Run a script to parse YAML when React app compiles

My Problem

I have a ReactJS website that parses a JSON file (stored in the src folder) to render content. I recently attempted to use a YAML file instead because of YAML's richer abilities (supporting Markdown, for example).

Because React must load and parse YAML asynchronously, this change complicated my codebase and degraded my app's performance (e.g., content flickers).

My Plan

Instead of rewriting my components and slowing down my app, I've written a script to convert my YAML file into a JSON file. This way, I can have the best of both worlds: the richer abilities of YAML and the simple implementation of JSON.

My Question

What's the best way to make React run this script when the app is built? My web host rebuilds my app every time I push a change, so hopefully this can be activated via package.json or similar.

答: Try creating an empty object that will store the converted data from the YAML, and use an if statement to check if the former object length is >0 then render what you want from the data (and if not, render a placeholder)</p>


问:
how to set the input text in react by taking it from from the url?
I am trying to input a location as text input
I want qr code to show the blow and location is the dynamic input we put in the input field
https://google.com?location={location} ?

How can i set the url as above and put the location as input? showup in qr code

so input will be the location from the url which can be any location and the qr code should show <url/
currently i am using the below code but i can only get the input field showup in the qr code .

```<code>import React, { useState } from 'react';
import QRCode from 'qrcode.react';

function App() {

  const [inputText, setInputText] = useState('');
  const [qrCodeText, setQRCodeText] = useState('');

  // generate QR code
  const generateQRCode = () => {
    setQRCodeText(inputText);
  }

  return (
    <div className="App">
      <h3>Generate and download a QR code image in React Omneo</h3>
      <div className="qr-input">
        <input
          type="text"
          placeholder="Enter input"
          value={inputText}
          onChange={e => setInputText(e.target.value)}
        />
        <input
          type="button"
          value="Generate"
          onClick={generateQRCode}
        />
      </div>
      <QRCode
        id="qrCodeEl"
        size={150}
        value={qrCodeText}
      />

    </div>
  );
}

export default App;
</code>```

答:
If the URL only has one parameter (location) you can split and get the rest. If there are more parameters you can split by '&' then location

useEffect(() => {
    setInputText(window.location.href.split("location=")[1]);
}, [])```

Body:
I am trying to input a location as text input
I want qr code to show the blow and location is the dynamic input we put in the input field
https://google.com?location={location} ?

How can i set the url as above and put the location as input? showup in qr code

so input will be the location from the url which can be any location and the qr code should show <url/
currently i am using the below code but i can only get the input field showup in the qr code .

import React, { useState } from 'react';
import QRCode from 'qrcode.react';

function App() {

  const [inputText, setInputText] = useState('');
  const [qrCodeText, setQRCodeText] = useState('');

  // generate QR code
  const generateQRCode = () => {
    setQRCodeText(inputText);
  }

  return (

Generate and download a QR code image in React Omneo

        <input
          type="text"
          placeholder="Enter input"
          value={inputText}
          onChange={e => setInputText(e.target.value)}
        />
        <input
          type="button"
          value="Generate"
          onClick={generateQRCode}
        />

      <QRCode
        id="qrCodeEl"
        size={150}
        value={qrCodeText}
      />

  );
}

export default App;


问:
Is it advisable to write a test case for every class in your program?
Im am just getting introduced to unit testing and test driven development. Thus far, I have only used Junit as testing framework. A question which emerged and for which I have not yet found a definite answer is: how much test cases do I need to write? Do I have to write a test case for every single class in my program? Or is this a stupid question because unit testing implies testing at the lowest (i.e. class) level?

I think writing a test case for every class is probably the more safe way to go (after all the more you test the lower the number of unforeseen bugs). But I was wondering if there are any widely agreed upon strategies regarding the amount of test cases to write?

答:
I'm not strict as other commenters about writing the test fist and code afterwards. You should do that, but not many people actually do that. The important thing is to write tests ideally before writing code, or right after you wrote the code. But not days/weeks/months/years after that, because you wouldn't do it and the test would suck.

I usually divide application to several parts: application logic, business logic, data access layer, domain objects and helper classes. It is most important to test completely business logic and helper classes. Other parts of application are less important, but you can test some parts. Also do some integration tests.

The most important thing is not to overthink it. Just try to do it on some small project and you will see by yourself.


问:
Exit from gridview.builder iteration in flutter or remove empty space
I am trying to implement a vision board. I'm using gridview.builder for adding up to 12 images. Almost everything works as I expect: adding up to 12 images, but when the limit is reached, somehow I want to stop the iteration, because I am not able to return null, and any widget I return, it will create additional space I don't want.

```<code> GridView.builder(
                clipBehavior: Clip.none,
                physics: ScrollPhysics(),
                shrinkWrap: true,
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent: SizeConfig.screenWidth!/3,
                    crossAxisSpacing: 0,
                    mainAxisSpacing: 0),
                itemCount: visions.length+1,
                itemBuilder: (BuildContext ctx, index) {
                  print("__________");
                  print("AM INTRAT IN ITEM BUILDER");
                  print("INDEX $index");
                  print(visions.length);
                  if (index < visions.length) {
                    print("PHOTO ALREADY ADDED CONTAINER");
                    return Stack(
                      alignment: Alignment.center,
                      children: [
                        Container(
                          width: double.infinity,
                          height: double.infinity,
                        ),
                        Container(
                          width: SizeConfig.screenWidth!/4,
                          height: SizeConfig.screenWidth!/4,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: FileImage(File(visions[index])),
                                fit: BoxFit.cover),
                            borderRadius: const BorderRadius.all(
                                Radius.circular(
                                    5.0) //                 <--- border radius here
                            ),
                          ),
                        ),
                        Positioned(
                          top:0,
                          right:0,
                          child: Container(
                            child: ClipOval(
                              child: InkWell(
                                onTap: () {
                                  _removeVisions(index);
                                },
                                child: Container(
                                  padding: const EdgeInsets.all(5),
                                  color: Colors.white,
                                  child:
                                    const Icon(
                                        Icons.delete,
                                        size: 16,
                                        color: Color(0xff221F1E)),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                      clipBehavior: Clip.none,
                    );
                  }
                  else if(index<12){
                    print("ADAUGA POZA");
                    print("INDEX $index");
                    print(visions.length);
                    return InkWell(
                      onTap: () {
                        _openGallery(context);
                      },
                      child:
                      Stack(
                        alignment: Alignment.center,
                        children:[
                          Container(
                          width: SizeConfig.screenWidth!/4,
                            height: SizeConfig.screenWidth!/4,
                            decoration:
                            BoxDecoration(
                              border: Border.all(color: const Color(0xff221F1E)),
                              borderRadius: const BorderRadius.all(Radius.circular(5.0)),
                            ),
                            child:
                              const Icon(
                                Icons.add,
                                size: 22,
                                color: Color(0xff221F1E),
                              )
                        ),
                        ],
                      ),
                    );
                  }
                  else {
                    return  Container(color: Colors.red);
                  }
                }
            ),
</code>```

I want to remove that red container.
I have also tried to hardcode something with Positioned widget, but nothing worked, so I am trying somehow to exit when index is equal to 12 or any other solution...

答:
I would try a true/false statement like this for your itemcount:</p>
```<code>itemCount: (visions.length == 12) ? visions.length : visions.length + 1,
</code>```

Body:
I am trying to implement a vision board. I'm using gridview.builder for adding up to 12 images. Almost everything works as I expect: adding up to 12 images, but when the limit is reached, somehow I want to stop the iteration, because I am not able to return null, and any widget I return, it will create additional space I don't want.

 GridView.builder(
                clipBehavior: Clip.none,
                physics: ScrollPhysics(),
                shrinkWrap: true,
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent: SizeConfig.screenWidth!/3,
                    crossAxisSpacing: 0,
                    mainAxisSpacing: 0),
                itemCount: visions.length+1,
                itemBuilder: (BuildContext ctx, index) {
                  print("__________");
                  print("AM INTRAT IN ITEM BUILDER");
                  print("INDEX $index");
                  print(visions.length);
                  if (index < visions.length) {
                    print("PHOTO ALREADY ADDED CONTAINER");
                    return Stack(
                      alignment: Alignment.center,
                      children: [
                        Container(
                          width: double.infinity,
                          height: double.infinity,
                        ),
                        Container(
                          width: SizeConfig.screenWidth!/4,
                          height: SizeConfig.screenWidth!/4,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: FileImage(File(visions[index])),
                                fit: BoxFit.cover),
                            borderRadius: const BorderRadius.all(
                                Radius.circular(
                                    5.0) //                 <--- border radius here
                            ),
                          ),
                        ),
                        Positioned(
                          top:0,
                          right:0,
                          child: Container(
                            child: ClipOval(
                              child: InkWell(
                                onTap: () {
                                  _removeVisions(index);
                                },
                                child: Container(
                                  padding: const EdgeInsets.all(5),
                                  color: Colors.white,
                                  child:
                                    const Icon(
                                        Icons.delete,
                                        size: 16,
                                        color: Color(0xff221F1E)),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                      clipBehavior: Clip.none,
                    );
                  }
                  else if(index<12){
                    print("ADAUGA POZA");
                    print("INDEX $index");
                    print(visions.length);
                    return InkWell(
                      onTap: () {
                        _openGallery(context);
                      },
                      child:
                      Stack(
                        alignment: Alignment.center,
                        children:[
                          Container(
                          width: SizeConfig.screenWidth!/4,
                            height: SizeConfig.screenWidth!/4,
                            decoration:
                            BoxDecoration(
                              border: Border.all(color: const Color(0xff221F1E)),
                              borderRadius: const BorderRadius.all(Radius.circular(5.0)),
                            ),
                            child:
                              const Icon(
                                Icons.add,
                                size: 22,
                                color: Color(0xff221F1E),
                              )
                        ),
                        ],
                      ),
                    );
                  }
                  else {
                    return  Container(color: Colors.red);
                  }
                }
            ),

I want to remove that red container.
I have also tried to hardcode something with Positioned widget, but nothing worked, so I am trying somehow to exit when index is equal to 12 or any other solution...

Body:
I would try a true/false statement like this for your itemcount:

itemCount: (visions.length == 12) ? visions.length : visions.length + 1,


问:
Django queryset - Add HAVING constraint after annotate(F())
I had a seemingly normal situation with adding HAVING to the query.
I read here and here, but it did not help me

I need add HAVING to my query

MODELS :

```<code>class Package(models.Model):
    status = models.IntegerField()

class Product(models.Model):
    title = models.CharField(max_length=10)
    packages = models.ManyToManyField(Package)
</code>```

Products:

```<code>|id|title|
| - | - |
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
</code>```

Packages:

```<code>|id|status|
| - | - |
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
| 4 | 2 |
</code>```

Product_Packages:

```<code>|product_id|package_id|
| - | - |
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
| 3 | 2 |
| 2 | 3 |
| 4 | 3 |
| 4 | 4 |
</code>```

visual

pack_1 (A, B) status OK

pack_2 (B, C) status not ok

pack_3 (B, D) status OK

pack_4 (D) status not ok

My task is to select those products that have the latest package in status = 1

Expected result is :  A, B

my query is like this

```<code>SELECT prod.title, max(tp.id)
FROM "product" as prod
INNER JOIN "product_packages" as p_p ON (p.id = p_p.product_id)
INNER JOIN "package" as pack ON (pack.id = p_p.package_id)
GROUP BY prod.title
HAVING pack.status = 1
</code>```

it returns exactly what I needed

```<code>|title|max(pack.id)|
| - | - |
| A | 1 |
| B | 3 |
</code>```

BUT my orm does not work correctly
I try like this

```<code>p = Product.objects.values('id').annotate(pack_id = Max('packages')).annotate(my_status = F('packages__status')).filter(my_status=1).values('id', 'pack_id')
</code>```

p.query

SELECT "product"."id", MAX("product_packages"."package_id") AS "pack_id"

FROM "product" LEFT OUTER JOIN "product_packages" ON ("product"."id" = "product_packages"."product_id") LEFT OUTER JOIN "package" ON ("product_packages"."package_id" = "package"."id")

WHERE "package"."status" = 1

GROUP BY "product"."id"

please help me to make correct ORM

答:
Haki Benita has an excellent site that is made for Database Gurus and how to make to most of Django.

You can take a look at this post:
https://hakibenita.com/django-group-by-sql#how-to-use-having

Django has a very specific way of adding the "HAVING" operator, i.e. your query set needs to be structured so that your annotation is followed by a 'values' call to single out the column you want to group by, then annotate the Max or whatever aggregate you want.

Also this annotation seems like it won't work annotate(my_status = F('packages__status') you want to annotate multiple status to a single annotation.

You might want to try a subquery to annotate the way you want.

e.g.

Product.objects.annotate(
    latest_pack_id=Subquery(
        Package.objects.order_by('-pk').filter(status=1).values('pk')[:1]
    )
).filter(
    packages__in=F('latest_pack_id')
)
```

Or something along those lines, I haven't tested this out

Body:
I had a seemingly normal situation with adding HAVING to the query.
I read here and here, but it did not help me

I need add HAVING to my query

MODELS :

class Package(models.Model):
    status = models.IntegerField()

class Product(models.Model):
    title = models.CharField(max_length=10)
    packages = models.ManyToManyField(Package)

Products:

|id|title|
| - | - |
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |

Packages:

|id|status|
| - | - |
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
| 4 | 2 |

Product_Packages:

|product_id|package_id|
| - | - |
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
| 3 | 2 |
| 2 | 3 |
| 4 | 3 |
| 4 | 4 |

visual

pack_1 (A, B) status OK

pack_2 (B, C) status not ok

pack_3 (B, D) status OK

pack_4 (D) status not ok

My task is to select those products that have the latest package in status = 1

Expected result is :  A, B

my query is like this

SELECT prod.title, max(tp.id)
FROM "product" as prod
INNER JOIN "product_packages" as p_p ON (p.id = p_p.product_id)
INNER JOIN "package" as pack ON (pack.id = p_p.package_id)
GROUP BY prod.title
HAVING pack.status = 1

it returns exactly what I needed

|title|max(pack.id)|
| - | - |
| A | 1 |
| B | 3 |

BUT my orm does not work correctly
I try like this

p = Product.objects.values('id').annotate(pack_id = Max('packages')).annotate(my_status = F('packages__status')).filter(my_status=1).values('id', 'pack_id')

p.query

SELECT "product"."id", MAX("product_packages"."package_id") AS "pack_id"

FROM "product" LEFT OUTER JOIN "product_packages" ON ("product"."id" = "product_packages"."product_id") LEFT OUTER JOIN "package" ON ("product_packages"."package_id" = "package"."id")

WHERE "package"."status" = 1

GROUP BY "product"."id"

please help me to make correct ORM

Body:
Haki Benita has an excellent site that is made for Database Gurus and how to make to most of Django.

You can take a look at this post:
https://hakibenita.com/django-group-by-sql#how-to-use-having

Django has a very specific way of adding the "HAVING" operator, i.e. your query set needs to be structured so that your annotation is followed by a 'values' call to single out the column you want to group by, then annotate the Max or whatever aggregate you want.

Also this annotation seems like it won't work annotate(my_status = F('packages__status') you want to annotate multiple status to a single annotation.

You might want to try a subquery to annotate the way you want.

e.g.

Product.objects.annotate(
    latest_pack_id=Subquery(
        Package.objects.order_by('-pk').filter(status=1).values('pk')[:1]
    )
).filter(
    packages__in=F('latest_pack_id')
)

Or something along those lines, I haven't tested this out


问:
Set values of list of Material UI Autocompletes that fetch options dynamically
I have a Material UI Autocomplete combo-box child component class that fetches results as the user types:

```<code>...
fetchIngredients(query) {
    this.sendAjax('/getOptions', {
      data: {
        q: query
      }
    }).then((options) => {
      this.setState({
        options: options
      });
    });
}
...
<Autocomplete
    options={this.state.options}
    value={this.state.value}
    onChange={(e, val) => {
       this.setState({value: val});
    }}
    onInputChange={(event, newInputValue) => {
      this.fetchIngredients(newInputValue);
    }}
    renderInput={(params) => {
      // Hidden input so that FormData can find the value of this input.
      return (<TextField {...params} label="Foo" required/>);
    }}
    // Required for search as you type implementations:
    // https://mui.com/components/autocomplete/#search-as-you-type
    filterOptions={(x) => x}
/>
...
</code>```

This child component is actually rendered as one of many in a list by its parent. Now, say I want the parent component to be able to set the value of each autocomplete programmatically (e.g., to auto-populate a form). How would I go about this?

I understand I could lift the value state up to the parent component and pass it as a prop, but what about the this.state.options? In order to set a default value of the combo-box, I'd actually need to also pass a single set of options such that value is valid. This would mean moving the ajax stuff up to the parent component so that it can pass options as a prop. This is starting to get really messy as now the parent has to manage multiple sets of ajax state for a list of its Autocomplete children.

Any good ideas here? What am I missing? Thanks in advance.

答:
If these are children components making up a form, then I would argue that hoisting the value state up to the parent component makes more sense, even if it does require work refactoring. This makes doing something with the filled-in values much easier and more organized.

Then in your parent component, you have something like this:

constructor(props) {
  super(props);
  this.state = {
    values: [],
    options: []
  };
}

const fetchIngredients = (query, id) => {
  this.sendAjax('/getOptions', {
    data: {
      q: query
    }
  }).then((options) => {
    this.setState(prevState => {
      ...prevState,
      [id]: options
    });
  });
}

const setValue = (newValue, id) => {
  this.setState(prevState => {
    ...prevState,
    [id]: newValue
  };
}

render() {
  return (
    <>
      ...
      {arrOfInputLabels.map((label, id) => (
        <ChildComponent
          id={id}
          key={id}
          value={this.state.values[id]}
          options={this.state.options[id]}
          fetchIngredients={fetchIngredients}
          labelName={label}
        />
      )}
      ...
    </>
```

Body:
I have a Material UI Autocomplete combo-box child component class that fetches results as the user types:

...
fetchIngredients(query) {
    this.sendAjax('/getOptions', {
      data: {
        q: query
      }
    }).then((options) => {
      this.setState({
        options: options
      });
    });
}
...
<Autocomplete
    options={this.state.options}
    value={this.state.value}
    onChange={(e, val) => {
       this.setState({value: val});
    }}
    onInputChange={(event, newInputValue) => {
      this.fetchIngredients(newInputValue);
    }}
    renderInput={(params) => {
      // Hidden input so that FormData can find the value of this input.
      return (<TextField {...params} label="Foo" required/>);
    }}
    // Required for search as you type implementations:
    // https://mui.com/components/autocomplete/#search-as-you-type
    filterOptions={(x) => x}
/>
...

This child component is actually rendered as one of many in a list by its parent. Now, say I want the parent component to be able to set the value of each autocomplete programmatically (e.g., to auto-populate a form). How would I go about this?

I understand I could lift the value state up to the parent component and pass it as a prop, but what about the this.state.options? In order to set a default value of the combo-box, I'd actually need to also pass a single set of options such that value is valid. This would mean moving the ajax stuff up to the parent component so that it can pass options as a prop. This is starting to get really messy as now the parent has to manage multiple sets of ajax state for a list of its Autocomplete children.

Any good ideas here? What am I missing? Thanks in advance.


问:
How do I add a class to a react element when it is clicked
I have this react component and I am trying to create a hamburger menu but, I don't know how to add a class when a button is clicked. I am new to React so please go easy on me. When I run the below code it doesn't work and throws an error in the Chrome dev tools.</p>
```<code>function Nav() {
const hamburger = document.getElementById('hamburger');
const navUL = document.getElementById('navul');
hamburger.addEventListener('click', () =>{
  navUL.classList.toggle('show');
});
  return (
<header>

  <h2>
    <a href="/">
      Travis Helms
    </a>
  </h2>
  <nav>
    <ul className="flex-row" id='navul'>
      <li className="mx-2">
        <a href="#about">
          About me
        </a>
      </li>
      <li>
        <span>Portfolio</span>
      </li>
      <li>
        <span>Contact</span>
      </li>
      <li>
        <span>Resume</span>
      </li>
    </ul>
  </nav>
  <button className="hamburger" id="hamburger">
    <FontAwesomeIcon icon={faBars}></FontAwesomeIcon>
    </button>
    </header>
  );
}
</code>```

答:
First of all, welcome to React! It's an amazing framework!

It would have been more helpful if you provided the error you are getting but from the code you shared I can see there are a few things you need to do differently.

Generally, you can use event listeners in React for certain things, and there is a certain way to add them properly, but for the most part they are not used very frequently. Instead, for example, to assign a click event to an element in React, all you need to do is pass it the onClick attribute with the function you want it to execute when it is clicked, for example <button onClick={doSomething}>click me</button>.

An easy way to control the state of your component is by using the useState hook and toggle the class of an element using state. In your case, it could look like this:

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

const Nav = () => {
    const [isOpen, setIsOpen] = useState(false);

    return (
        <header>
            <h2>
                <a href="/">Travis Helms</a>
            </h2>
            <nav>
                <ul className={"flex-row " + (isOpen ? "show" : "")}>
                    <li className="mx-2">
                        <a href="#about">About me</a>
                    </li>
                    <li>
                        <span>Portfolio</span>
                    </li>
                    <li>
                        <span>Contact</span>
                    </li>
                    <li>
                        <span>Resume</span>
                    </li>
                </ul>
            </nav>
            <button
                className="hamburger"
                onClick={() => setIsOpen(!isOpen)}
            >
                <FontAwesomeIcon icon={faBars}></FontAwesomeIcon>
            </button>
        </header>
    );
};
</code>```

It looks like you are in a very early stage of learning React and for you to be successful coding with React you need to cover a few basics like state management, props, children and a few more things. I would recommend going on YouTube and find a good introduction video to React and code along to it! There are a lot of great resources in there for people who are just starting with React, just make sure it's something fairly recent (I'd say 2020 onwards).

Body:
I have this react component and I am trying to create a hamburger menu but, I don't know how to add a class when a button is clicked. I am new to React so please go easy on me. When I run the below code it doesn't work and throws an error in the Chrome dev tools.

function Nav() {
const hamburger = document.getElementById('hamburger');
const navUL = document.getElementById('navul');
hamburger.addEventListener('click', () =>{
  navUL.classList.toggle('show');
});
  return (

      Travis Helms

          About me

        Portfolio

        Contact

        Resume

  <button className="hamburger" id="hamburger">
    <FontAwesomeIcon icon={faBars}></FontAwesomeIcon>
    </button>

  );
}

Body:
First of all, welcome to React! It's an amazing framework!

It would have been more helpful if you provided the error you are getting but from the code you shared I can see there are a few things you need to do differently.

Generally, you can use event listeners in React for certain things, and there is a certain way to add them properly, but for the most part they are not used very frequently. Instead, for example, to assign a click event to an element in React, all you need to do is pass it the onClick attribute with the function you want it to execute when it is clicked, for example <button onClick={doSomething}>click me</button>.

An easy way to control the state of your component is by using the useState hook and toggle the class of an element using state. In your case, it could look like this:

import React, { useState } from 'react';

const Nav = () => {
    const [isOpen, setIsOpen] = useState(false);

    return (
        <header>
            <h2>
                <a href="/">Travis Helms</a>
            </h2>
            <nav>
                <ul className={"flex-row " + (isOpen ? "show" : "")}>
                    <li className="mx-2">
                        <a href="#about">About me</a>
                    </li>
                    <li>
                        <span>Portfolio</span>
                    </li>
                    <li>
                        <span>Contact</span>
                    </li>
                    <li>
                        <span>Resume</span>
                    </li>
                </ul>
            </nav>
            <button
                className="hamburger"
                onClick={() => setIsOpen(!isOpen)}
            >
                <FontAwesomeIcon icon={faBars}></FontAwesomeIcon>
            </button>
        </header>
    );
};

It looks like you are in a very early stage of learning React and for you to be successful coding with React you need to cover a few basics like state management, props, children and a few more things. I would recommend going on YouTube and find a good introduction video to React and code along to it! There are a lot of great resources in there for people who are just starting with React, just make sure it's something fairly recent (I'd say 2020 onwards).


问:
How to remove only one of repeated chars in string using JavaScript
I have a string with repeated chars like : 'CANADA'.

And I am trying to get the string which removed only one of repeated chars :

'CNADA', 'CANDA', 'CANAD'.

I've tried it with subString, but it returned the part of string removed.
Also I've tried it with reduce, but it ended up removing all the repeated chars ('CND').

What is the way of removing only one char at time?
The results can be stored in array. (results = ['CNADA', 'CANDA', 'CANAD'])

Thank you.

答:
You could use some Array magic to remove duplicate characters:

function removeDuplicateCharacters(value) {

    // convert string to array and loop through each character
    return String(value).split('').filter(function(char, index, all) {

        // return false if char found at a different index
        return (index === all.indexOf(char));
    })
    .join(''); // convert back to a string
}
```
<pre class="lang-js prettyprint-override"><code>// returns `CAND`
removeDuplicateCharacters('CANADA');

// returns `helo wrd`
removeDuplicateCharacters('hello world');
</code>```

Body:
You could use some Array magic to remove duplicate characters:

function removeDuplicateCharacters(value) {

    // convert string to array and loop through each character
    return String(value).split('').filter(function(char, index, all) {

        // return false if char found at a different index
        return (index === all.indexOf(char));
    })
    .join(''); // convert back to a string
}

// returns `CAND`
removeDuplicateCharacters('CANADA');

// returns `helo wrd`
removeDuplicateCharacters('hello world');


答:
FWIW, I'm not familiar with bcftools but if the intention is to pipe the bcftools output into awk then we could do the whole thing in awk ...

Assumptions:

none of the fields (in the file) contain white space

always going to pull data for columns #CHROM / POS / REF / ALT

these 4 columns are always going to be in the same fields/positions (#CHROM = $1 / POS = $2 / REF = $4 / ALT = $5)

DeNovo always shows up between a pair of colons (ie, we're looking for :DeNovo: in field $10)

the three test fields always show up in the same fields/positions (SAMPLE_1 = $10 / SAMPLE_2 = $11 / SAMPLE_3 = $12)

PASS always shows up between a pair of colons (ie, we're lookinf for :PASS: in fields $10 / $11 / $12)

One awk idea:

```<code>awk '
$10 ~ ":DeNovo:" &&
$10 ~ ":PASS:"   &&
$11 ~ ":PASS:"   &&
$12 ~ ":PASS:"      { print $1,$2,$4,$5 }
' file.vcf
</code>```

This generates:

```<code>chr1 61871 C CT
</code>```

NOTE: The obvious (?) downside to this approach is that we've hardcoded the column references; we could certainly modify the awk code to provide a more dynamic interface (replicate bcftools functionality?) but I'm not sure the added complexity is worth the effort, ymmv.

Assuming OP needs the functionality of bcftools (eg, designate a variable set of columns), one idea would be to modify the current bcftools call to include the SAMPLE_X columns and then pipe that output to awk; something like:

```<code>bcftools query -f '%CHROM %POS %REF %ALT %SAMPLE_1 %SAMPLE_2 %SAMPLE_3\n' file.vcf | awk '
$5 ~ ":DeNovo:" &&
$5 ~ ":PASS:"   &&
$6 ~ ":PASS:"   &&
$7 ~ ":PASS:"      { print $1,$2,$3,$4 }'
</code>```

NOTES:

further improvements would include parameterizing the DeNovo and PASS strings

going back to the idea of eliminating bcftools and doing the whole thing in awk ... would likely need two column lists (columns to display, columns to test) along with a list of the string(s) to compare each of the 'test' columns against ... doable but now we're getting into a fairly substantial coding effort (vs what we've done so far)

Title: Extract variant positions from VCF dependent on contents of other columns

Body:
I have a vcf file, I am trying to extract the information from these columns:

#CHROM  POS   REF     ALT

However I would like to extract these only if the SAMPLE-1 column contains the string DeNovo (Not DeNovoSV) and that SAMPLE-1, SAMPLE-2, and SAMPLE-3 all contain PASS.

#CHROM  POS     ID      REF     ALT     QUAL    FILTER  INFO    FORMAT  SAMPLE-1  SAMPLE-2  SAMPLE-3
chr1    10230   .       AC      A       186.90  .       AC=4;AF=0.667;AN=6;DP=77;FS=0.000;MQ=26.38;MQRankSum=0.436;QD=3.89;ReadPosRankSum=0.000;SOR=1.162       GT:AD:AF:DP:GQ:FT:F1R2:F2R1:PL:GP:PP
:DN 0/1:6,12:0.667:18:32:PASS:2,3:4,9:69,0,30:3.9669e+01,2.7888e-03,3.2724e+01:295,0,215:Inherited  0/1:5,15:0.750:20:11:PASS:3,6:2,9:60,0,8:3.0340e+01,3.6694e-01,1.0964e+01:172,0,137:.   1/1:0,10
:1.000:10:26:PASS:0,2:0,8:93,29,0:6.1212e+01,2.6342e+01,1.0101e-02:378,0,183:.
chr1    61871   .       C       CT      60.27   .       AC=3;AF=0.500;AN=6;DP=29;FS=11.290;MQ=33.00;MQRankSum=-0.423;QD=2.51;ReadPosRankSum=0.705;SOR=0.478     GT:AD:AF:DP:GQ:FT:F1R2:F2R1:PL:GP:PP:DPL:DN:DQ  0/0:5,0:0.000:5:15:PASS:.:.:0,15,182:.:0,7,93:0,15,100:DeNovo:2.9227e-07        1/1:0,2:1.000:2:5:PASS:0,1:0,1:42,6,0:2.4787e+01,4.7870e+00,1.7754e+00:29,0,9:40,6,0:.  0/1:15,7:0.318:22:26:PASS:6,3:9,4:43,0,41:2.6538e+01,9.8206e-03,4.4010e+01:65,0,250:74,0,234:.
chr1    66369   .       TA      T       116.77  .       AC=2;AF=0.500;AN=4;DP=56;FS=10.138;MQ=173.59;MQRankSum=1.468;QD=4.32;ReadPosRankSum=0.929;SOR=0.367     GT:AD:AF:DP:GQ:FT:F1R2:F2R1:PL:GP:PP    ./.:11,5:0.312:16:0:LowGQ:.:.   0/1:8,4:0.333:12:40:PASS:3,2:5,2:71,0,43:4.1762e+01,4.0824e-04,4.5625e+01:71,0,43       0/1:8,7:0.467:15:45:PASS:4,4:4,3:77,0,47:4.7400e+01,1.2244e-04,5.0000e+01:77,0,47
chr1    934273  .       G       C       8.67    .       AC=1;AF=0.167;AN=6;DP=26;FS=0.000;MQ=19.17;MQRankSum=-1.179;QD=0.96;ReadPosRankSum=1.666;SOR=0.223      GT:AD:AF:DP:GQ:FT:F1R2:F2R1:PL:GP:PP
:DPL:DN:DQ  0/1:7,2:0.222:9:11:PASS:5,1:2,1:45,0,32:1.0868e+01,3.7242e-01,3.5372e+01:45,0,60:45,0,32:DeNovoSV:4.3945e-09    0/0:6,3:0.333:9:0:LowGQ:.:.:0,0,140:.:55,0,191:46,0,186:.       0/0:8,0:
0.000:8:23:PASS:.:.:0,23,190:.:0,25,195:0,23,190:.
chr1    934274  .       G       C       8.68    .       AC=1;AF=0.167;AN=6;DP=26;FS=0.000;MQ=19.17;MQRankSum=-1.179;QD=0.96;ReadPosRankSum=1.666;SOR=0.223      GT:AD:AF:DP:GQ:FT:F1R2:F2R1:PL:GP:PP
:DPL:DN:DQ  0/1:7,2:0.222:9:11:PASS:5,1:2,1:45,0,32:1.0868e+01,3.7242e-01,3.5372e+01:45,0,60:45,0,32:DeNovoSV:4.3945e-09    0/0:6,3:0.333:9:0:PASS:.:.:0,0,140:.:55,0,191:46,0,186:.       0/0:8,0:
0.000:8:23:PASS:.:.:0,23,190:.:0,25,195:0,23,190:.

I have tried using bcftools, see below.

bcftools query -f '%CHROM %POS %REF %ALT\n' file.vcf | head -3
chr1 10230 AC A
chr1 61871 C CT
chr1 66369 TA T

Is there a way to use bcftools, or combine it with awk in order to get the output I am looking for in the vcf file format?

Many thanks

Body:
FWIW, I'm not familiar with bcftools but if the intention is to pipe the bcftools output into awk then we could do the whole thing in awk ...

Assumptions:

none of the fields (in the file) contain white space

always going to pull data for columns #CHROM / POS / REF / ALT

these 4 columns are always going to be in the same fields/positions (#CHROM = $1 / POS = $2 / REF = $4 / ALT = $5)

DeNovo always shows up between a pair of colons (ie, we're looking for :DeNovo: in field $10)

the three test fields always show up in the same fields/positions (SAMPLE_1 = $10 / SAMPLE_2 = $11 / SAMPLE_3 = $12)

PASS always shows up between a pair of colons (ie, we're lookinf for :PASS: in fields $10 / $11 / $12)

One awk idea:

awk '
$10 ~ ":DeNovo:" &&
$10 ~ ":PASS:"   &&
$11 ~ ":PASS:"   &&
$12 ~ ":PASS:"      { print $1,$2,$4,$5 }
' file.vcf

This generates:

chr1 61871 C CT

NOTE: The obvious (?) downside to this approach is that we've hardcoded the column references; we could certainly modify the awk code to provide a more dynamic interface (replicate bcftools functionality?) but I'm not sure the added complexity is worth the effort, ymmv.

Assuming OP needs the functionality of bcftools (eg, designate a variable set of columns), one idea would be to modify the current bcftools call to include the SAMPLE_X columns and then pipe that output to awk; something like:

bcftools query -f '%CHROM %POS %REF %ALT %SAMPLE_1 %SAMPLE_2 %SAMPLE_3\n' file.vcf | awk '
$5 ~ ":DeNovo:" &&
$5 ~ ":PASS:"   &&
$6 ~ ":PASS:"   &&
$7 ~ ":PASS:"      { print $1,$2,$3,$4 }'

NOTES:

further improvements would include parameterizing the DeNovo and PASS strings

going back to the idea of eliminating bcftools and doing the whole thing in awk ... would likely need two column lists (columns to display, columns to test) along with a list of the string(s) to compare each of the 'test' columns against ... doable but now we're getting into a fairly substantial coding effort (vs what we've done so far)


问:
How to retrieve the triggered record information in CloudPage Marketing Cloud
I would like to have "Add to Calendar" in the Email. My idea is to write the code to Javascript to generate file.ICS in CloudPage and link it with the button. When the Email receiver clicks on the button, the file.ICS will be downloaded.

I have a Journey Builder which is triggered from Sales Cloud. I have a CloudPage and I would like to retrieve the information of the "Date field" from the triggered record. I quite have no idea how to write the code to retrieve the "Date field" information in CloudPage. Below is the code that I have

```<code>    %%[
VAR @sid, @jid, @reason, @lue, @lue_prop, @lue_statusCode, @overallStatus, @requestId, @Response, @Status, @Error, @curEmail

SET @sid = AttributeValue("_subscriberkey")
SET @jid = AttributeValue("jobid")
SET @listid = AttributeValue("listid")
SET @batchid = AttributeValue("_jobsubscriberbatchid")
SET @reason = "One Click Unsubscribe"

VAR @subscriberRows,@result

SET @subscriberRows = RetrieveSalesforceObjects(
   "Contact",
   "AccountId, Email",
   "Id", "=", @sid )

if RowCount(@subscriberRows) == 1 then
  VAR @subscriberRow, @AccountId
  SET @subscriberRow = Row(@subscriberRows, 1)
  SET @AccountId = Field(@subscriberRow, "AccountId")
  SET @curEmail = Field(@subscriberRow, "Email")
endif

]%%
</code>```

答:
I would recommend using a parameter on the url. You can construct a url to use in your button using the CloudPagesUrl() function. It would look something like the below. You can continue to add params as you wish.

```<code>%%[
set @url  = CloudPagesUrl([YOURCLOUDPAGEID],'ParamNameToPass',@ParamValueToPass)
/* if needed */
set @url = URLEncode(@url)
]%%
</code>```

NOTE: sometimes you will need to use URLEncode() so that the date is properly formatted in your url string. I usually would do that in the

and in the email, wrap the link in a RedirectTo():

```<code><a href="%%=@RedirectTo(@url)=%%">
</code>```

and in the CloudPage (assuming it works like a microsite - please verify) use the RequestParameter() function and ask for the string value you used as the 'ParamNameToPass'

```<code>set @cloudPageVar = RequestParameter('ParamNameToPass')
</code>```

Lastly, I highly recommend the function guide page on the dev site - it really helped me understand what was possible in AmpScript.

Body:
I would like to have "Add to Calendar" in the Email. My idea is to write the code to Javascript to generate file.ICS in CloudPage and link it with the button. When the Email receiver clicks on the button, the file.ICS will be downloaded.

I have a Journey Builder which is triggered from Sales Cloud. I have a CloudPage and I would like to retrieve the information of the "Date field" from the triggered record. I quite have no idea how to write the code to retrieve the "Date field" information in CloudPage. Below is the code that I have

    %%[
VAR @sid, @jid, @reason, @lue, @lue_prop, @lue_statusCode, @overallStatus, @requestId, @Response, @Status, @Error, @curEmail

SET @sid = AttributeValue("_subscriberkey")
SET @jid = AttributeValue("jobid")
SET @listid = AttributeValue("listid")
SET @batchid = AttributeValue("_jobsubscriberbatchid")
SET @reason = "One Click Unsubscribe"

VAR @subscriberRows,@result

SET @subscriberRows = RetrieveSalesforceObjects(
   "Contact",
   "AccountId, Email",
   "Id", "=", @sid )

if RowCount(@subscriberRows) == 1 then
  VAR @subscriberRow, @AccountId
  SET @subscriberRow = Row(@subscriberRows, 1)
  SET @AccountId = Field(@subscriberRow, "AccountId")
  SET @curEmail = Field(@subscriberRow, "Email")
endif

]%%

Body:
I would recommend using a parameter on the url. You can construct a url to use in your button using the CloudPagesUrl() function. It would look something like the below. You can continue to add params as you wish.

%%[
set @url  = CloudPagesUrl([YOURCLOUDPAGEID],'ParamNameToPass',@ParamValueToPass)
/* if needed */
set @url = URLEncode(@url)
]%%

NOTE: sometimes you will need to use URLEncode() so that the date is properly formatted in your url string. I usually would do that in the

and in the email, wrap the link in a RedirectTo():

<a href="%%=@RedirectTo(@url)=%%">

and in the CloudPage (assuming it works like a microsite - please verify) use the RequestParameter() function and ask for the string value you used as the 'ParamNameToPass'

set @cloudPageVar = RequestParameter('ParamNameToPass')

Lastly, I highly recommend the function guide page on the dev site - it really helped me understand what was possible in AmpScript.


问:
In dart, split string into two parts using length of first string
I have a string hiWorld and
i want to split this string in two parts hi and World by length of first word hi which is of length 2.

This is what i want to do

List<String> list = ("hiWorld").splitFromLength(2);

```

答:
This is my solution which is more generic:

```<code>List<String> splitByLength(String value, int length) {
  List<String> pieces = [];

  for (int i = 0; i < value.length; i += length) {
    int offset = i + length;
    pieces.add(value.substring(i, offset >= value.length ? value.length : offset));
  }
  return pieces;
}
</code>```

And the extension method:

```<code>extension on String {
  List<String> splitByLength(int length, {bool ignoreEmpty = false}) {
    List<String> pieces = [];

    for (int i = 0; i < this.length; i += length) {
      int offset = i + length;
      String piece = this.substring(i, offset >= this.length ? this.length : offset);

      if (ignoreEmpty) {
        piece = piece.replaceAll(RegExp(r'\s+'), '');
      }

      pieces.add(piece);
    }
    return pieces;
  }
}
</code>```

You can use it like:

```<code>'HELLO WORLD'.splitByLength(5, ignoreEmpty: true)
</code>```

Body:
This is my solution which is more generic:

List<String> splitByLength(String value, int length) {
  List<String> pieces = [];

  for (int i = 0; i < value.length; i += length) {
    int offset = i + length;
    pieces.add(value.substring(i, offset >= value.length ? value.length : offset));
  }
  return pieces;
}

And the extension method:

extension on String {
  List<String> splitByLength(int length, {bool ignoreEmpty = false}) {
    List<String> pieces = [];

    for (int i = 0; i < this.length; i += length) {
      int offset = i + length;
      String piece = this.substring(i, offset >= this.length ? this.length : offset);

      if (ignoreEmpty) {
        piece = piece.replaceAll(RegExp(r'\s+'), '');
      }

      pieces.add(piece);
    }
    return pieces;
  }
}

You can use it like:

'HELLO WORLD'.splitByLength(5, ignoreEmpty: true)


问:
How to get a Drawable that's a mirrored version of a different Drawable?

Background

I know it's possible to create a rotated version of a Drawable (or Bitmap), as such (written about it here) :

```<code>@JvmStatic
fun getRotateDrawable(d: Drawable, angle: Int): Drawable {
    if (angle % 360 == 0)
       return d
    return object : LayerDrawable(arrayOf(d)) {
        override fun draw(canvas: Canvas) {
            canvas.save()
            canvas.rotate(angle.toFloat(), (d.bounds.width() / 2).toFloat(), (d.bounds.height() / 2).toFloat())
            super.draw(canvas)
            canvas.restore()
        }
    }
}
</code>```

The problem

I wanted to have autoMirrored being set to some drawable (VectorDrawable in my case), which would flip (mirror so that left is right, and right is left, but not affect top and bottom) it in case the locale of the device is RTL.

As an example (and it's only an example!), if you take a drawable that shows a left-arrow, after flipping it will be a right-arrow.

Sadly, this is available only from API 19.

That's why I decided to make a new Drawable out of it, to be a flipped version of the original one

What I've tried

I've found a nice article of doing the same thing to a View, here, using a Matrix. So I've tried this:

```<code>    @JvmStatic
    fun getMirroredDrawable(d: Drawable): Drawable {
        return object : LayerDrawable(arrayOf(d)) {
            override fun draw(canvas: Canvas) {
                canvas.save()
                val matrix = Matrix()
                // use this for the other flipping: matrix.preScale(1.0f, -1.0f)
                matrix.preScale(-1.0f, 1.0f);
                canvas.matrix = matrix
                super.draw(canvas)
                canvas.restore()
            }
        }
    }
</code>```

Sadly, for some reason, this made the drawable not being shown at all. Maybe it does work, yet tries to get shown out of its bounds of whatever View that's showing it.

The question

How can I make a flipped version of a given Drawable, similar to what I did for rotating a Drawable?

Solution:

Based on the answer suggested below (here), here's a nice way to do it:

```<code>fun Drawable.getMirroredDrawable(): Drawable {
    return object : LayerDrawable(arrayOf(this)) {
        val drawingRect = Rect()
        val matrix = Matrix()
        override fun draw(canvas: Canvas) {
            matrix.reset()
            matrix.preScale(-1.0f, 1.0f, canvas.width / 2.0f, canvas.height / 2.0f)
            canvas.matrix = matrix
            drawingRect.left = (canvas.width - intrinsicWidth) / 2
            drawingRect.top = (canvas.height - intrinsicHeight) / 2
            drawingRect.right = drawingRect.left + intrinsicWidth
            drawingRect.bottom = drawingRect.top + intrinsicHeight
            if (bounds != drawingRect)
                bounds = drawingRect
            super.draw(canvas)
        }
    }
}
</code>```

答: Set android:autoMirrored="true" in your XML vector file,

Body:
Background

I know it's possible to create a rotated version of a Drawable (or Bitmap), as such (written about it here) :

@JvmStatic
fun getRotateDrawable(d: Drawable, angle: Int): Drawable {
    if (angle % 360 == 0)
       return d
    return object : LayerDrawable(arrayOf(d)) {
        override fun draw(canvas: Canvas) {
            canvas.save()
            canvas.rotate(angle.toFloat(), (d.bounds.width() / 2).toFloat(), (d.bounds.height() / 2).toFloat())
            super.draw(canvas)
            canvas.restore()
        }
    }
}

The problem

I wanted to have autoMirrored being set to some drawable (VectorDrawable in my case), which would flip (mirror so that left is right, and right is left, but not affect top and bottom) it in case the locale of the device is RTL.

As an example (and it's only an example!), if you take a drawable that shows a left-arrow, after flipping it will be a right-arrow.

Sadly, this is available only from API 19.

That's why I decided to make a new Drawable out of it, to be a flipped version of the original one

What I've tried

I've found a nice article of doing the same thing to a View, here, using a Matrix. So I've tried this:

    @JvmStatic
    fun getMirroredDrawable(d: Drawable): Drawable {
        return object : LayerDrawable(arrayOf(d)) {
            override fun draw(canvas: Canvas) {
                canvas.save()
                val matrix = Matrix()
                // use this for the other flipping: matrix.preScale(1.0f, -1.0f)
                matrix.preScale(-1.0f, 1.0f);
                canvas.matrix = matrix
                super.draw(canvas)
                canvas.restore()
            }
        }
    }

Sadly, for some reason, this made the drawable not being shown at all. Maybe it does work, yet tries to get shown out of its bounds of whatever View that's showing it.

The question

How can I make a flipped version of a given Drawable, similar to what I did for rotating a Drawable?

Solution:

Based on the answer suggested below (here), here's a nice way to do it:

fun Drawable.getMirroredDrawable(): Drawable {
    return object : LayerDrawable(arrayOf(this)) {
        val drawingRect = Rect()
        val matrix = Matrix()
        override fun draw(canvas: Canvas) {
            matrix.reset()
            matrix.preScale(-1.0f, 1.0f, canvas.width / 2.0f, canvas.height / 2.0f)
            canvas.matrix = matrix
            drawingRect.left = (canvas.width - intrinsicWidth) / 2
            drawingRect.top = (canvas.height - intrinsicHeight) / 2
            drawingRect.right = drawingRect.left + intrinsicWidth
            drawingRect.bottom = drawingRect.top + intrinsicHeight
            if (bounds != drawingRect)
                bounds = drawingRect
            super.draw(canvas)
        }
    }
}


问:
Error exporting Xcode archive since version 13.2.1
We have been getting an error in exporting an archive since the release of Xcode 13.2.1, and are also seeing it in 13.3.  (13.1 works great)

The error is:

```<code>Reached end of file while looking for: Mach-O slice.
</code>```

I get this when exporting on our jenkins/fastlane server as well on my development machine.

Curious if anyone has found a solution for this?

答:
It can be an internal issue with malformed library files, try to reload it.

You can try: export_xcargs: "-allowProvisioningUpdates"

Body:
We have been getting an error in exporting an archive since the release of Xcode 13.2.1, and are also seeing it in 13.3.  (13.1 works great)

The error is:

Reached end of file while looking for: Mach-O slice.

I get this when exporting on our jenkins/fastlane server as well on my development machine.

Curious if anyone has found a solution for this?


问:
Blender animation in WPF
Hi I have my stickman with bones etc in blender. I want to use him in my WPF/C# application to make some simple app like shaking hand or move leg. I found some graphic engines but they cost a lot, is there any free solution to import stickman from blender and make some simple animation ?</p>

答:
These are different products provided by different vendors:

blender: for animation creation, game, etc, replacing 3D maya studio;

blend: supplied with microsoft visual studio, to write xaml wpf;

unity: an ide for game spicifically.

Title: Blender animation in WPF


答:
If you want to remove only the first repeating character then you can use matchAll here as:

Just see the browser compatibility before using this

const str = 'CANADA';
const firstRepeatedChar = 'A';
const result = [];

for (let { index } of str.matchAll(firstRepeatedChar)) {
  result.push(str.slice(0, index) + str.slice(index + 1));
}

console.log(result);```
</div>
</div>
</p>
<hr />
<p><strong>NOTE: If you want to search for the first repeating character then remove it, then you can do as:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const str = 'CANADA';

let firstRepeatedChar = '';
const set = new Set();
for (let i = 0; i < str.length; ++i) {
  if (!set.has(str[i])) {
    set.add(str[i]);
  } else {
    firstRepeatedChar = str[i];
    break;
  }
}

const result = [];
for (let { index } of str.matchAll(firstRepeatedChar)) {
  result.push(str.slice(0, index) + str.slice(index + 1));
}

console.log(result);</code>```

Title: How to remove only one of repeated chars in string using JavaScript

Body:
I have a string with repeated chars like : 'CANADA'.

And I am trying to get the string which removed only one of repeated chars :

'CNADA', 'CANDA', 'CANAD'.

I've tried it with subString, but it returned the part of string removed.
Also I've tried it with reduce, but it ended up removing all the repeated chars ('CND').

What is the way of removing only one char at time?
The results can be stored in array. (results = ['CNADA', 'CANDA', 'CANAD'])

Thank you.

Body:
If you want to remove only the first repeating character then you can use matchAll here as:

Just see the browser compatibility before using this

const str = 'CANADA';
const firstRepeatedChar = 'A';
const result = [];

for (let { index } of str.matchAll(firstRepeatedChar)) {
  result.push(str.slice(0, index) + str.slice(index + 1));
}

console.log(result);

NOTE: If you want to search for the first repeating character then remove it, then you can do as:

const str = 'CANADA';

let firstRepeatedChar = '';
const set = new Set();
for (let i = 0; i < str.length; ++i) {
  if (!set.has(str[i])) {
    set.add(str[i]);
  } else {
    firstRepeatedChar = str[i];
    break;
  }
}

const result = [];
for (let { index } of str.matchAll(firstRepeatedChar)) {
  result.push(str.slice(0, index) + str.slice(index + 1));
}

console.log(result);