问:
POST request with aiohttp returns invalid method for slightly larger files
I try to implement aiohttp requests for one of my services. I need to send a POST request with a .pdf file to another API. This API accepts multipart/form-data and application/pdf.
Following code works just fine for some .pdf:

```<code>async with aiohttp.ClientSession() as session:
    async with session.post(URL, data={'file': open(file_to_store, 'rb').read()}) as aioresp:
        asynresp = await aioresp.json()
</code>```

But for slightly larger .pdf I get an error from the receiving API with

```<code>WARNING:  Invalid HTTP request received.
   Traceback (most recent call last):
     File "/usr/local/lib/python3.7/site-packages/uvicorn/protocols/http/httptools_impl.py", line 131, in data_received
       self.parser.feed_data(data)
     File "httptools/parser/parser.pyx", line 212, in httptools.parser.parser.HttpParser.feed_data
   httptools.parser.errors.HttpParserInvalidMethodError: Invalid method encountered
</code>```

I assume it has something to do that aiohttp tries to stream larger files but I can't figure out how to format the request in another way?

答:
Since I could not figure the problem out I switched to httpx and all worked just fine and my problem was solved in minutes. Be careful about the timeout, you should set a value that makes sense for your requirements. I can highly recommend httpx: https://www.python-httpx.org/</p>
```<code>files = {'file': open(file_to_store, 'rb')}

async with httpx.AsyncClient() as client:
    r = await client.post(URL, files=files, timeout=None)
</code>```

Body:
I try to implement aiohttp requests for one of my services. I need to send a POST request with a .pdf file to another API. This API accepts multipart/form-data and application/pdf.
Following code works just fine for some .pdf:

async with aiohttp.ClientSession() as session:
    async with session.post(URL, data={'file': open(file_to_store, 'rb').read()}) as aioresp:
        asynresp = await aioresp.json()

But for slightly larger .pdf I get an error from the receiving API with

WARNING:  Invalid HTTP request received.
   Traceback (most recent call last):
     File "/usr/local/lib/python3.7/site-packages/uvicorn/protocols/http/httptools_impl.py", line 131, in data_received
       self.parser.feed_data(data)
     File "httptools/parser/parser.pyx", line 212, in httptools.parser.parser.HttpParser.feed_data
   httptools.parser.errors.HttpParserInvalidMethodError: Invalid method encountered

I assume it has something to do that aiohttp tries to stream larger files but I can't figure out how to format the request in another way?

Body:
Since I could not figure the problem out I switched to httpx and all worked just fine and my problem was solved in minutes. Be careful about the timeout, you should set a value that makes sense for your requirements. I can highly recommend httpx: https://www.python-httpx.org/

files = {'file': open(file_to_store, 'rb')}

async with httpx.AsyncClient() as client:
    r = await client.post(URL, files=files, timeout=None)


来源: stackexchange

问:
PRISM Navigation - Xamarin Forms - MasterDetail/FlyoutPage page setup, previous page nav links disabled when back button pressed?
So I built an app using Prism Library and Xamarin Forms and the Navigation flow starts with a MasterDetail page, like so.

```<code>NavigationService.NavigateAsync($"/{nameof(MainMenuPage)}/{nameof(NavigationPage)}/{nameof(DashboardPage)}");
</code>```

MainMenuPage

My MainMenuPage contains the Flyout page with a ListView of the MenuItems

```<code><FlyoutPage.Flyout>
    <NavigationPage
        NavigationPage.HasNavigationBar="false"
        Icon="{ StaticResource HamburgerIcon }"
        Style="{ StaticResource MainMenuStyle }"
        Title="{ grial:Translate PageTitleMainMenu }">
        <x:Arguments>
            <ContentPage>
                <Grid>
                    <BoxView
                        Style="{ StaticResource MainMenuOrModalBackgroundStyle }"
                        Opacity="1" />

                    <Image
                        Style="{ StaticResource MainMenuBackgroundImageStyle }" />

                    <Grid
                        grial:Effects.ApplyIOSSafeAreaAsPadding="Left,Right"
                        RowSpacing="0"
                        VerticalOptions="FillAndExpand">
                        <Grid.RowDefinitions>
                            <RowDefinition
                                    Height="Auto" />
                            <RowDefinition
                                    Height="*" />
                            <RowDefinition
                                    Height="Auto"/>
                        </Grid.RowDefinitions>

                        <local:BrandBlock
                                Grid.Row="0"
                                Grid.Column="0"
                                Margin="20,60,20,30"
                                VerticalOptions="Start"
                                HorizontalOptions="Start" />

                        <ListView
                                Margin="0,0,0,10"
                                Grid.Row="1"
                                SelectedItem="{ Binding SelectedMainMenuItem, Mode=TwoWay}"
                                ItemsSource="{ Binding MainMenuItems }"
                                VerticalOptions="FillAndExpand"
                                Style="{ StaticResource MainMenuListViewStyle }">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <ViewCell>
                                        <views:MainMenuItemTemplate />
                                    </ViewCell>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                            <ListView.Behaviors>
                                <behavior:EventToCommandBehavior EventName="ItemTapped"
                                                                 Command="{Binding NavigateCommand}"
                                                                 EventArgsParameterPath="Item">

                                </behavior:EventToCommandBehavior>
                            </ListView.Behaviors>
                        </ListView>

                        <views:ApplicationVersionTemplate Grid.Row="2" Margin="35,0,0,20" HorizontalOptions="Start" VerticalOptions="Start" />
                    </Grid>
                </Grid>
            </ContentPage>
        </x:Arguments>
    </NavigationPage>
</FlyoutPage.Flyout>

<FlyoutPage.Detail>
    <NavigationPage>
        <x:Arguments>
            <ContentPage>
                <Grid></Grid>
            </ContentPage>
        </x:Arguments>
    </NavigationPage>
</FlyoutPage.Detail>
</code>```

I'm navigating to the detail pages using the following format:

```<code>await NavigationService.NavigateAsync($"{nameof(NavigationPage)}/{SelectedMainMenuItem.PageName}", null, SelectedMainMenuItem.IsModal, SelectedMainMenuItem.IsAnimated);
</code>```

I noticed in a lot of the samples, the MasterDetailPage.Master node is in a ContentPage not a NavigationPage node like I'm doing. Is that what I'm doing wrong? It looks to me like NavigationPage is a child of Master here. Is that correct? Just trying to figure out why when I go back to a previous page (by pressing the back button in the navbar) the page is disabled, meaning the navigation links no longer work. My initial root page navigation is absolute, all the rest of the Navigate commands are relative.

Note - I changed the MasterDetailPage to FlyoutPage since the naming changed in Xamarin.Forms v5. This bug was happening before I changed the name to FlyoutPage.

答: So, I rolled back my code to a previous version and then, one at a time, added back in the packages and code changes, smoke testing each iteration along the way. My best guess is there was a conflict between Telerik UI for Xamarin package and the latest Xamarin Forms version but I can't be sure. I updated Xamarin Forms and Prism to latest update and it's all working fine.</p>

ContentLicense: CC BY-SA 4.0

Body:
So I built an app using Prism Library and Xamarin Forms and the Navigation flow starts with a MasterDetail page, like so.

NavigationService.NavigateAsync($"/{nameof(MainMenuPage)}/{nameof(NavigationPage)}/{nameof(DashboardPage)}");

MainMenuPage

My MainMenuPage contains the Flyout page with a ListView of the MenuItems

<FlyoutPage.Flyout>
    <NavigationPage
        NavigationPage.HasNavigationBar="false"
        Icon="{ StaticResource HamburgerIcon }"
        Style="{ StaticResource MainMenuStyle }"
        Title="{ grial:Translate PageTitleMainMenu }">
        <x:Arguments>
            <ContentPage>
                <Grid>
                    <BoxView
                        Style="{ StaticResource MainMenuOrModalBackgroundStyle }"
                        Opacity="1" />

                    <Image
                        Style="{ StaticResource MainMenuBackgroundImageStyle }" />

                    <Grid
                        grial:Effects.ApplyIOSSafeAreaAsPadding="Left,Right"
                        RowSpacing="0"
                        VerticalOptions="FillAndExpand">
                        <Grid.RowDefinitions>
                            <RowDefinition
                                    Height="Auto" />
                            <RowDefinition
                                    Height="*" />
                            <RowDefinition
                                    Height="Auto"/>
                        </Grid.RowDefinitions>

                        <local:BrandBlock
                                Grid.Row="0"
                                Grid.Column="0"
                                Margin="20,60,20,30"
                                VerticalOptions="Start"
                                HorizontalOptions="Start" />

                        <ListView
                                Margin="0,0,0,10"
                                Grid.Row="1"
                                SelectedItem="{ Binding SelectedMainMenuItem, Mode=TwoWay}"
                                ItemsSource="{ Binding MainMenuItems }"
                                VerticalOptions="FillAndExpand"
                                Style="{ StaticResource MainMenuListViewStyle }">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <ViewCell>
                                        <views:MainMenuItemTemplate />
                                    </ViewCell>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                            <ListView.Behaviors>
                                <behavior:EventToCommandBehavior EventName="ItemTapped"
                                                                 Command="{Binding NavigateCommand}"
                                                                 EventArgsParameterPath="Item">

                                </behavior:EventToCommandBehavior>
                            </ListView.Behaviors>
                        </ListView>

                        <views:ApplicationVersionTemplate Grid.Row="2" Margin="35,0,0,20" HorizontalOptions="Start" VerticalOptions="Start" />
                    </Grid>
                </Grid>
            </ContentPage>
        </x:Arguments>
    </NavigationPage>
</FlyoutPage.Flyout>

<FlyoutPage.Detail>
    <NavigationPage>
        <x:Arguments>
            <ContentPage>
                <Grid></Grid>
            </ContentPage>
        </x:Arguments>
    </NavigationPage>
</FlyoutPage.Detail>

I'm navigating to the detail pages using the following format:

await NavigationService.NavigateAsync($"{nameof(NavigationPage)}/{SelectedMainMenuItem.PageName}", null, SelectedMainMenuItem.IsModal, SelectedMainMenuItem.IsAnimated);

I noticed in a lot of the samples, the MasterDetailPage.Master node is in a ContentPage not a NavigationPage node like I'm doing. Is that what I'm doing wrong? It looks to me like NavigationPage is a child of Master here. Is that correct? Just trying to figure out why when I go back to a previous page (by pressing the back button in the navbar) the page is disabled, meaning the navigation links no longer work. My initial root page navigation is absolute, all the rest of the Navigate commands are relative.

Note - I changed the MasterDetailPage to FlyoutPage since the naming changed in Xamarin.Forms v5. This bug was happening before I changed the name to FlyoutPage.


问:
Spring AMQP - anonymous queue declaration
I am trying to declare anonymous queue using Spring AMQP annotations, but seems it is not working.

```<code>@RabbitListener(
  id = "b1",
  bindings =
      @QueueBinding(
          value =
              @Queue(
                  name = "",
                  durable = "false",
                  exclusive = "true",
                  autoDelete = "true",
                  admins = "amqpAdmin1"),
          exchange =
              @Exchange(
                  value = "${my.rabbitmq[0].exchange}", declare = "false",
                  ignoreDeclarationExceptions = "true",
                  type = ExchangeTypes.TOPIC,
                  admins = "amqpAdmin1"),
          key = "*.*.*.*.*.*.*.-",
          admins = "amqpAdmin1"),
  admin = "amqpAdmin1",
  containerFactory = "lf1",
  autoStartup = "true")
</code>```

I read that I can use empty name param, and it should create anonymous queue - but the thing is that I need server-generated name (I have no privileges to name my own queue). Is this possible at all with spring AMQP lib currently?

I see in the code that it currently uses

```<code>private String declareQueue(org.springframework.amqp.rabbit.annotation.Queue bindingQueue,
        Collection<Declarable> declarables) {
    String queueName = (String) resolveExpression(bindingQueue.value());
    boolean isAnonymous = false;
    if (!StringUtils.hasText(queueName)) {
        queueName = Base64UrlNamingStrategy.DEFAULT.generateName(); //<---- HERE
        // default exclusive/autodelete and non-durable when anonymous
        isAnonymous = true;
    }
</code>```

but here instead of Base64UrlNamingStrategy.DEFAULT.generateName(); -> I would need to spring to go to RabbitMQ broker and fetch RabbitMQ generated name and use that one.

UPDATE

```<code>@Bean
  public Queue q2(){
    Queue q = QueueBuilder.nonDurable().exclusive().autoDelete().build();
    //Queue q = new Queue("", false, true, true); --> same
    q.setAdminsThatShouldDeclare(amqpAdmin2());
    return q;
  }

  @Bean
  public Exchange e2(@Value("${my.rabbitmq[1].exchange}") String name){
    Exchange e = ExchangeBuilder.topicExchange(name).ignoreDeclarationExceptions().build();
    e.setAdminsThatShouldDeclare(amqpAdmin2());
    return e;
  }

  @Bean
  public Binding bin2(Queue q2, Exchange e2){
    Binding b = BindingBuilder.bind(q2).to(e2).with("*.*.*.*.*.*.*.-").noargs();
    b.setAdminsThatShouldDeclare(amqpAdmin2());
    return b;
  }

  @RabbitListener(id = "b2", queues = "#{q2}",
      admin = "amqpAdmin2",
      containerFactory = "lf2", autoStartup = "true")
  public void listen2(GenericMessage<?> msg) {
    comparator.recordForComparison(props.getRabbitmq().get(1).getId(), msg.getPayload());
  }
</code>```

and this is in the logs:

```<code>Auto-declaring a non-durable, auto-delete, or exclusive Queue () durable:false, auto-delete:true, exclusive:true. It will be redeclared if the broker stops and is restarted while the connection factory is alive, but all messages will be lost.
2022-02-10 09:22:43.660  INFO 30076 --- [           main] o.s.a.r.l.DirectMessageListenerContainer : Container initialized for queues: [spring.gen-ZAVana-pSSW2WaanrkVZXw_awaiting_declaration]
2022-02-10 09:22:43.661  INFO 30076 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: my.server.com:5671
2022-02-10 09:22:43.765 ERROR 30076 --- [           b2-1] o.s.a.r.l.DirectMessageListenerContainer : Queue not present, scheduling consumer SimpleConsumer [queue=spring.gen-ZAVana-pSSW2WaanrkVZXw_awaiting_declaration, index=0, consumerTag=null identity=3f844994] for restart
</code>```

and this is what I added after removing @RabbitListener. Now it works with this:

```<code>@Bean
  public MessageListenerContainer c2(DirectRabbitListenerContainerFactory lf2, Queue q2){
    DirectMessageListenerContainer lc = lf2.createListenerContainer();
    lc.setQueues(q2);
    lc.setAutoStartup(true);
    MessageListenerAdapter a = new MessageListenerAdapter();
    a.setMessageConverter(converter());
    a.setDefaultListenerMethod("receive");
    a.setDelegate(new MessageReceiver(props.getRabbitmq().get(1).getId()));
    lc.setupMessageListener(a);
    lc.afterPropertiesSet();
    return lc;
  }

class MessageReceiver{

    private final int id;

    public MessageReceiver(int id){
      this.id= id;
    }

    void receive(Object o){
      comparator.recordForComparison(this.id, o);
    }
  }
</code>```

答:
I found the problem - the @RabbitListener bean postprocessor grabs the name before it has been declared.

Here is a work around (manually inject the queue):

@SpringBootApplication
public class So71033589Application {

    public static void main(String[] args) {
        SpringApplication.run(So71033589Application.class, args);
    }

    @RabbitListener(id = "foo", autoStartup = "false")
    public void listen(String in) {
        System.out.println(in);
    }

}

@Configuration
class Config{

    @Bean
    Queue q() {
        return new Queue("", false, true, true);
    }

    @Bean
    ApplicationRunner runner(RabbitListenerEndpointRegistry registry, Queue q) {
        return args -> {
            MessageListenerContainer container = registry.getListenerContainer("foo");
            ((AbstractMessageListenerContainer) container).setQueues(q);
            container.start();
        };
    }

}
```

Body:
I am trying to declare anonymous queue using Spring AMQP annotations, but seems it is not working.

@RabbitListener(
  id = "b1",
  bindings =
      @QueueBinding(
          value =
              @Queue(
                  name = "",
                  durable = "false",
                  exclusive = "true",
                  autoDelete = "true",
                  admins = "amqpAdmin1"),
          exchange =
              @Exchange(
                  value = "${my.rabbitmq[0].exchange}", declare = "false",
                  ignoreDeclarationExceptions = "true",
                  type = ExchangeTypes.TOPIC,
                  admins = "amqpAdmin1"),
          key = "*.*.*.*.*.*.*.-",
          admins = "amqpAdmin1"),
  admin = "amqpAdmin1",
  containerFactory = "lf1",
  autoStartup = "true")

I read that I can use empty name param, and it should create anonymous queue - but the thing is that I need server-generated name (I have no privileges to name my own queue). Is this possible at all with spring AMQP lib currently?

I see in the code that it currently uses

private String declareQueue(org.springframework.amqp.rabbit.annotation.Queue bindingQueue,
        Collection<Declarable> declarables) {
    String queueName = (String) resolveExpression(bindingQueue.value());
    boolean isAnonymous = false;
    if (!StringUtils.hasText(queueName)) {
        queueName = Base64UrlNamingStrategy.DEFAULT.generateName(); //<---- HERE
        // default exclusive/autodelete and non-durable when anonymous
        isAnonymous = true;
    }

but here instead of Base64UrlNamingStrategy.DEFAULT.generateName(); -> I would need to spring to go to RabbitMQ broker and fetch RabbitMQ generated name and use that one.

UPDATE

@Bean
  public Queue q2(){
    Queue q = QueueBuilder.nonDurable().exclusive().autoDelete().build();
    //Queue q = new Queue("", false, true, true); --> same
    q.setAdminsThatShouldDeclare(amqpAdmin2());
    return q;
  }

  @Bean
  public Exchange e2(@Value("${my.rabbitmq[1].exchange}") String name){
    Exchange e = ExchangeBuilder.topicExchange(name).ignoreDeclarationExceptions().build();
    e.setAdminsThatShouldDeclare(amqpAdmin2());
    return e;
  }

  @Bean
  public Binding bin2(Queue q2, Exchange e2){
    Binding b = BindingBuilder.bind(q2).to(e2).with("*.*.*.*.*.*.*.-").noargs();
    b.setAdminsThatShouldDeclare(amqpAdmin2());
    return b;
  }

  @RabbitListener(id = "b2", queues = "#{q2}",
      admin = "amqpAdmin2",
      containerFactory = "lf2", autoStartup = "true")
  public void listen2(GenericMessage<?> msg) {
    comparator.recordForComparison(props.getRabbitmq().get(1).getId(), msg.getPayload());
  }

and this is in the logs:

Auto-declaring a non-durable, auto-delete, or exclusive Queue () durable:false, auto-delete:true, exclusive:true. It will be redeclared if the broker stops and is restarted while the connection factory is alive, but all messages will be lost.
2022-02-10 09:22:43.660  INFO 30076 --- [           main] o.s.a.r.l.DirectMessageListenerContainer : Container initialized for queues: [spring.gen-ZAVana-pSSW2WaanrkVZXw_awaiting_declaration]
2022-02-10 09:22:43.661  INFO 30076 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: my.server.com:5671
2022-02-10 09:22:43.765 ERROR 30076 --- [           b2-1] o.s.a.r.l.DirectMessageListenerContainer : Queue not present, scheduling consumer SimpleConsumer [queue=spring.gen-ZAVana-pSSW2WaanrkVZXw_awaiting_declaration, index=0, consumerTag=null identity=3f844994] for restart

and this is what I added after removing @RabbitListener. Now it works with this:

@Bean
  public MessageListenerContainer c2(DirectRabbitListenerContainerFactory lf2, Queue q2){
    DirectMessageListenerContainer lc = lf2.createListenerContainer();
    lc.setQueues(q2);
    lc.setAutoStartup(true);
    MessageListenerAdapter a = new MessageListenerAdapter();
    a.setMessageConverter(converter());
    a.setDefaultListenerMethod("receive");
    a.setDelegate(new MessageReceiver(props.getRabbitmq().get(1).getId()));
    lc.setupMessageListener(a);
    lc.afterPropertiesSet();
    return lc;
  }

class MessageReceiver{

    private final int id;

    public MessageReceiver(int id){
      this.id= id;
    }

    void receive(Object o){
      comparator.recordForComparison(this.id, o);
    }
  }


问:
Retrieving values from multidimensional arrays
I have an array something like this:

```<code>   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } };
</code>```

if I want to retrieve 1 and 2 and feed them into this:

```<code>int a;
int b;
</code>```

How do I do it?

Is it something like this:

```<code>multiDimensionalArray2[0,0]
</code>```

What if I wanted to put more numbers in the same form  e.g. { { 2, 1 }, { 4, 1 } };, in the same form as above. Would it be something like this:

```<code>   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } },{ { 2, 1 }, { 4, 1 } };
</code>```

To retrieve the second set would I do this, multiDimensionalArray2[1,1]

答:
If you have a multi dimensional array like the one you gave,

```<code>int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 }, { 2, 1 }, { 4, 1 } };
</code>```

We want to get the index of the number 5. To do this we need two indexes, [a,b]

Index a is the index of the "group of numbers" that you want to get.
First look at which group it is in. The first group (index 0) contains 1 and 2, the second group (index 1) contains 4 and 5.
Therefore a = 1.

Index b is the index of the "position within the group" that you want to get.
In the group {4, 5}, the number 5 is the first item (index 0). Therfore b = 0.

This means that the number 5 can be found at multiDimensionalArray2[1,0]

Body:
I have an array something like this:

   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } };

if I want to retrieve 1 and 2 and feed them into this:

int a;
int b;

How do I do it?

Is it something like this:

multiDimensionalArray2[0,0]

What if I wanted to put more numbers in the same form  e.g. { { 2, 1 }, { 4, 1 } };, in the same form as above. Would it be something like this:

   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } },{ { 2, 1 }, { 4, 1 } };

To retrieve the second set would I do this, multiDimensionalArray2[1,1]

Body:
If you have a multi dimensional array like the one you gave,

int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 }, { 2, 1 }, { 4, 1 } };

We want to get the index of the number 5. To do this we need two indexes, [a,b]

Index a is the index of the "group of numbers" that you want to get.
First look at which group it is in. The first group (index 0) contains 1 and 2, the second group (index 1) contains 4 and 5.
Therefore a = 1.

Index b is the index of the "position within the group" that you want to get.
In the group {4, 5}, the number 5 is the first item (index 0). Therfore b = 0.

This means that the number 5 can be found at multiDimensionalArray2[1,0]

ContentLicense: CC BY-SA 3.0


问:
How to write this PostgreSQL query in jpa specification or criteria query?
i need to implement the following query as a jpa specification or criteria query?

Please let me know how this can be done using inner joins and also a group by clause.

select SUM(r.story_points) as SP,count(r.user_id) as mx,r.user_id,e.component_id from task r inner join component e on  r.component_id =e.component_id group by r.user_id ,e.component_id;

My Task Entity:

```<code>package com.sysco.sprintreporting.entity;

import com.fasterxml.jackson.annotation.JsonBackReference;

import lombok.*;

import javax.persistence.*;
import java.time.LocalDate;

@Entity
@Table(name = "Task")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString

public class Task {

    @Id
    @Column(name = "issue_key")
    private String issueKey;

    @Column(name = "issue_id")
    private long issueId;

    @Column(name = "issue_type")
    private String issueType;

    @Column(name = "storyPoints")
    private Double storyPoints;

    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "user_id")
    @JsonBackReference
    private User assignee_id;

    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "component_id")
    @JsonBackReference
    private Component component_id;

}

</code>```

My Component Entity:

```<code>package com.sysco.sprintreporting.entity;

import java.util.Set;

import javax.persistence.*;

import lombok.*;

@Entity
@Table(name = "Component")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Component {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "component_id")
    private int id;

    @Column(name = "component_name")
    private String name;

    @Column(name = "component_desc")
    private String description;

    @OneToMany(mappedBy = "component_id", cascade = CascadeType.ALL)
    private Set<Task> Task;

}

</code>```

答:
To do an aggregated query with joins with Criteria Query API you can use Tuple Query. Tuple Query allows to select multiple values/columns with multiselect method.

Something like this (not tested):

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> mainQuery = cb.createTupleQuery();

Root<Task> rootTask = mainQuery.from(Task.class);
Join<Task, Component> componentJoin = rootTask.join("component_id");

mainQuery.multiselect(
    rootTask.get("user_id"),
    componentJoin.get("component_id"),
    cb.sum(rootTask.get("story_points").alias("SP"),
    cb.count(rootTask.get("user_id")).alias("mx")
);

mainQuery.groupBy(
    rootTask.get("user_id"),
    componentJoin.get("component_id")
);

TypedQuery<Tuple> query = entityManager.createQuery(mainQuery);

List<Tuple> tasks = query.getResultList();
```

You can see some examples of using Tuple Query: JPA Criteria API - Multiple Query selection and use of Tuple

Regards.

Body:
i need to implement the following query as a jpa specification or criteria query?

Please let me know how this can be done using inner joins and also a group by clause.

select SUM(r.story_points) as SP,count(r.user_id) as mx,r.user_id,e.component_id from task r inner join component e on  r.component_id =e.component_id group by r.user_id ,e.component_id;

My Task Entity:

package com.sysco.sprintreporting.entity;

import com.fasterxml.jackson.annotation.JsonBackReference;

import lombok.*;

import javax.persistence.*;
import java.time.LocalDate;

@Entity
@Table(name = "Task")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString

public class Task {

    @Id
    @Column(name = "issue_key")
    private String issueKey;

    @Column(name = "issue_id")
    private long issueId;

    @Column(name = "issue_type")
    private String issueType;

    @Column(name = "storyPoints")
    private Double storyPoints;

    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "user_id")
    @JsonBackReference
    private User assignee_id;

    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "component_id")
    @JsonBackReference
    private Component component_id;

}

My Component Entity:

package com.sysco.sprintreporting.entity;

import java.util.Set;

import javax.persistence.*;

import lombok.*;

@Entity
@Table(name = "Component")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Component {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "component_id")
    private int id;

    @Column(name = "component_name")
    private String name;

    @Column(name = "component_desc")
    private String description;

    @OneToMany(mappedBy = "component_id", cascade = CascadeType.ALL)
    private Set<Task> Task;

}

Body:
To do an aggregated query with joins with Criteria Query API you can use Tuple Query. Tuple Query allows to select multiple values/columns with multiselect method.

Something like this (not tested):

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> mainQuery = cb.createTupleQuery();

Root<Task> rootTask = mainQuery.from(Task.class);
Join<Task, Component> componentJoin = rootTask.join("component_id");

mainQuery.multiselect(
    rootTask.get("user_id"),
    componentJoin.get("component_id"),
    cb.sum(rootTask.get("story_points").alias("SP"),
    cb.count(rootTask.get("user_id")).alias("mx")
);

mainQuery.groupBy(
    rootTask.get("user_id"),
    componentJoin.get("component_id")
);

TypedQuery<Tuple> query = entityManager.createQuery(mainQuery);

List<Tuple> tasks = query.getResultList();

You can see some examples of using Tuple Query: JPA Criteria API - Multiple Query selection and use of Tuple

Regards.


问:
Save Dark mode to local storage in JavaScript
I've added dark mode to my website and it works perfectly

But just after I refresh my page the default view that is Day Mode is shown.

so, is there any way to save this preferences?

HTML

```<code>    <body>
    <div class="main-page" id="main-page">
        <a id="darkmode" onclick="myFunction()" style="display: block; position: fixed; z-index: 2147483647;"><span><i class="fa fa-moon" id="darkIcon"></i></span></a>
    </div>
</body>
</code>```

JavaScript

```<code>    function myFunction() {
    var element = document.getElementById("main-page");
    var icon = document.getElementById("darkIcon");
    element.classList.toggle("active-dark");

    if (element.className == ["main-page active-dark"]){
        if (icon.className == "fa fa-moon"){
            icon.classList.toggle("fa-sun");
        }else {
            icon.classList.toggle("fa-moon");

        }

    }
    if (element.className == "main-page"){
        if (icon.className == "fa fa-sun"){
            icon.classList.toggle("fa-moon");
        }else {
            icon.classList.toggle("fa-sun");

        }

    }
}
</code>```

NOTE :

To activate dark mode i just add "active-dark" after "main-page" class and to disable dark mode i just remove the class

答:
Here is the full code to auto-detect user dark mode and save it to local storage for keeping the current mode throughout the session.

The below code will run when the user clicks the dark mode toggle button. Make sure you create the CSS class for .dark-mode with the required CSS code.

```<code>$(document).ready(function () {

   $("#dark-mode").click(function () {
      $("body").toggleClass("dark-mode");
      if (localStorage.hasOwnProperty('isDarkMode')) {
         if (localStorage.getItem('isDarkMode') === 'true') {
            localStorage.setItem('isDarkMode', 'false');
         }
         else if (localStorage.getItem('isDarkMode') === 'false') {
            localStorage.setItem('isDarkMode', 'true');
         }
      }
   })

   if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      if (!(localStorage.hasOwnProperty('isDarkMode'))) {
         $("body").addClass("dark-mode");
         localStorage.setItem('isDarkMode', true);
      }
   }
   else {
      if (!(localStorage.hasOwnProperty('isDarkMode'))) {
         $("body").removeClass("dark-mode");
         localStorage.setItem('isDarkMode', false);
      }
   }

   if (localStorage.hasOwnProperty('isDarkMode')) {

      if (localStorage.getItem('isDarkMode') === 'true') {
         $("body").addClass("dark-mode");
      }
      else if (localStorage.getItem('isDarkMode') === 'false') {
         $("body").removeClass("dark-mode");
      }
   }
})
</code>```

Body:
I've added dark mode to my website and it works perfectly

But just after I refresh my page the default view that is Day Mode is shown.

so, is there any way to save this preferences?

HTML

JavaScript

    function myFunction() {
    var element = document.getElementById("main-page");
    var icon = document.getElementById("darkIcon");
    element.classList.toggle("active-dark");

    if (element.className == ["main-page active-dark"]){
        if (icon.className == "fa fa-moon"){
            icon.classList.toggle("fa-sun");
        }else {
            icon.classList.toggle("fa-moon");

        }

    }
    if (element.className == "main-page"){
        if (icon.className == "fa fa-sun"){
            icon.classList.toggle("fa-moon");
        }else {
            icon.classList.toggle("fa-sun");

        }

    }
}

NOTE :

To activate dark mode i just add "active-dark" after "main-page" class and to disable dark mode i just remove the class

Body:
Here is the full code to auto-detect user dark mode and save it to local storage for keeping the current mode throughout the session.

The below code will run when the user clicks the dark mode toggle button. Make sure you create the CSS class for .dark-mode with the required CSS code.

$(document).ready(function () {

   $("#dark-mode").click(function () {
      $("body").toggleClass("dark-mode");
      if (localStorage.hasOwnProperty('isDarkMode')) {
         if (localStorage.getItem('isDarkMode') === 'true') {
            localStorage.setItem('isDarkMode', 'false');
         }
         else if (localStorage.getItem('isDarkMode') === 'false') {
            localStorage.setItem('isDarkMode', 'true');
         }
      }
   })

   if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      if (!(localStorage.hasOwnProperty('isDarkMode'))) {
         $("body").addClass("dark-mode");
         localStorage.setItem('isDarkMode', true);
      }
   }
   else {
      if (!(localStorage.hasOwnProperty('isDarkMode'))) {
         $("body").removeClass("dark-mode");
         localStorage.setItem('isDarkMode', false);
      }
   }

   if (localStorage.hasOwnProperty('isDarkMode')) {

      if (localStorage.getItem('isDarkMode') === 'true') {
         $("body").addClass("dark-mode");
      }
      else if (localStorage.getItem('isDarkMode') === 'false') {
         $("body").removeClass("dark-mode");
      }
   }
})


问:
Using python and Selenium to scrape the innerText within an HTML element?
I wrote a script that uses the selenium and pyautogui modules to login and scrape a value from an element and print it, but it's printing two dashes --.

Here is the HTML that contains the value 417 which I want to retrieve:

```<code><p id="totReqCountVal" class="trailer-0 avenir-regular font-size-4 text-green js-total-requests">417</p>
</code>```

This is the relevant code I have tried:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By

browser.get('website_to_be_scraped')
browser.find_element(By.ID, 'totReqCountVal')
</code>```

I then tried:

```<code>views = browser.find_element(By.ID, 'totReqCountVal')
    print(views)
</code>```

which returns:

```<code>(session="12e48df447f7df855a1ee596ba609a30", element="1027ec31-8cb8-4758-b4b0-82b85628ed6c")
</code>```

With some help I have also tried the following:

Using CSS_SELECTOR and text attribute:

```<code>print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "p#totReqCountVal[class$='js-total-requests']"))).text)
Using XPATH and get_attribute("innerHTML"):

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//p[@id='totReqCountVal' and contains(@class, 'js-total-requests')]"))).get_attribute("innerHTML"))
</code>```

added the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

I have checked through devtools if the locator strategies identifies the element uniquely, checked for iframes, and shadow root.

How do I retrieve the 417 value?

答:
views is the WebElement which on printing rightly prints:

```<code>(session="12e48df447f7df855a1ee596ba609a30", element="1027ec31-8cb8-4758-b4b0-82b85628ed6c")
</code>```

Solution

To print the text 417 you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR and text attribute:

```<code>print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "p#totReqCountVal[class$='js-total-requests']"))).text)
</code>```

Using XPATH and get_attribute("innerHTML"):

```<code>print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//p[@id='totReqCountVal' and contains(@class, 'js-total-requests')]"))).get_attribute("innerHTML"))
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python

References

Link to useful documentation:

get_attribute() method Gets the given attribute or property of the element.

text attribute returns The text of the element.

Difference between text and innerHTML using Selenium

Body:
I wrote a script that uses the selenium and pyautogui modules to login and scrape a value from an element and print it, but it's printing two dashes --.

Here is the HTML that contains the value 417 which I want to retrieve:

417

This is the relevant code I have tried:

from selenium import webdriver
from selenium.webdriver.common.by import By

browser.get('website_to_be_scraped')
browser.find_element(By.ID, 'totReqCountVal')

I then tried:

views = browser.find_element(By.ID, 'totReqCountVal')
    print(views)

which returns:

(session="12e48df447f7df855a1ee596ba609a30", element="1027ec31-8cb8-4758-b4b0-82b85628ed6c")

With some help I have also tried the following:

Using CSS_SELECTOR and text attribute:

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "p#totReqCountVal[class$='js-total-requests']"))).text)
Using XPATH and get_attribute("innerHTML"):

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//p[@id='totReqCountVal' and contains(@class, 'js-total-requests')]"))).get_attribute("innerHTML"))

added the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

I have checked through devtools if the locator strategies identifies the element uniquely, checked for iframes, and shadow root.

How do I retrieve the 417 value?

Body:
views is the WebElement which on printing rightly prints:

(session="12e48df447f7df855a1ee596ba609a30", element="1027ec31-8cb8-4758-b4b0-82b85628ed6c")

Solution

To print the text 417 you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR and text attribute:

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "p#totReqCountVal[class$='js-total-requests']"))).text)

Using XPATH and get_attribute("innerHTML"):

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//p[@id='totReqCountVal' and contains(@class, 'js-total-requests')]"))).get_attribute("innerHTML"))

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python

References

Link to useful documentation:

get_attribute() method Gets the given attribute or property of the element.

text attribute returns The text of the element.

Difference between text and innerHTML using Selenium


问:
adding class to current day with javascript
im making a calendar and i want to add a className to current day so i could highlight it but i got some troubles and i wanna please you for help</p>
```<code>function getCurrentDayClass() {
        return day.format("DD-MM-YY") === dayjs().format("DD-MM-YY")
        //   document.getElementById().className += "current-day"
    }
</code>```
```<code><header>
                {rowIdx === 0 && (
                    <p>
                        {day.format('ddd').toUpperCase()}
                    </p>
                )}

                <p className="calendar-day">
                    {day.format("DD")}

                </p>

            </header>
</code>```

答:
function getCurrentDayClass() {
  if (day.format("DD-MM-YY") === dayjs().format("DD-MM-YY"))
    return "PUT_YOUR_CSS_CLASSNAME_HERE";// something like "cal-day active"
  return "calendar-day";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  {rowIdx === 0 && (<p>{day.format('ddd').toUpperCase()}</p>)}
  <p className={getCurrentDayClass()}>{day.format("DD")}</p>
</header></code>```

Body:
im making a calendar and i want to add a className to current day so i could highlight it but i got some troubles and i wanna please you for help

function getCurrentDayClass() {
        return day.format("DD-MM-YY") === dayjs().format("DD-MM-YY")
        //   document.getElementById().className += "current-day"
    }

                {rowIdx === 0 && (

                        {day.format('ddd').toUpperCase()}

                )}

                    {day.format("DD")}

Body:
function getCurrentDayClass() {
  if (day.format("DD-MM-YY") === dayjs().format("DD-MM-YY"))
    return "PUT_YOUR_CSS_CLASSNAME_HERE";// something like "cal-day active"
  return "calendar-day";
}

<header>
  {rowIdx === 0 && (<p>{day.format('ddd').toUpperCase()}</p>)}
  <p className={getCurrentDayClass()}>{day.format("DD")}</p>
</header>


问:
Can I publish an app on tha Play Store that has almost the same nape that other app?
Imagine that there is a popular app on Google Play that is named "Obtain results making abdominal exercise in 10 days - exercises of abdominals". Now my question is, could I publish my app with a similar name like "Obtain results making biceps exercise in 10 days - exercises of biceps". So only changing two words of the name of the pupular app. Is this permited on Google Play? Is it considered copy or copyright? Thanks in advance.</p>

答: Yes, you can, if "Obtain results making abdominal exercise in 10 days - exercises of abdominals" rights are not reserved. Google just looking for package name, not app name. Of course, the app name can't be Facebook, Twitter :)</p>


问:
Flutter integration test failing with error `'_pendingFrame == null': is not true.`
I'm creating an integration test to my flutter app but I get this error when finding an TextInput and trying to type inside.
The error: 'package:flutter_test/src/binding.dart': Failed assertion: line 1649 pos 12: '_pendingFrame == null': is not true.

The code:

```<code>final Finder email = find.byWidgetPredicate(
      (widget) => widget is FutXTextField && widget.title == 'EMAIL',
    );

expect(email, findsOneWidget,
        reason: " Só pode haver um botão de escrever email");

await tester.enterText(email, "teste@teste.teste");
</code>```

I didn`t find it anywhere on the internet what this error is.

Does anyone had this exception before and has any idea of how to solve it?

答: I had the same error when the app that I was running the test on threw an exception, if you check the logs do you see any errors occurring before your test failed?</p>

Body:
I'm creating an integration test to my flutter app but I get this error when finding an TextInput and trying to type inside.
The error: 'package:flutter_test/src/binding.dart': Failed assertion: line 1649 pos 12: '_pendingFrame == null': is not true.

The code:

final Finder email = find.byWidgetPredicate(
      (widget) => widget is FutXTextField && widget.title == 'EMAIL',
    );

expect(email, findsOneWidget,
        reason: " Só pode haver um botão de escrever email");

await tester.enterText(email, "teste@teste.teste");

I didn`t find it anywhere on the internet what this error is.

Does anyone had this exception before and has any idea of how to solve it?


问:
Unable to Tap Days in iOS 14 inline DatePicker
I'm trying to create an expandable/collapsible date picker (similar to Apple's date picker in the Date & Time section of the Settings app). I have a tableview that can have a button as one of its table cells. That button shows the currently picked date as its title. Tapping on that button will add a table cell below the button with the new iOS 14 inline date picker.

The issue I'm facing is that I can interact with the date picker by changing the month and year, but the selected day doesn't change when I tap on different days. I added a target on valueChanged and the selector method is triggered when I change the month and year, but not when I choose a different day.

I saw there was a similar question on StackOverflow, but the OP deleted it for some reason.

The table cell containing the date picker is simple. I am dequeueing the cell from its own xib and the xib only contains a view with the date picker inside it. I am not setting the height of the date picker cell, but just using UITableView.automaticDimension to get self-sizing cells. I also looked at the view hierarchy and there isn't anything in front of the date picker, so the touches should be sent to the date picker.

Has anyone else had this issue?

答:
I had the same issue. In my case problem was in UITapGestureRecognizer, which I've add to hide keyboard.

This code fixed my problem:

```<code>tapGesture.cancelsTouchesInView = false
</code>```

Body:
I had the same issue. In my case problem was in UITapGestureRecognizer, which I've add to hide keyboard.

This code fixed my problem:

tapGesture.cancelsTouchesInView = false


问:
How do I port code for Borland C++ builder to Linux?
I have source code for a Windows DLL that is written in C++ and uses Visual Component Library. Now my task is to port that to Linux, but I don't have source code for the VCL itself, or any kind of documentation (and I have never worked with Borland C++; in my Windows days I used MFC).

This should not be all that hard, since my DLL does not have any GUI: as far as I can see, it mostly uses VCL for multithreading. I ran into a class that inherits from TThread and that is where I got stuck. I did some search on the Internet, but found no documentation for VCL so far. I would like to avoid buying a book on Borland C++ Builder, because I don't have time to wait for it to arrive from the Amazon. I cannot consider buying the package for Windows, because at work I only have a Linux box.

Any suggestions?

答:
The VCL is documented on CodeGear's web site.  TThread in particular is described here.

I've found the documentation on the threading-related components of the VCL to be rather sparse.  This site has a much better description of the Delphi/VCL approach to threading.

OwnerDisplayName: ajanicij

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Josh Kelley


问:
Safely hooking C functions into assembly
I'm trying to put some C hooks into some code that someone else wrote in asm. I don't know much about x86 asm and I want to make sure I'm doing this safely.

So far I've got this much:

```<code>EXTERN _C_func

CALL _C_func
</code>```

And that seems to work, but I'm sure that's dangerous as-is. At the very least it could be destroying EAX, and possibly more.

So I think all I need to know is: Which registers does C destroy and how do I ensure the registers are being saved properly? Is there anything else I can do to make sure I can safely insert hooks into arbitrary locations?

I'm using Visual Studio for the C functions, if that helps.
Thank you.

UPDATE:

I looked up the "paranoid" method several people suggested and it looks like this:

```<code>pushfd
pushad
call _C_func
popad
popfd
</code>```

AD = (A)ll general registers

FD = (F)lags

(I'm not sure what the 'd' stands for, but it means 32-bit registers instead of 16-bit.)

But the most efficient method is illustrated in Kragen's answer below. (Assuming you don't need the preserve the flags. If you do, add the FD instructions.)

Also, be careful about allocating lots of stack variables in your C function as it could overrun the asm subroutine's stack space.

I think that about does it, thanks for you help everyone!

答:
This will depend on whether you are using an x86 or x86_64 platform ... the calling conventions for each, as well as the caller-save and callee-save registers (and even the available register set) are a bit different.

That being said, caller-save registers need to be pushed on the stack before you call your C-function.  Callee-save registers you don't need to worry about if you are calling a C-function, but you will need to pay attention to if you call an assembly routine from a C-function.

For a x86 32-bit platform, the caller-save registers are:

```<code>EAX
EDX
ECX
</code>```

Also keep in mind that the stack-pointer registers, ESP and EBP will be changed as well with cdecl calling convention, but a C-function will restore those values after the call assuming you have not done something that a C-function would not expect you to-do with those registers.

The callee-save registers are:

```<code>EBX
ESI
EDI
</code>```

Finally, the return value from your C-function is in the EAX register, and the C-function arguments are pushed onto the stack before calling the function.  The order in which that is done will depend on the calling convention, but for cdecl, that will be in right-to-left order, meaning the left-most argument to the C-function is pushed last on the stack before calling the function.

Should you decide to simply save all the general purpose registers on the stack before you call your C-function, and then pop them back off the stack after the C-function, you can do that on x86 using the PUSHAD and POPAD instructions.  These instructions are not useable on x86_64 though.  And also keep in mind that if you have a return value in EAX, you will need to-do something with that (like saving it in memory), before you call POPAD.

Body:
I'm trying to put some C hooks into some code that someone else wrote in asm. I don't know much about x86 asm and I want to make sure I'm doing this safely.

So far I've got this much:

EXTERN _C_func

CALL _C_func

And that seems to work, but I'm sure that's dangerous as-is. At the very least it could be destroying EAX, and possibly more.

So I think all I need to know is: Which registers does C destroy and how do I ensure the registers are being saved properly? Is there anything else I can do to make sure I can safely insert hooks into arbitrary locations?

I'm using Visual Studio for the C functions, if that helps.
Thank you.

UPDATE:

I looked up the "paranoid" method several people suggested and it looks like this:

pushfd
pushad
call _C_func
popad
popfd

AD = (A)ll general registers

FD = (F)lags

(I'm not sure what the 'd' stands for, but it means 32-bit registers instead of 16-bit.)

But the most efficient method is illustrated in Kragen's answer below. (Assuming you don't need the preserve the flags. If you do, add the FD instructions.)

Also, be careful about allocating lots of stack variables in your C function as it could overrun the asm subroutine's stack space.

I think that about does it, thanks for you help everyone!

Body:
This will depend on whether you are using an x86 or x86_64 platform ... the calling conventions for each, as well as the caller-save and callee-save registers (and even the available register set) are a bit different.

That being said, caller-save registers need to be pushed on the stack before you call your C-function.  Callee-save registers you don't need to worry about if you are calling a C-function, but you will need to pay attention to if you call an assembly routine from a C-function.

For a x86 32-bit platform, the caller-save registers are:

EAX
EDX
ECX

Also keep in mind that the stack-pointer registers, ESP and EBP will be changed as well with cdecl calling convention, but a C-function will restore those values after the call assuming you have not done something that a C-function would not expect you to-do with those registers.

The callee-save registers are:

EBX
ESI
EDI

Finally, the return value from your C-function is in the EAX register, and the C-function arguments are pushed onto the stack before calling the function.  The order in which that is done will depend on the calling convention, but for cdecl, that will be in right-to-left order, meaning the left-most argument to the C-function is pushed last on the stack before calling the function.

Should you decide to simply save all the general purpose registers on the stack before you call your C-function, and then pop them back off the stack after the C-function, you can do that on x86 using the PUSHAD and POPAD instructions.  These instructions are not useable on x86_64 though.  And also keep in mind that if you have a return value in EAX, you will need to-do something with that (like saving it in memory), before you call POPAD.


问:
Looking to assign subgroup values to of a group to a common value in R
I have a series of phone numbers that have individual names associated with them.  The phone numbers are not necessarily unique, and sometimes the name associated with them is missing. I would like to fill in the names with the following rules:

If a grouped phone number has blank entries and only a single name available, I would like to replace the blank names with the one available.

If the grouped number has entries with multiple non-blank names, then I cannot determine who belongs to that phone number and so I make no changes.

Here is the original table:

```<code>library("dplyr")
phone = c("1234","1234","1234","4567","4567","4567","4567","4567");phone
sgroup = c("","Jones","","Smith","","Smith","Williams","Jones");sgroup

DATA = data.frame(phone,sgroup);DATA
</code>```

And here is how I want it to look:

```<code>phone1 = c("1234","1234","1234","4567","4567","4567","4567","4567");phone1
sgroup1 = c("Jones","Jones","Jones","Smith","","Smith","Williams","Jones");sgroup1

DATA1 = data.frame(phone1,sgroup1)
</code>```

Note the "1234" since it originally had only 'Jones" and Blanks(NAs) assigned, so I assigned all records in that group to 'Jones. The second number (4567) had multiple names assigned, so I was unable to determine a common name so no assignment was made.

I can determine which phones have blank or non-blank name assignments, but I have been unable to determine how to assign them back to the blank records in that group.

```<code>Countdf1 <- DATA %>% count(phone,sgroup)
</code>```

答:
I think this does what you need.

We go through all unique phone numbers (a kind of "group by") and then check if there's more than 2 unique names associated or if there are no missing names at all. If there are only two unique names and one of them is missing, that's when we apply your rule number 1. Else, we don't do anything.

```<code>phone = c("1234","1234","1234","4567","4567","4567","4567","4567")
sgroup = c("","Jones","","Smith","","Smith","Williams","Jones")

DATA = data.frame(phone,sgroup);

for (phone in unique(DATA$phone)) {
    names <- unique(DATA$sgroup[DATA$phone == phone])
    if (length(names) > 2 || all(!names %in% c(NA, "", NULL))) {
        next
    } else {
        df <- DATA[DATA$phone == phone, ]
        df$sgroup <- names[!names %in% c(NA, "", NULL)]
        DATA[DATA$phone == phone, ] <- df
    }
}
</code>```

Body:
I have a series of phone numbers that have individual names associated with them.  The phone numbers are not necessarily unique, and sometimes the name associated with them is missing. I would like to fill in the names with the following rules:

If a grouped phone number has blank entries and only a single name available, I would like to replace the blank names with the one available.

If the grouped number has entries with multiple non-blank names, then I cannot determine who belongs to that phone number and so I make no changes.

Here is the original table:

library("dplyr")
phone = c("1234","1234","1234","4567","4567","4567","4567","4567");phone
sgroup = c("","Jones","","Smith","","Smith","Williams","Jones");sgroup

DATA = data.frame(phone,sgroup);DATA

And here is how I want it to look:

phone1 = c("1234","1234","1234","4567","4567","4567","4567","4567");phone1
sgroup1 = c("Jones","Jones","Jones","Smith","","Smith","Williams","Jones");sgroup1

DATA1 = data.frame(phone1,sgroup1)

Note the "1234" since it originally had only 'Jones" and Blanks(NAs) assigned, so I assigned all records in that group to 'Jones. The second number (4567) had multiple names assigned, so I was unable to determine a common name so no assignment was made.

I can determine which phones have blank or non-blank name assignments, but I have been unable to determine how to assign them back to the blank records in that group.

Countdf1 <- DATA %>% count(phone,sgroup)

Body:
I think this does what you need.

We go through all unique phone numbers (a kind of "group by") and then check if there's more than 2 unique names associated or if there are no missing names at all. If there are only two unique names and one of them is missing, that's when we apply your rule number 1. Else, we don't do anything.

phone = c("1234","1234","1234","4567","4567","4567","4567","4567")
sgroup = c("","Jones","","Smith","","Smith","Williams","Jones")

DATA = data.frame(phone,sgroup);

for (phone in unique(DATA$phone)) {
    names <- unique(DATA$sgroup[DATA$phone == phone])
    if (length(names) > 2 || all(!names %in% c(NA, "", NULL))) {
        next
    } else {
        df <- DATA[DATA$phone == phone, ]
        df$sgroup <- names[!names %in% c(NA, "", NULL)]
        DATA[DATA$phone == phone, ] <- df
    }
}


问:
How to Insert data in a single row of database of sqlite from different activites in android studio
I have made a helper class named baby

```<code>public class Baby {
    private int baby_id;
    private String baby_name;
    private String birthdate;
    private String gender;
    private String age;
    private String height;
    private String weight;
    private String sleep;
    private String medicate;

    public int getBaby_id() {
        return baby_id;
    }

    public void setBaby_id(int baby_id) {
        this.baby_id = baby_id;
    }

    public String getBaby_name() {
        return baby_name;
    }

    public void setBaby_name(String baby_name) {
        this.baby_name = baby_name;
    }

    public String getBirthdate() {
        return birthdate;
    }

    public void setBirthdate(String birthdate) {
        this.birthdate = birthdate;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public String getSleep() {
        return sleep;
    }

    public void setSleep(String sleep) {
        this.sleep = sleep;
    }

    public String getMedicate() {
        return medicate;
    }

    public void setMedicate(String medicate) {
        this.medicate = medicate;
    }
}
</code>```

and the database activity

```<code>private static final int DATABASE_VERSION = 10;
private static final String DATABASE_NAME = "BabyDetails.db";
private static final String TABLE_BABY = "baby";
private static final String COLUMN_BABY_ID = "baby_id";
private static final String COLUMN_BABY_NAME = "baby_name";
private static final String COLUMN_BABY_DATE = "birthdate";
private static final String COLUMN_BABY_GENDER = "gender";
private static final String COLUMN_BABY_AGE = "Age_group";
private static final String COLUMN_BABY_HEIGHT = "height";
private static final String COLUMN_BABY_WEIGHT = "weight";
private static final String COLUMN_BABY_SLEEP = "sleep";
private static final String COLUMN_BABY_MEDICATE = "medicate";

private String CREATE_BABY_TABLE = "CREATE TABLE "+ TABLE_BABY + "(" +
    COLUMN_BABY_ID + " INTEGER  PRIMARY KEY AUTOINCREMENT , " + COLUMN_BABY_NAME + " TEXT, "
    + COLUMN_BABY_DATE + " TEXT, " + COLUMN_BABY_GENDER + " TEXT, " + COLUMN_BABY_AGE + " TEXT, "
    +COLUMN_BABY_HEIGHT+ " TEXT, " + COLUMN_BABY_WEIGHT + " TEXT, " +COLUMN_BABY_SLEEP+ " TEXT, "
    +COLUMN_BABY_MEDICATE+ " TEXT " + ")";

private String DROP_BABY_TABLE = "DROP TABLE IF EXISTS " + TABLE_BABY;

public DbaseBaby( Context context) {
    super(context,DATABASE_NAME,null,DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(CREATE_BABY_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL(DROP_BABY_TABLE);
    onCreate(db);
}

public void addBaby(@NonNull Baby baby){
    SQLiteDatabase db= this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COLUMN_BABY_NAME,baby.getBaby_name());
    values.put(COLUMN_BABY_DATE,baby.getBirthdate());
    values.put(COLUMN_BABY_GENDER,baby.getGender());
    values.put(COLUMN_BABY_AGE,baby.getAge());
    values.put(COLUMN_BABY_HEIGHT,baby.getHeight());
    values.put(COLUMN_BABY_WEIGHT,baby.getWeight());
    values.put(COLUMN_BABY_SLEEP,baby.getSleep());
    values.put(COLUMN_BABY_MEDICATE,baby.getMedicate());
    db.insert(TABLE_BABY,null, values);
    db.close();
}

public Cursor getData(){
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.rawQuery(" SELECT * FROM " + TABLE_BABY , null );

    return cursor;
}
</code>```

and the Sign up activity from where I am insert name, birthdate, gender and age

```<code>try {
    baby.setBaby_name(et_baby.getText().toString());
    baby.setBirthdate(et_date.getText().toString());
    baby.setGender(radioButton.getText().toString());
    baby.setAge("0-3 years");
    dbaseBaby.addBaby(baby);
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

and the acivity from where I want to insert the height is

```<code>dbaseBaby = new DbaseBaby( Heightone.this);
baby = new Baby();
try {
    baby.setHeight(height.getText().toString()+ "cm");
    dbaseBaby.addBaby(baby);
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

But I am unable to insert the data in a single row instead, the data from the Sign up activity is stored in 1st row and the height from the height activity is stored in 2nd row rest of the columns are set to Null. Any idea where I am doing wrong.

答:
hello,

in first activity you are creating an object of baby and insert it to DB (without height attribute) in second activity again you are creating another object form baby and insert it to DB(this time just whit height attribute and others are null) actually you run two independent insert command for data-base!!(how should database understand you need add height attribute for last inserted object?)

solution:
in second activity you should Update  previously added record(in first activity) not add a new baby-item in DB (use id of last added item in first activity and update that row in second activity)

Edited:

every time you add new item to DB addBaby method return a long value as id of added item in table you need to catch it so this new addBaby() by yours in SQLiteOpenHelper class:

```<code> public Long addBaby(@NonNull Baby baby){
    SQLiteDatabase db= this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COLUMN_BABY_NAME,baby.getBaby_name());
    values.put(COLUMN_BABY_DATE,baby.getBirthdate());
    values.put(COLUMN_BABY_GENDER,baby.getGender());
    values.put(COLUMN_BABY_AGE,baby.getAge());
    values.put(COLUMN_BABY_HEIGHT,baby.getHeight());
    values.put(COLUMN_BABY_WEIGHT,baby.getWeight());
    values.put(COLUMN_BABY_SLEEP,baby.getSleep());
    values.put(COLUMN_BABY_MEDICATE,baby.getMedicate());
    Long id = db.insert(TABLE_BABY,null, values);
    db.close();
    return id;
}
</code>```

every time you add new baby to table catch returned id like this:

```<code>   try {
    baby.setBaby_name(et_baby.getText().toString());
    baby.setBirthdate(et_date.getText().toString());
    baby.setGender(radioButton.getText().toString());
    baby.setAge("0-3 years");
    Long id = dbaseBaby.addBaby(baby);
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

when navigate to second activity, put retrieved id in intent and send to next activity:

```<code> Intent intent = new Intent(this,SecondActivity.class);
 intent.putExtra("added_id",id);
 startActivity(intent);
</code>```

now add updateHeight method inside your SQLiteOpenHelper class :

```<code>public void updateHeight(Long id, String height) {
    sqLiteDatabase = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_BABY_HEIGHT,height);
    sqLiteDatabase.update(TableName, cv, "baby_id = ?", new String[]{String.valueOf(id)});

}
</code>```

and finally you can in second activity read id from intent and by this id , update last inserted row and add height attribute for that :

```<code>    dbaseBaby = new DbaseBaby(Heightone.this);
    baby = new Baby();
    Long id = getIntent().getLongExtra("added_id", 0);
    String height = "50cm";
    dbaseBaby.updateHeight(id, height);
</code>```

Body:
I have made a helper class named baby

public class Baby {
    private int baby_id;
    private String baby_name;
    private String birthdate;
    private String gender;
    private String age;
    private String height;
    private String weight;
    private String sleep;
    private String medicate;

    public int getBaby_id() {
        return baby_id;
    }

    public void setBaby_id(int baby_id) {
        this.baby_id = baby_id;
    }

    public String getBaby_name() {
        return baby_name;
    }

    public void setBaby_name(String baby_name) {
        this.baby_name = baby_name;
    }

    public String getBirthdate() {
        return birthdate;
    }

    public void setBirthdate(String birthdate) {
        this.birthdate = birthdate;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public String getSleep() {
        return sleep;
    }

    public void setSleep(String sleep) {
        this.sleep = sleep;
    }

    public String getMedicate() {
        return medicate;
    }

    public void setMedicate(String medicate) {
        this.medicate = medicate;
    }
}

and the database activity

private static final int DATABASE_VERSION = 10;
private static final String DATABASE_NAME = "BabyDetails.db";
private static final String TABLE_BABY = "baby";
private static final String COLUMN_BABY_ID = "baby_id";
private static final String COLUMN_BABY_NAME = "baby_name";
private static final String COLUMN_BABY_DATE = "birthdate";
private static final String COLUMN_BABY_GENDER = "gender";
private static final String COLUMN_BABY_AGE = "Age_group";
private static final String COLUMN_BABY_HEIGHT = "height";
private static final String COLUMN_BABY_WEIGHT = "weight";
private static final String COLUMN_BABY_SLEEP = "sleep";
private static final String COLUMN_BABY_MEDICATE = "medicate";

private String CREATE_BABY_TABLE = "CREATE TABLE "+ TABLE_BABY + "(" +
    COLUMN_BABY_ID + " INTEGER  PRIMARY KEY AUTOINCREMENT , " + COLUMN_BABY_NAME + " TEXT, "
    + COLUMN_BABY_DATE + " TEXT, " + COLUMN_BABY_GENDER + " TEXT, " + COLUMN_BABY_AGE + " TEXT, "
    +COLUMN_BABY_HEIGHT+ " TEXT, " + COLUMN_BABY_WEIGHT + " TEXT, " +COLUMN_BABY_SLEEP+ " TEXT, "
    +COLUMN_BABY_MEDICATE+ " TEXT " + ")";

private String DROP_BABY_TABLE = "DROP TABLE IF EXISTS " + TABLE_BABY;

public DbaseBaby( Context context) {
    super(context,DATABASE_NAME,null,DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(CREATE_BABY_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL(DROP_BABY_TABLE);
    onCreate(db);
}

public void addBaby(@NonNull Baby baby){
    SQLiteDatabase db= this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COLUMN_BABY_NAME,baby.getBaby_name());
    values.put(COLUMN_BABY_DATE,baby.getBirthdate());
    values.put(COLUMN_BABY_GENDER,baby.getGender());
    values.put(COLUMN_BABY_AGE,baby.getAge());
    values.put(COLUMN_BABY_HEIGHT,baby.getHeight());
    values.put(COLUMN_BABY_WEIGHT,baby.getWeight());
    values.put(COLUMN_BABY_SLEEP,baby.getSleep());
    values.put(COLUMN_BABY_MEDICATE,baby.getMedicate());
    db.insert(TABLE_BABY,null, values);
    db.close();
}

public Cursor getData(){
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.rawQuery(" SELECT * FROM " + TABLE_BABY , null );

    return cursor;
}

and the Sign up activity from where I am insert name, birthdate, gender and age

try {
    baby.setBaby_name(et_baby.getText().toString());
    baby.setBirthdate(et_date.getText().toString());
    baby.setGender(radioButton.getText().toString());
    baby.setAge("0-3 years");
    dbaseBaby.addBaby(baby);
} catch (Exception e) {
    e.printStackTrace();
}

and the acivity from where I want to insert the height is

dbaseBaby = new DbaseBaby( Heightone.this);
baby = new Baby();
try {
    baby.setHeight(height.getText().toString()+ "cm");
    dbaseBaby.addBaby(baby);
} catch (Exception e) {
    e.printStackTrace();
}

But I am unable to insert the data in a single row instead, the data from the Sign up activity is stored in 1st row and the height from the height activity is stored in 2nd row rest of the columns are set to Null. Any idea where I am doing wrong.

Body:
hello,

in first activity you are creating an object of baby and insert it to DB (without height attribute) in second activity again you are creating another object form baby and insert it to DB(this time just whit height attribute and others are null) actually you run two independent insert command for data-base!!(how should database understand you need add height attribute for last inserted object?)

solution:
in second activity you should Update  previously added record(in first activity) not add a new baby-item in DB (use id of last added item in first activity and update that row in second activity)

Edited:

every time you add new item to DB addBaby method return a long value as id of added item in table you need to catch it so this new addBaby() by yours in SQLiteOpenHelper class:

 public Long addBaby(@NonNull Baby baby){
    SQLiteDatabase db= this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COLUMN_BABY_NAME,baby.getBaby_name());
    values.put(COLUMN_BABY_DATE,baby.getBirthdate());
    values.put(COLUMN_BABY_GENDER,baby.getGender());
    values.put(COLUMN_BABY_AGE,baby.getAge());
    values.put(COLUMN_BABY_HEIGHT,baby.getHeight());
    values.put(COLUMN_BABY_WEIGHT,baby.getWeight());
    values.put(COLUMN_BABY_SLEEP,baby.getSleep());
    values.put(COLUMN_BABY_MEDICATE,baby.getMedicate());
    Long id = db.insert(TABLE_BABY,null, values);
    db.close();
    return id;
}

every time you add new baby to table catch returned id like this:

   try {
    baby.setBaby_name(et_baby.getText().toString());
    baby.setBirthdate(et_date.getText().toString());
    baby.setGender(radioButton.getText().toString());
    baby.setAge("0-3 years");
    Long id = dbaseBaby.addBaby(baby);
} catch (Exception e) {
    e.printStackTrace();
}

when navigate to second activity, put retrieved id in intent and send to next activity:

 Intent intent = new Intent(this,SecondActivity.class);
 intent.putExtra("added_id",id);
 startActivity(intent);

now add updateHeight method inside your SQLiteOpenHelper class :

public void updateHeight(Long id, String height) {
    sqLiteDatabase = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_BABY_HEIGHT,height);
    sqLiteDatabase.update(TableName, cv, "baby_id = ?", new String[]{String.valueOf(id)});

}

and finally you can in second activity read id from intent and by this id , update last inserted row and add height attribute for that :

    dbaseBaby = new DbaseBaby(Heightone.this);
    baby = new Baby();
    Long id = getIntent().getLongExtra("added_id", 0);
    String height = "50cm";
    dbaseBaby.updateHeight(id, height);


问:
A C program process is waited by some OS routine?
Well, I'm learning about processes using the C language, and I have seen that when you call the exit function a process is terminated and without waiting for it, it will become a zombie process. My question is, if the first process created when executing the program is a process itself, is there a 0S routine that wait for it after an exit() call, avoiding that it becomes a zombie process? I'm curious about it.</p>

答:
On Linux, the top most (parent) process is init. This is the only process, which has no parent. Any other process (without any exception) do have a parent and hence is a child of another process.

See:

init

Section NOTES on wait

A child that terminates, but has not been waited for becomes a
"zombie".  The kernel maintains a minimal set of information
about the zombie process (PID, termination status, resource usage
information) in order to allow the parent to later perform a wait
to obtain information about the child.  As long as a zombie is
not removed from the system via a wait, it will consume a slot in
the kernel process table, and if this table fills, it will not be
possible to create further processes.  If a parent process
terminates, then its "zombie" children (if any) are adopted by
init(1), ... init(1) automatically performs a wait to remove the
zombies.


问:
How do I install libXSLT for Perl's XML::LibXSLT?
When I run a Perl script I get

```
    Can't locate XML/LibXSLT.pm in @INC
```

So I try doing this in cpan:

```

cpan> install XML::LibXSLT
CPAN: Storable loaded ok
Going to read /root/.cpan/Metadata
  Database was generated on Fri, 02 Oct 2009 13:28:24 GMT
Running install for module XML::LibXSLT
Running make for P/PA/PAJAS/XML-LibXSLT-1.68.tar.gz
CPAN: Digest::MD5 loaded ok
CPAN: Compress::Zlib loaded ok
Checksum for /root/.cpan/sources/authors/id/P/PA/PAJAS/XML-LibXSLT-1.68.tar.gz ok
Scanning cache /root/.cpan/build for sizes
XML-LibXSLT-1.68/
XML-LibXSLT-1.68/perl-libxml-mm.h
XML-LibXSLT-1.68/t/
XML-LibXSLT-1.68/t/08literal.t
XML-LibXSLT-1.68/t/09exslt.t
XML-LibXSLT-1.68/t/02dromeds.t
XML-LibXSLT-1.68/t/01basic.t
XML-LibXSLT-1.68/t/14security.t
XML-LibXSLT-1.68/t/12import.t
XML-LibXSLT-1.68/t/05quick.t
XML-LibXSLT-1.68/t/03input.t
XML-LibXSLT-1.68/t/13error.t
XML-LibXSLT-1.68/t/11utf8.t
XML-LibXSLT-1.68/t/04params.t
XML-LibXSLT-1.68/t/06entities.t
XML-LibXSLT-1.68/t/06output.t
XML-LibXSLT-1.68/t/07blankdoc.t
XML-LibXSLT-1.68/t/10functions.t
XML-LibXSLT-1.68/testcases/
XML-LibXSLT-1.68/testcases/default.conf
XML-LibXSLT-1.68/Changes
XML-LibXSLT-1.68/example/
XML-LibXSLT-1.68/example/1.xsl
XML-LibXSLT-1.68/example/2.xsl
XML-LibXSLT-1.68/example/fatal.xsl
XML-LibXSLT-1.68/example/nonfatal.xsl
XML-LibXSLT-1.68/example/bad1.xsl
XML-LibXSLT-1.68/example/1.xml
XML-LibXSLT-1.68/example/bad3.xsl
XML-LibXSLT-1.68/example/bad2.xsl
XML-LibXSLT-1.68/example/2.xml
XML-LibXSLT-1.68/MANIFEST
XML-LibXSLT-1.68/typemap
XML-LibXSLT-1.68/Driver/
XML-LibXSLT-1.68/Driver/LibXSLT.pm
XML-LibXSLT-1.68/Driver/Sablotron.pm
XML-LibXSLT-1.68/Driver/BaseClass.pm
XML-LibXSLT-1.68/perl-libxml-mm.c
XML-LibXSLT-1.68/LibXSLT.pm
XML-LibXSLT-1.68/benchmark.pl
XML-LibXSLT-1.68/ppport.h
XML-LibXSLT-1.68/LibXSLT.xs
XML-LibXSLT-1.68/Makefile.PL
XML-LibXSLT-1.68/README
XML-LibXSLT-1.68/META.yml
Removing previously used /root/.cpan/build/XML-LibXSLT-1.68

  CPAN.pm: Going to build P/PA/PAJAS/XML-LibXSLT-1.68.tar.gz

running xslt-config... failed
using fallback values for LIBS and INC
options:
  LIBS='-L/usr/local/lib -L/usr/lib -lxslt -lxml2 -lz -lm'
  INC='-I/usr/local/include -I/usr/include'
If this is wrong, Re-run as:
  $ /usr/bin/perl Makefile.PL LIBS='-L/path/to/lib' INC='-I/path/to/include'

looking for -lxslt... no
libxslt not found
Try setting LIBS and INC values on the command line
Or get libxslt and libxml2 from
  http://www.libxml.org/
If you install via RPMs, make sure you also install the -devel
RPMs, as this is where the headers (.h files) are.
make: *** No targets specified and no makefile found.  Stop.
  /usr/bin/make  -- NOT OK
Running make test
  Can't test without successful make
Running make install
  make had returned bad status, install seems impossible
```

So... no luck. I tried writing cpan> install XML::XSLT which installed but my script still doesn't work. What can I do now?

I also tried using YaST to install the packages. It was a success, then I tried the above and still no luck.

-extra-

I also tried building the bindings. From http://cpan.uwinnipeg.ca/dist/XML-LibXSLT I untar and wrote

```
    # perl Makefile.PL
    running xslt-config... failed
    using fallback values for LIBS and INC
    options:
      LIBS='-L/usr/local/lib -L/usr/lib -lxslt -lxml2 -lz -lm'
      INC='-I/usr/local/include -I/usr/include'
    If this is wrong, Re-run as:
      $ /usr/bin/perl Makefile.PL LIBS='-L/path/to/lib' INC='-I/path/to/include'

    looking for -lxslt... no
    libxslt not found
    Try setting LIBS and INC values on the command line
    Or get libxslt and libxml2 from
      http://www.libxml.org/
    If you install via RPMs, make sure you also install the -devel
    RPMs, as this is where the headers (.h files) are.
```

答:
on ubuntu try </p>

```<code>sudo apt-get install libxml-libxslt-perl
</code>```

Body:
When I run a Perl script I get

    Can't locate XML/LibXSLT.pm in @INC

So I try doing this in cpan:

cpan> install XML::LibXSLT
CPAN: Storable loaded ok
Going to read /root/.cpan/Metadata
  Database was generated on Fri, 02 Oct 2009 13:28:24 GMT
Running install for module XML::LibXSLT
Running make for P/PA/PAJAS/XML-LibXSLT-1.68.tar.gz
CPAN: Digest::MD5 loaded ok
CPAN: Compress::Zlib loaded ok
Checksum for /root/.cpan/sources/authors/id/P/PA/PAJAS/XML-LibXSLT-1.68.tar.gz ok
Scanning cache /root/.cpan/build for sizes
XML-LibXSLT-1.68/
XML-LibXSLT-1.68/perl-libxml-mm.h
XML-LibXSLT-1.68/t/
XML-LibXSLT-1.68/t/08literal.t
XML-LibXSLT-1.68/t/09exslt.t
XML-LibXSLT-1.68/t/02dromeds.t
XML-LibXSLT-1.68/t/01basic.t
XML-LibXSLT-1.68/t/14security.t
XML-LibXSLT-1.68/t/12import.t
XML-LibXSLT-1.68/t/05quick.t
XML-LibXSLT-1.68/t/03input.t
XML-LibXSLT-1.68/t/13error.t
XML-LibXSLT-1.68/t/11utf8.t
XML-LibXSLT-1.68/t/04params.t
XML-LibXSLT-1.68/t/06entities.t
XML-LibXSLT-1.68/t/06output.t
XML-LibXSLT-1.68/t/07blankdoc.t
XML-LibXSLT-1.68/t/10functions.t
XML-LibXSLT-1.68/testcases/
XML-LibXSLT-1.68/testcases/default.conf
XML-LibXSLT-1.68/Changes
XML-LibXSLT-1.68/example/
XML-LibXSLT-1.68/example/1.xsl
XML-LibXSLT-1.68/example/2.xsl
XML-LibXSLT-1.68/example/fatal.xsl
XML-LibXSLT-1.68/example/nonfatal.xsl
XML-LibXSLT-1.68/example/bad1.xsl
XML-LibXSLT-1.68/example/1.xml
XML-LibXSLT-1.68/example/bad3.xsl
XML-LibXSLT-1.68/example/bad2.xsl
XML-LibXSLT-1.68/example/2.xml
XML-LibXSLT-1.68/MANIFEST
XML-LibXSLT-1.68/typemap
XML-LibXSLT-1.68/Driver/
XML-LibXSLT-1.68/Driver/LibXSLT.pm
XML-LibXSLT-1.68/Driver/Sablotron.pm
XML-LibXSLT-1.68/Driver/BaseClass.pm
XML-LibXSLT-1.68/perl-libxml-mm.c
XML-LibXSLT-1.68/LibXSLT.pm
XML-LibXSLT-1.68/benchmark.pl
XML-LibXSLT-1.68/ppport.h
XML-LibXSLT-1.68/LibXSLT.xs
XML-LibXSLT-1.68/Makefile.PL
XML-LibXSLT-1.68/README
XML-LibXSLT-1.68/META.yml
Removing previously used /root/.cpan/build/XML-LibXSLT-1.68

  CPAN.pm: Going to build P/PA/PAJAS/XML-LibXSLT-1.68.tar.gz

running xslt-config... failed
using fallback values for LIBS and INC
options:
  LIBS='-L/usr/local/lib -L/usr/lib -lxslt -lxml2 -lz -lm'
  INC='-I/usr/local/include -I/usr/include'
If this is wrong, Re-run as:
  $ /usr/bin/perl Makefile.PL LIBS='-L/path/to/lib' INC='-I/path/to/include'

looking for -lxslt... no
libxslt not found
Try setting LIBS and INC values on the command line
Or get libxslt and libxml2 from
  http://www.libxml.org/
If you install via RPMs, make sure you also install the -devel
RPMs, as this is where the headers (.h files) are.
make: *** No targets specified and no makefile found.  Stop.
  /usr/bin/make  -- NOT OK
Running make test
  Can't test without successful make
Running make install
  make had returned bad status, install seems impossible

So... no luck. I tried writing cpan> install XML::XSLT which installed but my script still doesn't work. What can I do now?

I also tried using YaST to install the packages. It was a success, then I tried the above and still no luck.

-extra-

I also tried building the bindings. From http://cpan.uwinnipeg.ca/dist/XML-LibXSLT I untar and wrote

    # perl Makefile.PL
    running xslt-config... failed
    using fallback values for LIBS and INC
    options:
      LIBS='-L/usr/local/lib -L/usr/lib -lxslt -lxml2 -lz -lm'
      INC='-I/usr/local/include -I/usr/include'
    If this is wrong, Re-run as:
      $ /usr/bin/perl Makefile.PL LIBS='-L/path/to/lib' INC='-I/path/to/include'

    looking for -lxslt... no
    libxslt not found
    Try setting LIBS and INC values on the command line
    Or get libxslt and libxml2 from
      http://www.libxml.org/
    If you install via RPMs, make sure you also install the -devel
    RPMs, as this is where the headers (.h files) are.

Body:
on ubuntu try

sudo apt-get install libxml-libxslt-perl


问:
Azure Search - Accent insensitive analyzer not working when sorting
I'm using Azure Search. I have a model with a property with this attributes

```<code>[IsRetrievable(true), IsSearchable, IsSortable, Analyzer("standardasciifolding.lucene")]
public string Title { get; set; }
</code>```

I want the search to be accent insensitive. Although it is working when searching/filtering, it is not working when sorting the results. So, If I have words that start with an accent and I sort alphabetically, those results appear at the end of the list.

答:
There is a new feature that allows you to enable normalization while filtering. Please check out the Text normalization for case-insensitive filtering, faceting and sorting feature that's in Preview.

You can update your index to use this "normalizer" feature for the fields in which you'd like case-insensitive order-by operations.

You don't need a separate field TitleNormalized anymore. You can add "normalizer": "standard" to the Title field, and  $orderBy=Title will sort in the order you'd like, ignoring casing and accents.

The "standard" normalizer is pre-defined. If you'd like other filters to be applied, please look at predefined and custom normalizers

"index": {
    "name": "your-name-here",
    "fields": [
        {"name": "Title", "type": "Edm.String", "filterable": true, "sortable": true, "facetable": false, "searchable": true, "normalizer":"standard"}
    ]
}
```

Body:
I'm using Azure Search. I have a model with a property with this attributes

[IsRetrievable(true), IsSearchable, IsSortable, Analyzer("standardasciifolding.lucene")]
public string Title { get; set; }

I want the search to be accent insensitive. Although it is working when searching/filtering, it is not working when sorting the results. So, If I have words that start with an accent and I sort alphabetically, those results appear at the end of the list.


问:
FIWARE : Errors when dealing with Locale caracters (french for instance) as Payload
I am currently testing some SmartDataModels (SmartDestination/Events), and when I try to add an entity in which the description contains some french caracters like "é" or "à", the Orion CB rejects my payload with the following error message :

entityCreate009 400 Bad Request {"error":"BadRequest","description":"Invalid characters in attribute value"}

... because it contains an "é"

The tested JSON payload (NGSI v2) is this one : https://raw.githubusercontent.com/smart-data-models/dataModel.TourismDestinations/2ab2bac0fae5893ba4310714823e293c9030f8c1/Event/examples/example.json

Do I need to provide specific option in order to deal with Locale caracters ?

Many thanks in advance for your help
Rgds
Laurent

答:
Some characters are not allowed in attribute value in order to avoid script injections attack in some circumstances. The set of forbidden characters is described in Orion documentation.

Note "é" or "à" are not in this list, but probably you are using some other that is forbidden and you are getting the error due to this reason.

You can use attribute type TextUnrestricted to avoid this Orion protection mechanism. But use it at your own risk! ;)


问:
Find duplicated value with different time index
I'm new to pandas and would like to check if there are more efficient way to do what I would like to achieve.

I have a customer master data change log for 12 months looks like below (the full file have 150K rows and 15 columns)

date1
changed_by
customer
field_name

23/02/2021 18:59
101852
40001375
Industry

23/02/2021 18:59
101852
40001375
Industry code 1

23/02/2021 18:59
101852
40001375
Region

30/12/2021 02:31
119186
30045194
Postal Code

30/12/2021 02:31
119186
30045194
Industry code 1

30/12/2021 02:31
119186
30045194
Region

30/01/2021 03:31
109209
40001375
Postal Code

30/01/2021 03:31
109209
40001375
Industry code 1

30/01/2021 03:31
109209
40001375
Bank

I would like to check if there are any customers' data being change more than once within the period, i.e. same customer ID but different date, then extract those line for further analysis.

Below are the code I currently have and seems work ok.

```<code>pvz = df3.groupby(['date1','customer'])['field_name'].count().reset_index()
pvz
</code>```

Gives me

date1
customer
field_name

23/02/2021 18:59
40001375
3

30/01/2021 03:31
40001375
3

30/12/2021 02:31
30045194
3

Then I:

```<code>pvz[pvz.duplicated(subset='customer',keep=False)]
</code>```

Return the below that seems ok:

date1
customer
field_name

23/02/2021 18:59
40001375
3

30/01/2021 03:31
40001375
3

As a beginner I would like to check

if there are any suggestions on my code and if there are more efficient way to do what I would like to achieve

I thought of set the date column to datetime index. But I do not know how to handle it afterward, and whether it would make my task any easier ?

Thank you.

答:
You can reduce it to one line by doing the following:

Using as_index=False in your groupby call instead of using reset_index()

Passing a lambda function to .loc

```<code>filtered = df.groupby(['date1','customer'], as_index=False)['field_name'].count().loc[lambda x: x.duplicated(subset='customer',keep=False)]
</code>```

Output:

```<code>>>> filtered
              date1  customer  field_name
0  23/02/2021 18:59  40001375           3
1  30/01/2021 03:31  40001375           3
</code>```

Body:
I'm new to pandas and would like to check if there are more efficient way to do what I would like to achieve.

I have a customer master data change log for 12 months looks like below (the full file have 150K rows and 15 columns)

date1
changed_by
customer
field_name

23/02/2021 18:59
101852
40001375
Industry

23/02/2021 18:59
101852
40001375
Industry code 1

23/02/2021 18:59
101852
40001375
Region

30/12/2021 02:31
119186
30045194
Postal Code

30/12/2021 02:31
119186
30045194
Industry code 1

30/12/2021 02:31
119186
30045194
Region

30/01/2021 03:31
109209
40001375
Postal Code

30/01/2021 03:31
109209
40001375
Industry code 1

30/01/2021 03:31
109209
40001375
Bank

I would like to check if there are any customers' data being change more than once within the period, i.e. same customer ID but different date, then extract those line for further analysis.

Below are the code I currently have and seems work ok.

pvz = df3.groupby(['date1','customer'])['field_name'].count().reset_index()
pvz

Gives me

date1
customer
field_name

23/02/2021 18:59
40001375
3

30/01/2021 03:31
40001375
3

30/12/2021 02:31
30045194
3

Then I:

pvz[pvz.duplicated(subset='customer',keep=False)]

Return the below that seems ok:

date1
customer
field_name

23/02/2021 18:59
40001375
3

30/01/2021 03:31
40001375
3

As a beginner I would like to check

if there are any suggestions on my code and if there are more efficient way to do what I would like to achieve

I thought of set the date column to datetime index. But I do not know how to handle it afterward, and whether it would make my task any easier ?

Thank you.

Body:
You can reduce it to one line by doing the following:

Using as_index=False in your groupby call instead of using reset_index()

Passing a lambda function to .loc

filtered = df.groupby(['date1','customer'], as_index=False)['field_name'].count().loc[lambda x: x.duplicated(subset='customer',keep=False)]

Output:

>>> filtered
              date1  customer  field_name
0  23/02/2021 18:59  40001375           3
1  30/01/2021 03:31  40001375           3