问:
How to hide/display specific RecyclerView item?
I have a contacts list RecyclerView, where the first item (position 0) holds the user's details. When the search icon in the toolbar is pressed, I want that entry to be hidden from the user.

I've tried using setVisibility(View.GONE) on it, and, although the entry is hidden, the space it occupied was still there, much like setting setVisibility(View.INVISIBLE). How can I toggle the visibility of this specific entry to VISIBLE/GONE in my RecyclerView, or how can I set its height only to 0dp?

EDIT:

My xml is quite simple, it comprises of simply a recyclerView and a FAB. My adapter code is as below.

```<code>ContactsAdapter(
            Context context,
            List<LinphoneContact> contactsList,
            ContactViewHolder.ClickListener clickListener,
            SelectableHelper helper) {
        super(helper);
        mContext = context;
        updateDataSet(contactsList);
        mClickListener = clickListener;
    }

    @NonNull
    @Override
    public ContactViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        // For the first position only, use the user's own contact card
        // For all the rest, use the contact card
        switch (viewType) {
            case USER_CARD_VIEW:
                View userCard =
                        LayoutInflater.from(parent.getContext())
                                .inflate(R.layout.contacts_user_card, parent, false);
                return new ContactViewHolder(userCard, mClickListener);
            case CONTACT_CARD_VIEW:
                View contactCard =
                        LayoutInflater.from(parent.getContext())
                                .inflate(R.layout.contact_cell, parent, false);
                return new ContactViewHolder(contactCard, mClickListener);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {

        // Remove the user's card when searching contacts - DOES NOT WORK, MAKES ALL FIRST ITEMS
        // INVISIBLE
        //        if (position == 0) {
        //            if (mIsSearchMode) holder.itemView.setVisibility(View.GONE);
        //            else holder.itemView.setVisibility(View.VISIBLE);
        //        }

        if (position != 0) {

            LinphoneContact contact = (LinphoneContact) getItem(position - 1);

            holder.name.setText(contact.getFullName());

            if (!mIsSearchMode) {
                String fullName = contact.getFullName();
                if (fullName != null && !fullName.isEmpty()) {
                    holder.separatorText.setText(String.valueOf(fullName.charAt(0)));
                }
            }

            // Separator as in the big capital letter on the left to indicate sections
            holder.separator.setVisibility(
                    mIsSearchMode
                                    || (getPositionForSection(getSectionForPosition(position))
                                            != position)
                            ? View.GONE
                            : View.VISIBLE);

            holder.linphoneFriend.setVisibility(
                    contact.isInFriendList() ? View.VISIBLE : View.GONE);

            ContactAvatar.displayAvatar(contact, holder.avatarLayout);

            boolean isOrgVisible = LinphonePreferences.instance().isDisplayContactOrganization();
            String org = contact.getOrganization();
            if (org != null && !org.isEmpty() && isOrgVisible) {
                holder.organization.setText(org);
                holder.organization.setVisibility(View.VISIBLE);
            } else {
                holder.organization.setVisibility(View.GONE);
            }

            holder.delete.setVisibility(isEditionEnabled() ? View.VISIBLE : View.INVISIBLE);
            holder.delete.setChecked(isSelected(position));
            //        } else {
            //            // TODO - user's card should have whole and voicemail onClick listeners
        }

        //        Log.d("contactsAdapter", "Position: " + position);
        //        Log.d("contactsAdapter", "Section for position: " +
        // getSectionForPosition(position));
        //        Log.d(
        //                "contactsAdapter",
        //                "The other thingy: " +
        // getPositionForSection(getSectionForPosition(position)));
    }

    // +1 item count to account for user's contact card
    @Override
    public int getItemCount() {
        return mContacts.size() + 1;
    }

    public Object getItem(int position) {
        if (position >= getItemCount()) return null;
        return mContacts.get(position);
    }

    public void setIsSearchMode(boolean set) {
        mIsSearchMode = set;
    }

    [...]

    @Override
    public int getItemViewType(int position) {
        return position == 0 ? USER_CARD_VIEW : CONTACT_CARD_VIEW;
    }

</code>```

Essentially, I don't add the first item to my list of items, but instead I add it to the recyclerView, and shift my list of items by one position up.

答:
although the entry is hidden, the space it occupied was still there

may be because you are hiding the child but its parent is still there with its height or padding given

How can I toggle the visibility of this specific entry to VISIBLE/GONE in my RecyclerView

Toggle the visibility of parent

In your onBindViewHolder

```<code> @Override
public void onBindViewHolder(@NonNull MyViewHolder viewHolder, int i) {

    if (isButtonPressed) {
        viewHolder.parentViewId.setVisibility(View.GONE);
    }else {
        viewHolder.parentViewId.setVisibility(View.VISIBLE);
    }
}
</code>```

Create a public boolean isButtonPressed; and when you press the button make it true and call adapter.notifyDataSetChanged();

Body:
I have a contacts list RecyclerView, where the first item (position 0) holds the user's details. When the search icon in the toolbar is pressed, I want that entry to be hidden from the user.

I've tried using setVisibility(View.GONE) on it, and, although the entry is hidden, the space it occupied was still there, much like setting setVisibility(View.INVISIBLE). How can I toggle the visibility of this specific entry to VISIBLE/GONE in my RecyclerView, or how can I set its height only to 0dp?

EDIT:

My xml is quite simple, it comprises of simply a recyclerView and a FAB. My adapter code is as below.

ContactsAdapter(
            Context context,
            List<LinphoneContact> contactsList,
            ContactViewHolder.ClickListener clickListener,
            SelectableHelper helper) {
        super(helper);
        mContext = context;
        updateDataSet(contactsList);
        mClickListener = clickListener;
    }

    @NonNull
    @Override
    public ContactViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        // For the first position only, use the user's own contact card
        // For all the rest, use the contact card
        switch (viewType) {
            case USER_CARD_VIEW:
                View userCard =
                        LayoutInflater.from(parent.getContext())
                                .inflate(R.layout.contacts_user_card, parent, false);
                return new ContactViewHolder(userCard, mClickListener);
            case CONTACT_CARD_VIEW:
                View contactCard =
                        LayoutInflater.from(parent.getContext())
                                .inflate(R.layout.contact_cell, parent, false);
                return new ContactViewHolder(contactCard, mClickListener);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {

        // Remove the user's card when searching contacts - DOES NOT WORK, MAKES ALL FIRST ITEMS
        // INVISIBLE
        //        if (position == 0) {
        //            if (mIsSearchMode) holder.itemView.setVisibility(View.GONE);
        //            else holder.itemView.setVisibility(View.VISIBLE);
        //        }

        if (position != 0) {

            LinphoneContact contact = (LinphoneContact) getItem(position - 1);

            holder.name.setText(contact.getFullName());

            if (!mIsSearchMode) {
                String fullName = contact.getFullName();
                if (fullName != null && !fullName.isEmpty()) {
                    holder.separatorText.setText(String.valueOf(fullName.charAt(0)));
                }
            }

            // Separator as in the big capital letter on the left to indicate sections
            holder.separator.setVisibility(
                    mIsSearchMode
                                    || (getPositionForSection(getSectionForPosition(position))
                                            != position)
                            ? View.GONE
                            : View.VISIBLE);

            holder.linphoneFriend.setVisibility(
                    contact.isInFriendList() ? View.VISIBLE : View.GONE);

            ContactAvatar.displayAvatar(contact, holder.avatarLayout);

            boolean isOrgVisible = LinphonePreferences.instance().isDisplayContactOrganization();
            String org = contact.getOrganization();
            if (org != null && !org.isEmpty() && isOrgVisible) {
                holder.organization.setText(org);
                holder.organization.setVisibility(View.VISIBLE);
            } else {
                holder.organization.setVisibility(View.GONE);
            }

            holder.delete.setVisibility(isEditionEnabled() ? View.VISIBLE : View.INVISIBLE);
            holder.delete.setChecked(isSelected(position));
            //        } else {
            //            // TODO - user's card should have whole and voicemail onClick listeners
        }

        //        Log.d("contactsAdapter", "Position: " + position);
        //        Log.d("contactsAdapter", "Section for position: " +
        // getSectionForPosition(position));
        //        Log.d(
        //                "contactsAdapter",
        //                "The other thingy: " +
        // getPositionForSection(getSectionForPosition(position)));
    }

    // +1 item count to account for user's contact card
    @Override
    public int getItemCount() {
        return mContacts.size() + 1;
    }

    public Object getItem(int position) {
        if (position >= getItemCount()) return null;
        return mContacts.get(position);
    }

    public void setIsSearchMode(boolean set) {
        mIsSearchMode = set;
    }

    [...]

    @Override
    public int getItemViewType(int position) {
        return position == 0 ? USER_CARD_VIEW : CONTACT_CARD_VIEW;
    }

Essentially, I don't add the first item to my list of items, but instead I add it to the recyclerView, and shift my list of items by one position up.

Body:
although the entry is hidden, the space it occupied was still there

may be because you are hiding the child but its parent is still there with its height or padding given

How can I toggle the visibility of this specific entry to VISIBLE/GONE in my RecyclerView

Toggle the visibility of parent

In your onBindViewHolder

 @Override
public void onBindViewHolder(@NonNull MyViewHolder viewHolder, int i) {

    if (isButtonPressed) {
        viewHolder.parentViewId.setVisibility(View.GONE);
    }else {
        viewHolder.parentViewId.setVisibility(View.VISIBLE);
    }
}

Create a public boolean isButtonPressed; and when you press the button make it true and call adapter.notifyDataSetChanged();


来源: stackexchange

问:
How to make Firefox accept insecure SSL certs and doesn't show message about "Potential Security Risk Ahead'
I'm trying to access a page with Selenium that has a basic authentication prompt when accessed (a internal system) with a URL that uses HTTPS.

I wrote the following code...

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

PATH_TO_FIREFOX_DRIVER = r'C:\Users\MyUser\PycharmProjects\some-project\drivers\geckodriver.exe'
MY_INTERNAL_HTTPS_PAGE_WITH_BASIC_AUTHENTICATION = 'https://example.com'

USERNAME = 'user'
PASSWORD = 'pass'

ff_profile = FirefoxProfile()

#trying to set Firefox to accept unsecure SSL Certs
ff_profile.accept_untrusted_certs = True
ff_profile.assume_untrusted_cert_issuer = False

driver = webdriver.Firefox(executable_path=PATH_TO_FIREFOX_DRIVER,
                       firefox_profile=ff_profile)

driver.get(MY_INTERNAL_HTTPS_PAGE_WITH_BASIC_AUTHENTICATION)

w_basicauth = driver.switch_to.alert.send_keys(USERNAME + Keys().TAB + PASSWORD + Keys().ENTER)`
</code>```

When I run, the script correctly fills the basic authentication prompt with username and password. But althought I have tried to set Firefox profile to accept untrusted SSL Certificates, Firefox still shows that message "Warning: Potential Security Risk Ahead".

How could I do to Firefox doesn't show that message? What am I doing wrong?

I'm using Firefox 66.0.3 (64-bit) and selenium 3.141.0.

Thanks!

答:
It works (with Chrome):</p>

```<code>import os
import unittest
import pprint
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

class testMyApp(unittest.TestCase):

    def setUp(self):
        dir = os.path.dirname(__file__)
        chrome_driver_path = dir + "chromedriver"

        options = webdriver.ChromeOptions()
        options.add_argument('--ignore-certificate-errors')

        self.driver = webdriver.Chrome(chrome_driver_path,chrome_options=options)
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()

[...]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to access a page with Selenium that has a basic authentication prompt when accessed (a internal system) with a URL that uses HTTPS.

I wrote the following code...

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

PATH_TO_FIREFOX_DRIVER = r'C:\Users\MyUser\PycharmProjects\some-project\drivers\geckodriver.exe'
MY_INTERNAL_HTTPS_PAGE_WITH_BASIC_AUTHENTICATION = 'https://example.com'

USERNAME = 'user'
PASSWORD = 'pass'

ff_profile = FirefoxProfile()

#trying to set Firefox to accept unsecure SSL Certs
ff_profile.accept_untrusted_certs = True
ff_profile.assume_untrusted_cert_issuer = False

driver = webdriver.Firefox(executable_path=PATH_TO_FIREFOX_DRIVER,
                       firefox_profile=ff_profile)

driver.get(MY_INTERNAL_HTTPS_PAGE_WITH_BASIC_AUTHENTICATION)

w_basicauth = driver.switch_to.alert.send_keys(USERNAME + Keys().TAB + PASSWORD + Keys().ENTER)`

When I run, the script correctly fills the basic authentication prompt with username and password. But althought I have tried to set Firefox profile to accept untrusted SSL Certificates, Firefox still shows that message "Warning: Potential Security Risk Ahead".

How could I do to Firefox doesn't show that message? What am I doing wrong?

I'm using Firefox 66.0.3 (64-bit) and selenium 3.141.0.

Thanks!

Body:
It works (with Chrome):

import os
import unittest
import pprint
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

class testMyApp(unittest.TestCase):

    def setUp(self):
        dir = os.path.dirname(__file__)
        chrome_driver_path = dir + "chromedriver"

        options = webdriver.ChromeOptions()
        options.add_argument('--ignore-certificate-errors')

        self.driver = webdriver.Chrome(chrome_driver_path,chrome_options=options)
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()

[...]


问:
How to copy a generic list with Eclipse EMF?
how can i split an Elist to two Elists without getting the NullPointerException. I already tried EcoreUtil.copy() / Collections.copy. The Problem seems that when declaring the copy target List it needs to be initialized with = null; I also tried using an Iterator to copy Elements and tried adding them with .set() .add() all exit with the Exception above. The declaration of the target List seems to be working only with an allocation. While debugging i clearly see that the copied object in the List is not null.

```<code> EList<RtTask> tasks = rtModule.getTasks();
 EList<RtModuleInvocation> invoc0 = null; //target List
        for (RtTask rtTask : tasks) {
            EList<RtModuleInvocation> invocations = rtTask.getModuleInvocations(); //src List
</code>```

Thanks.

答:
Thanks to https://www.programcreek.com/java-api-examples/emf i found out the correct way to initialize my Elist with a constructor that Creates an empty instance with no initial capacity.The data storage will be null. and HOP it works.</p>

```<code>EList<RtModuleInvocation> invoc0 = new BasicEList<>();
</code>```

Body:
how can i split an Elist to two Elists without getting the NullPointerException. I already tried EcoreUtil.copy() / Collections.copy. The Problem seems that when declaring the copy target List it needs to be initialized with = null; I also tried using an Iterator to copy Elements and tried adding them with .set() .add() all exit with the Exception above. The declaration of the target List seems to be working only with an allocation. While debugging i clearly see that the copied object in the List is not null.

 EList<RtTask> tasks = rtModule.getTasks();
 EList<RtModuleInvocation> invoc0 = null; //target List
        for (RtTask rtTask : tasks) {
            EList<RtModuleInvocation> invocations = rtTask.getModuleInvocations(); //src List

Thanks.

Body:
Thanks to https://www.programcreek.com/java-api-examples/emf i found out the correct way to initialize my Elist with a constructor that Creates an empty instance with no initial capacity.The data storage will be null. and HOP it works.

EList<RtModuleInvocation> invoc0 = new BasicEList<>();


问:
how to remove /?fbclid=... in nuxt url
hello there i like to remove the facebook analytic forced url parameter /?fbclid= https://www.example.com/?fbclid=..., from my host url, when redirected from facebook by clicking the url, the problem is the nuxt-link-exact-active class is not applied if redirected with this parameter.
Thanks

答:
For simple cases like https://www.example.com/?fbclid=... where fbclid is the first and only parameter, it can be done by a simple server configuration.

So for example put this in the .htaccess file:

```<code>RewriteEngine on
<if "%{QUERY_STRING} =~ /^fbclid=/">
 RewriteRule  .  %{REQUEST_URI}?   [R=301,L]
</if>
</code>```

Note the ? after %{REQUEST_URI}. It deletes the query string completely.

In other cases (where fbclid was appended to other parameters) this example does nothing - more complicated code is needed for that.

Title: how to remove /?fbclid=... in nuxt url

Body:
For simple cases like https://www.example.com/?fbclid=... where fbclid is the first and only parameter, it can be done by a simple server configuration.

So for example put this in the .htaccess file:

RewriteEngine on
<if "%{QUERY_STRING} =~ /^fbclid=/">
 RewriteRule  .  %{REQUEST_URI}?   [R=301,L]
</if>

Note the ? after %{REQUEST_URI}. It deletes the query string completely.

In other cases (where fbclid was appended to other parameters) this example does nothing - more complicated code is needed for that.


问:
Git ignore changeset
Hi
I'm currently using SVN. Let's say I have some files with some changes that should be locally presented on my pc (I need them to run it on my configuration) but they shouldn't be committed to server.
I case of SVN it is ok to add them to .ignore and just do not commit them, but this works only in case of changing other files during my work. If I need to change something in files that are marked as ignore - I need before commit to backup these files, revert ignored changes, commit and restore them after backup. Sometimes this can be very annoying.

I heard about git, that it is built upon changesets not files. Can I use git-svn to ignore some changeset?

答:
I have a bit of trouble to understand your question but I try:

If you add a file to svn:ignore, it's ignored by SVN. So there should be no need to backup or restore it before/after a commit. Are you sure you didn't add those file accidentally? SVN ignores files in svn:ignore but if you do svn add ignorefile.bak the file will be added to the repository.

The same is true for git. It also has an ignore file but you can still force add a file.

That said, you should never have files in your project that are not committed. Either the file is important, then you should commit it. If that would disrupt the work of others, commit it under a different name (say arched.config instead of project.config). Otherwise, it will be very hard for another user to maintain the software. Or for yourself, if your PC suddenly dies.

If the file is unrelated to the project, it should not be in the project at all. Put it somewhere else.

And with Git, you even have another option: You can create a branch that contains the file just like it contains any other file. Name that branch "archeg-work". Now you can always work on this branch and the project will work out of the box. Just clone it and no further changes are necessary.

When you're happy with your work, merge the changes back into the master branch. Unlike with SVN, branching really works with Git. Linus Torvalds merges thousands of branches every day without problems.

ContentLicense: CC BY-SA 3.0

Title: Git ignore changeset


问:
Forking a process into 7 children without looping
How can I create 7 processes using 1 parent in just 3 forks() calls? Looping is not allowed out of 7 1 is the parent one

答: Total number of processes created using fork() can be found using 2^n where n is the number of times fork() is being called. Here if we calls fork() 3 times, then 2^3 processes will be created i.e 8.


问:
Compare a list of strings with each other in R
I am trying to compare a list of strings with each other using the function levenshteinSim() from package 'RecordLinkage'. However, I am having a very hard time to figure out how I can incorporate my list of strings into the function as it only takes two arguments str1 and str2. I am trying to find the most optimal way as my list contains 4k strings. Any help is much appreciated!

Below is some sample data:

```<code>sample <- c('apple', 'appeal', 'apparel', 'peel', 'peer', 'pear')
</code>```

答:
So, I think this might be what you want. The RecordLinkage package is not on CRAN anymore, so I went for another package that calculates the Levenshtein distance:

```<code>library(stringdist)

sample <- c('apple', 'appeal', 'apparel', 'peel', 'peer', 'pear')

df <- expand.grid(sample, sample) # this creates a dataframe of all combinations of the sample elements

stringdist(df$Var1, df$Var2, method = "lv")
</code>```

Output:

```<code>[1] 0 3 3 4 4 4 3 0 3 3 4 3 3 3 0 4 5 4 4 3 4 0 1 2 4 4 5 1 0 1 4 3 4 2 1 0
</code>```

And maybe a little more appealing - the dplyr version:

```<code>library(dplyr)

df %>%
    mutate(levenshtein = stringdist(Var1, Var2, method = "lv"))
</code>```

which outputs

```<code>     Var1  Var2 levenshtein
1   apple apple           0
2  appeal apple           3
3 apparel apple           3
4    peel apple           4
5    peer apple           4
6    pear apple           4
...
</code>```

Body:
I am trying to compare a list of strings with each other using the function levenshteinSim() from package 'RecordLinkage'. However, I am having a very hard time to figure out how I can incorporate my list of strings into the function as it only takes two arguments str1 and str2. I am trying to find the most optimal way as my list contains 4k strings. Any help is much appreciated!

Below is some sample data:

sample <- c('apple', 'appeal', 'apparel', 'peel', 'peer', 'pear')

Body:
So, I think this might be what you want. The RecordLinkage package is not on CRAN anymore, so I went for another package that calculates the Levenshtein distance:

library(stringdist)

sample <- c('apple', 'appeal', 'apparel', 'peel', 'peer', 'pear')

df <- expand.grid(sample, sample) # this creates a dataframe of all combinations of the sample elements

stringdist(df$Var1, df$Var2, method = "lv")

Output:

[1] 0 3 3 4 4 4 3 0 3 3 4 3 3 3 0 4 5 4 4 3 4 0 1 2 4 4 5 1 0 1 4 3 4 2 1 0

And maybe a little more appealing - the dplyr version:

library(dplyr)

df %>%
    mutate(levenshtein = stringdist(Var1, Var2, method = "lv"))

which outputs

     Var1  Var2 levenshtein
1   apple apple           0
2  appeal apple           3
3 apparel apple           3
4    peel apple           4
5    peer apple           4
6    pear apple           4
...


问:
How to open owl ng datepicker via icon trigger
Right now I am using owl ng datepicker - as shown in the image(https://daniel-projects.firebaseapp.com/owlng/date-time-picker). But it is opening on input field click. I want it to be opened on datepicker icon click in my input box.

here is the html code for the same.

```<code> <input id="fromDate"
            name="fromDate"
            type="text"
            placeholder="From Date"
            class="form-control"
            tooltip="From Date"
            delay="500"
            triggers=""
            #fromDateToolTip="bs-tooltip"
            (mouseenter)="fromDateToolTip.show()"
            (mouseleave)="fromDateToolTip.hide()"
            [(ngModel)]="fromDatePicker"
            [owlDateTime]="dt1"
            [owlDateTimeTrigger]="dt1"
            readonly="readonly"
            (ngModelChange)="dateFilter()"
            (keydown.backspace)="clear()">
        <owl-date-time
            [pickerType]="'calendar'"
            [startAt]="startAtFromDate"
            [showSecondsTimer]="true"
            (afterPickerClosed)="setFromDateSelected($event,dt1)"
            (afterPickerOpen)="fromDatePickerOpen()"
             #dt1>
        </owl-date-time>
</code>```

答:
remove <code>[owlDateTimeTrigger]="dt2"</code> from input field and place it some where in icon field. </p>

```<code><div class="example-wrapper">
    <h2>Trigger Picker by a Icon</h2>
    <label class="example-input-wrapper">
        Date Time
        <input placeholder="Date Time:" [(ngModel)]="dateTime" [owlDateTime]="dt2">
        <span class="example-trigger" [owlDateTimeTrigger]="dt2">
            <i class="fas fa-calendar-alt"></i>
        </span>
        <owl-date-time #dt2></owl-date-time>
    </label>

    <h4>Value From Picker: {{dateTime}}</h4>
</div>
</code>```

Body:
Right now I am using owl ng datepicker - as shown in the image(https://daniel-projects.firebaseapp.com/owlng/date-time-picker). But it is opening on input field click. I want it to be opened on datepicker icon click in my input box.

here is the html code for the same.

 <input id="fromDate"
            name="fromDate"
            type="text"
            placeholder="From Date"
            class="form-control"
            tooltip="From Date"
            delay="500"
            triggers=""
            #fromDateToolTip="bs-tooltip"
            (mouseenter)="fromDateToolTip.show()"
            (mouseleave)="fromDateToolTip.hide()"
            [(ngModel)]="fromDatePicker"
            [owlDateTime]="dt1"
            [owlDateTimeTrigger]="dt1"
            readonly="readonly"
            (ngModelChange)="dateFilter()"
            (keydown.backspace)="clear()">
        <owl-date-time
            [pickerType]="'calendar'"
            [startAt]="startAtFromDate"
            [showSecondsTimer]="true"
            (afterPickerClosed)="setFromDateSelected($event,dt1)"
            (afterPickerOpen)="fromDatePickerOpen()"
             #dt1>
        </owl-date-time>

Body:
remove [owlDateTimeTrigger]="dt2" from input field and place it some where in icon field.

<div class="example-wrapper">
    <h2>Trigger Picker by a Icon</h2>
    <label class="example-input-wrapper">
        Date Time
        <input placeholder="Date Time:" [(ngModel)]="dateTime" [owlDateTime]="dt2">
        <span class="example-trigger" [owlDateTimeTrigger]="dt2">
            <i class="fas fa-calendar-alt"></i>
        </span>
        <owl-date-time #dt2></owl-date-time>
    </label>

    <h4>Value From Picker: {{dateTime}}</h4>
</div>


问:
Drag and drop between several lists
I have 4 lists of four different objects (A, B, C, D).

Is there a way to associate a name with each of these lists? In other words, list A being A, B being B ...

I intend to drag and drop an object and at the same time know which list it came from and where it went.

I used this to find out the automatically generated list value console.log ("FROM" + event.previousContainer.id)
    console.log ("TO" + event.container.id), the problem is that these values sometimes vary, they are not always the same and if you use conditions it can stop working.

Is there a way to assign or always get the same name from the list where it is object and the one in which it was dropped?

Thanks

Demo- Stackblitz

.ts

```<code>  drop(event: CdkDragDrop<string[]>) {
    console.log("FROM" + event.previousContainer.id)
    console.log("TO" + event.container.id)
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }
</code>```

答:
Since it's a list of elements and when drag and drop the element get add to the other list .

The easiest way to achieve what you want you need to add a key to each element in your list :

Keep in mind : It's not the best solution

Example :

```<code>A = [{
    name:"AA",
    belongTo: "A"
  },
  {
    name:"BB",
    belongTo: "A"
  },
  {
    name:"CC",
    belongTo: "A"
  },
  ];

  B = [{
    name:"RR",
    belongTo: "B"
  },
  {
    name:"PP",
    belongTo: "B"
  },
  {
    name:"QQ",
    belongTo: "B"
  },
  ];
</code>```

HTML (div card-body for list A):

```<code>   <div class="card-body" style="overflow-y: auto;"  #activeList="cdkDropList"
      style="height:100%"
      class="box-list"
      cdkDropList
      cdkDropListOrientation="vertical"
      [cdkDropListData]="A"
      [cdkDropListConnectedTo]="[inactiveList]"
      (cdkDropListDropped)="drop($event)">
        <div *ngFor="let nw of A" cdkDrag >
          <div class="card mysmallCcards">
            <div class="card-body">
                <span>{{nw.name}} => {{nw.belongTo}}</span>
            </div>
          </div>
        </div>
      </div>
</code>```

Title: Drag and drop between several lists

Body:
I have 4 lists of four different objects (A, B, C, D).

Is there a way to associate a name with each of these lists? In other words, list A being A, B being B ...

I intend to drag and drop an object and at the same time know which list it came from and where it went.

I used this to find out the automatically generated list value console.log ("FROM" + event.previousContainer.id)
    console.log ("TO" + event.container.id), the problem is that these values sometimes vary, they are not always the same and if you use conditions it can stop working.

Is there a way to assign or always get the same name from the list where it is object and the one in which it was dropped?

Thanks

Demo- Stackblitz

.ts

  drop(event: CdkDragDrop<string[]>) {
    console.log("FROM" + event.previousContainer.id)
    console.log("TO" + event.container.id)
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }

Body:
Since it's a list of elements and when drag and drop the element get add to the other list .

The easiest way to achieve what you want you need to add a key to each element in your list :

Keep in mind : It's not the best solution

Example :

A = [{
    name:"AA",
    belongTo: "A"
  },
  {
    name:"BB",
    belongTo: "A"
  },
  {
    name:"CC",
    belongTo: "A"
  },
  ];

  B = [{
    name:"RR",
    belongTo: "B"
  },
  {
    name:"PP",
    belongTo: "B"
  },
  {
    name:"QQ",
    belongTo: "B"
  },
  ];

HTML (div card-body for list A):

   <div class="card-body" style="overflow-y: auto;"  #activeList="cdkDropList"
      style="height:100%"
      class="box-list"
      cdkDropList
      cdkDropListOrientation="vertical"
      [cdkDropListData]="A"
      [cdkDropListConnectedTo]="[inactiveList]"
      (cdkDropListDropped)="drop($event)">
        <div *ngFor="let nw of A" cdkDrag >
          <div class="card mysmallCcards">
            <div class="card-body">
                <span>{{nw.name}} => {{nw.belongTo}}</span>
            </div>
          </div>
        </div>
      </div>


问:
Can someone help me with this linked list? C++
I have an object oriented exam tomorrow and I'm still stuck with linked lists. For some reason I cant quite understand how they work or how to implement them properly. I've watched a lot of videos and tutorials but it still is quite complex. I always get an error which prints nothing to the console, just a blank black page. Can someone tell em what am I doing wrong?
Thank you.</p>

```<code>#include <iostream>
#include <string>

using namespace std;

struct node
{
    string name;
    int number;
    node* next;
};
struct node* head = 0;

class Employees
{
private:
    node* head, * tail;
public:
    Employees()
    {
        head = NULL;
        tail = NULL;
    }
    void addToList(string Name, int Num)
    {
        node* n = new node;
        n->name = Name;
        n->number = Num;
        n->next = NULL;
        if (head == NULL)
        {
            head = n;
            tail = n;
        }
        else
        {
            tail->next = n;
            tail = tail->next;
        }
    }
    void PrintAll()
    {
        while (head != NULL)
        {
            node* current;
            while (current != NULL)
            {
                cout << current->name << "\t";
                cout << current->number;
            }
        }
    }
};

int main()
{
    Employees a;
    a.addToList("Robert", 54);
    a.addToList("Manny", 77);

    a.PrintAll();

}
</code>```

答:
Three issues:

```<code>while (head != NULL)
{
    /*...*/
}
</code>```

You do not modify head inside the loop (why would you), hence this loop would run either never or forever.

Second:

```<code> node* current;
 while (current != NULL)
</code>```

current in uninitialized. Comparing it to NULL invokes undefined behavior. Always initialize your variables!

Last:

```<code>while (current != NULL)
{
    cout << current->name << "\t";
    cout << current->number;
}
</code>```

Similar to the first issue, the loop condition is either true or false, but it never changes, ie the loop either runs never or infinite.

As this appears to be an exercise, I'll leave it to you to fix the code.

Body:
I have an object oriented exam tomorrow and I'm still stuck with linked lists. For some reason I cant quite understand how they work or how to implement them properly. I've watched a lot of videos and tutorials but it still is quite complex. I always get an error which prints nothing to the console, just a blank black page. Can someone tell em what am I doing wrong?
Thank you.

#include <iostream>
#include <string>

using namespace std;

struct node
{
    string name;
    int number;
    node* next;
};
struct node* head = 0;

class Employees
{
private:
    node* head, * tail;
public:
    Employees()
    {
        head = NULL;
        tail = NULL;
    }
    void addToList(string Name, int Num)
    {
        node* n = new node;
        n->name = Name;
        n->number = Num;
        n->next = NULL;
        if (head == NULL)
        {
            head = n;
            tail = n;
        }
        else
        {
            tail->next = n;
            tail = tail->next;
        }
    }
    void PrintAll()
    {
        while (head != NULL)
        {
            node* current;
            while (current != NULL)
            {
                cout << current->name << "\t";
                cout << current->number;
            }
        }
    }
};

int main()
{
    Employees a;
    a.addToList("Robert", 54);
    a.addToList("Manny", 77);

    a.PrintAll();

}

Body:
Three issues:

while (head != NULL)
{
    /*...*/
}

You do not modify head inside the loop (why would you), hence this loop would run either never or forever.

Second:

 node* current;
 while (current != NULL)

current in uninitialized. Comparing it to NULL invokes undefined behavior. Always initialize your variables!

Last:

while (current != NULL)
{
    cout << current->name << "\t";
    cout << current->number;
}

Similar to the first issue, the loop condition is either true or false, but it never changes, ie the loop either runs never or infinite.

As this appears to be an exercise, I'll leave it to you to fix the code.


问:
This question is related to the datetime module of Python
I wrote a Python function that prints the number of days remaining in birthday of a user - the value of which is entered by the user. The code is as follows:

```<code>"""
Created on Thu Feb 20 16:01:33 2020
@author: hussain.ali

"""
    import datetime as dt
    import pytz
    def days_to_birthday():
        a = (input('Enter your birthday in YYYY, MM, DD format with the year being the current year:'))
        td = dt.datetime.today()
        #td2= td.replace(hour=0, minute =0, second =0, microsecond =0)
        birthday = dt.datetime.strptime(a, '%Y,%m,%d')
        days_to_birthday = birthday - td
        print("There are", days_to_birthday, ' remaining until your next birthday!')

    days_to_birthday()
</code>```

This script or code works well except that it gives the number of days plus hours as well as minutes, seconds and even microseconds remaining until the next birthday.

The output seems like:

```<code>Enter your birthday in YYYY, MM, DD format with the year being the current year:2020,3,7
There are 15 days, 6:11:07.020133  remaining until your next birthday!
</code>```

I want either only the days remaining to be displayed in the output
OR the output as:
There are 15 days, 6 hours, 11minutes, 07seconds, and 020133 microseconds remaining until your next birthday!

What one needs to do to attain the desired output? Please advise.

答:
change your print statement to this code below.</p>

```<code>print("There are", days_to_birthday.days, 'days remaining until your next birthday!')
</code>```

Body:
I wrote a Python function that prints the number of days remaining in birthday of a user - the value of which is entered by the user. The code is as follows:

"""
Created on Thu Feb 20 16:01:33 2020
@author: hussain.ali

"""
    import datetime as dt
    import pytz
    def days_to_birthday():
        a = (input('Enter your birthday in YYYY, MM, DD format with the year being the current year:'))
        td = dt.datetime.today()
        #td2= td.replace(hour=0, minute =0, second =0, microsecond =0)
        birthday = dt.datetime.strptime(a, '%Y,%m,%d')
        days_to_birthday = birthday - td
        print("There are", days_to_birthday, ' remaining until your next birthday!')

    days_to_birthday()

This script or code works well except that it gives the number of days plus hours as well as minutes, seconds and even microseconds remaining until the next birthday.

The output seems like:

Enter your birthday in YYYY, MM, DD format with the year being the current year:2020,3,7
There are 15 days, 6:11:07.020133  remaining until your next birthday!

I want either only the days remaining to be displayed in the output
OR the output as:
There are 15 days, 6 hours, 11minutes, 07seconds, and 020133 microseconds remaining until your next birthday!

What one needs to do to attain the desired output? Please advise.

Body:
change your print statement to this code below.

print("There are", days_to_birthday.days, 'days remaining until your next birthday!')


问:
JSON.parse generates error with backslash
Why does the following JSON fail to be parsed by JSON.parse?

```<code>{"page_title":"contact us","val":{"pattern":"/email/\s+us\s*(.*?)/\s/","type":"1"}}
</code>```

When I log result to the console then it gives above output. After using JSON.parse it gives this error :

Uncaught SyntaxError: Unexpected token s in JSON at position 1649 at JSON.parse ()
  see my code below:

```<code>var result ='<?php echo json_encode($output);?>';
console.log(result);
var data = JSON.parse(result);
</code>```

答:
Use addslashes function because you are using regex into string</p>

```<code>var result ='<?php echo addslashes(json_encode($output));?>';
</code>```

Body:
Why does the following JSON fail to be parsed by JSON.parse?

{"page_title":"contact us","val":{"pattern":"/email/\s+us\s*(.*?)/\s/","type":"1"}}

When I log result to the console then it gives above output. After using JSON.parse it gives this error :

Uncaught SyntaxError: Unexpected token s in JSON at position 1649 at JSON.parse ()
  see my code below:

var result ='<?php echo json_encode($output);?>';
console.log(result);
var data = JSON.parse(result);

Body:
Use addslashes function because you are using regex into string

var result ='<?php echo addslashes(json_encode($output));?>';


问:
fake Geolocation in chrome automation
I need to automate geolocation in chrome using python script. I have to fake the latitude and longitude. I followed some links in stackoverflow but they gave errors.
               chromeDriver.executeScript("window.navigator.geolocation.getCurrentPosition=function(success){var position = {"coords" : {"latitude": "555","longitude": "999"}};success(position);}");

is there any other way i can change the location?

答:
It's actually now progammable by using the Chrome Devtools Protocol (cdp):</p>

```<code>params = {
    "latitude": 50.1109,
    "longitude": 8.6821,
    "accuracy": 100
}

self.driver = webdriver.Chrome()
self.driver.execute_cdp_cmd("Page.setGeolocationOverride", params)
self.driver.get('https://www.google.com/maps')
</code>```

Title: fake Geolocation in chrome automation

Body:
It's actually now progammable by using the Chrome Devtools Protocol (cdp):

params = {
    "latitude": 50.1109,
    "longitude": 8.6821,
    "accuracy": 100
}

self.driver = webdriver.Chrome()
self.driver.execute_cdp_cmd("Page.setGeolocationOverride", params)
self.driver.get('https://www.google.com/maps')


问:
Best practice - How to respond with different entity views to improve performance in a RESTful API (Symfony 4)
When listing an using a REST index endpoint I would like to have different outputs for performance reasons.

```<code>ex: on the same GET path for CRUD indexing
- List of Entities with all associations
- List of Entities with some associations
- List of Entities with just some basic fields
</code>```

This would be used for listing entities for a detailed view with statistics or just listing them for a drop down selector.

Possible Solution 1: I can do this in the controller by returning an object where I customize all the fields based on a query parameter - but then my controllers become very fat because listing all the required fields can be 20-30 fields per object. (basically giving up on the benefit of a serializer doing this automatically based on the type of the entity)

```<code>return [
   [
     'id' => $event->getId(),
     'name' => $event->getName(),
      ...
     'order_count' => $orderRepository->getOrderCountForEvent($event->getId())
   ],
   ...
]
</code>```

Possible Solution 2: I could define transform functions in the repository for the different views and filters that I want to return.

```<code>public function transform(Event $event, $type = 'shortlist')
{
    $view = null;

    switch($type) {
        case 'shortlist':
            $view = [
                'id'    => $event->getId(),
                'name'  => $event->getName(),
                'participants' => $orderRepository->getParticipantCountForEvent($event->getId()),
                 ...
            ];
        break;
        default:
            ... // all fields
        break
    }

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

Are there any better / cleaner solutions? Most tutorials are only dealing with simple entities with simple relations and their CRUD implementations are very basic where they simply fetch every field and pass it to a serializer.

答:
Maybe you are looking for the Symfony serializer, which has the feature of choosing fields you render.

Example from the doc:

```<code>use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class User
{
    public $familyName;
    public $givenName;
    public $company;
}

class Company
{
    public $name;
    public $address;
}

$company = new Company();
$company->name = 'Les-Tilleuls.coop';
$company->address = 'Lille, France';

$user = new User();
$user->familyName = 'Dunglas';
$user->givenName = 'Kévin';
$user->company = $company;

$serializer = new Serializer([new ObjectNormalizer()]);

$data = $serializer->normalize($user, null, [AbstractNormalizer::ATTRIBUTES => ['familyName', 'company' => ['name']]]);
// $data = ['familyName' => 'Dunglas', 'company' => ['name' => 'Les-Tilleuls.coop']];
</code>```

See documentation here: https://symfony.com/doc/current/components/serializer.html#selecting-specific-attributes

Body:
When listing an using a REST index endpoint I would like to have different outputs for performance reasons.

ex: on the same GET path for CRUD indexing
- List of Entities with all associations
- List of Entities with some associations
- List of Entities with just some basic fields

This would be used for listing entities for a detailed view with statistics or just listing them for a drop down selector.

Possible Solution 1: I can do this in the controller by returning an object where I customize all the fields based on a query parameter - but then my controllers become very fat because listing all the required fields can be 20-30 fields per object. (basically giving up on the benefit of a serializer doing this automatically based on the type of the entity)

return [
   [
     'id' => $event->getId(),
     'name' => $event->getName(),
      ...
     'order_count' => $orderRepository->getOrderCountForEvent($event->getId())
   ],
   ...
]

Possible Solution 2: I could define transform functions in the repository for the different views and filters that I want to return.

public function transform(Event $event, $type = 'shortlist')
{
    $view = null;

    switch($type) {
        case 'shortlist':
            $view = [
                'id'    => $event->getId(),
                'name'  => $event->getName(),
                'participants' => $orderRepository->getParticipantCountForEvent($event->getId()),
                 ...
            ];
        break;
        default:
            ... // all fields
        break
    }

    return $view;
}

Are there any better / cleaner solutions? Most tutorials are only dealing with simple entities with simple relations and their CRUD implementations are very basic where they simply fetch every field and pass it to a serializer.

Body:
Maybe you are looking for the Symfony serializer, which has the feature of choosing fields you render.

Example from the doc:

use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class User
{
    public $familyName;
    public $givenName;
    public $company;
}

class Company
{
    public $name;
    public $address;
}

$company = new Company();
$company->name = 'Les-Tilleuls.coop';
$company->address = 'Lille, France';

$user = new User();
$user->familyName = 'Dunglas';
$user->givenName = 'Kévin';
$user->company = $company;

$serializer = new Serializer([new ObjectNormalizer()]);

$data = $serializer->normalize($user, null, [AbstractNormalizer::ATTRIBUTES => ['familyName', 'company' => ['name']]]);
// $data = ['familyName' => 'Dunglas', 'company' => ['name' => 'Les-Tilleuls.coop']];

See documentation here: https://symfony.com/doc/current/components/serializer.html#selecting-specific-attributes


问:
How to fix "cannot convert from 'TouchTracking.TouchTrackingPoint' to 'Xamarin.Forms.Point'"?
hope your doing well.

I've been attempting to create a simple page in my app which allows the user to draw on the screen by following the code posted by Microsoft. However I must have mucked something up something as currently I'm being faced with the error "cannot convert from 'TouchTracking.TouchTrackingPoint' to 'Xamarin.Forms.Point'". Does anyone know how to fix this?

Xaml

```<code><?xml version="1.0" encoding="UTF-8"?>
<pages:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             xmlns:skia="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms"
             xmlns:tt="clr-namespace:TouchTracking.Forms;assembly=TouchTracking.Forms"
             x:Class="NEA_I_MDL.Misc.Notes_Popup"
             xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup">

      <Grid BackgroundColor="White">

        <skia:SKCanvasView x:Name="CanvasView" PaintSurface="CanvasView_PaintSurface"></skia:SKCanvasView>

        <Grid.Effects>

            <tt:TouchEffect Capture = "True" TouchAction="TouchEffect_TouchAction"></tt:TouchEffect>

        </Grid.Effects>

      </Grid>

</pages:PopupPage>
</code>```

C#

```<code>using SkiaSharp;
using TouchTracking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using SkiaSharp.Views.Forms;

namespace NEA_I_MDL.Misc
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Notes_Popup
    {

        Dictionary<long, SKPath> ActivePaths = new Dictionary<long, SKPath>();
        List<SKPath> FinishedPaths = new List<SKPath>();

        SKPaint Paint = new SKPaint
        {

            Style = SKPaintStyle.Stroke,
            Color = SKColors.Black,
            StrokeWidth = 10,
            StrokeCap = SKStrokeCap.Round,
            StrokeJoin = SKStrokeJoin.Round

        };

        public Notes_Popup()
        {
            InitializeComponent();
        }

        private void CanvasView_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
        {

        }

        SkiaSharp.SKPoint ConvertToPixel(Point pt)
        {
            return new SKPoint((float)(CanvasView.CanvasSize.Width * pt.X / CanvasView.Width),(float)(CanvasView.CanvasSize.Height*pt.Y / CanvasView.Height));
        }

        private void TouchEffect_TouchAction(object sender, TouchTracking.TouchActionEventArgs args)
        {

            switch (args.Type)
            {

                case TouchActionType.Pressed:

                    if (!ActivePaths.ContainsKey(args.Id))
                    {
                        SKPath path = new SKPath();
                        path.MoveTo(ConvertToPixel(args.Location));
                        ActivePaths.Add(args.Id, path);
                        CanvasView.InvalidateSurface();
                    }

                    break;

                case TouchActionType.Moved:

                    if(ActivePaths.ContainsKey(args.Id))
                    {
                        SKPath path = ActivePaths[args.Id];
                        path.LineTo(ConvertToPixel(args.Location));
                        CanvasView.InvalidateSurface();
                    }

                    break;

                case TouchActionType.Released:

                    if(ActivePaths.ContainsKey(args.Id))
                    {
                        FinishedPaths.Add(ActivePaths[args.Id]);
                        ActivePaths.Remove(args.Id);
                        CanvasView.InvalidateSurface();
                    }

                    break;

                case TouchActionType.Cancelled:

                    if (ActivePaths.ContainsKey(args.Id))
                    {
                        ActivePaths.Remove(args.Id);
                        CanvasView.InvalidateSurface();
                    }

                break;

            }

        }

        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {

            SKCanvas Canvas = args.Surface.Canvas;
            Canvas.Clear();

            foreach(SKPath i in FinishedPaths)
            {
                Canvas.DrawPath(i, Paint);
            }

            foreach (SKPath path in ActivePaths.Values)
            {
                Canvas.DrawPath(path, Paint);
            }

        }

    }
}
</code>```

答:
you have to use SKPoint if you add point to SKPath.
check your code in the line and change your Points to SKPoint.</p>

Body:
hope your doing well.

I've been attempting to create a simple page in my app which allows the user to draw on the screen by following the code posted by Microsoft. However I must have mucked something up something as currently I'm being faced with the error "cannot convert from 'TouchTracking.TouchTrackingPoint' to 'Xamarin.Forms.Point'". Does anyone know how to fix this?

Xaml

<?xml version="1.0" encoding="UTF-8"?>
<pages:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             xmlns:skia="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms"
             xmlns:tt="clr-namespace:TouchTracking.Forms;assembly=TouchTracking.Forms"
             x:Class="NEA_I_MDL.Misc.Notes_Popup"
             xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup">

      <Grid BackgroundColor="White">

        <skia:SKCanvasView x:Name="CanvasView" PaintSurface="CanvasView_PaintSurface"></skia:SKCanvasView>

        <Grid.Effects>

            <tt:TouchEffect Capture = "True" TouchAction="TouchEffect_TouchAction"></tt:TouchEffect>

        </Grid.Effects>

      </Grid>

</pages:PopupPage>

C#

using SkiaSharp;
using TouchTracking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using SkiaSharp.Views.Forms;

namespace NEA_I_MDL.Misc
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Notes_Popup
    {

        Dictionary<long, SKPath> ActivePaths = new Dictionary<long, SKPath>();
        List<SKPath> FinishedPaths = new List<SKPath>();

        SKPaint Paint = new SKPaint
        {

            Style = SKPaintStyle.Stroke,
            Color = SKColors.Black,
            StrokeWidth = 10,
            StrokeCap = SKStrokeCap.Round,
            StrokeJoin = SKStrokeJoin.Round

        };

        public Notes_Popup()
        {
            InitializeComponent();
        }

        private void CanvasView_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
        {

        }

        SkiaSharp.SKPoint ConvertToPixel(Point pt)
        {
            return new SKPoint((float)(CanvasView.CanvasSize.Width * pt.X / CanvasView.Width),(float)(CanvasView.CanvasSize.Height*pt.Y / CanvasView.Height));
        }

        private void TouchEffect_TouchAction(object sender, TouchTracking.TouchActionEventArgs args)
        {

            switch (args.Type)
            {

                case TouchActionType.Pressed:

                    if (!ActivePaths.ContainsKey(args.Id))
                    {
                        SKPath path = new SKPath();
                        path.MoveTo(ConvertToPixel(args.Location));
                        ActivePaths.Add(args.Id, path);
                        CanvasView.InvalidateSurface();
                    }

                    break;

                case TouchActionType.Moved:

                    if(ActivePaths.ContainsKey(args.Id))
                    {
                        SKPath path = ActivePaths[args.Id];
                        path.LineTo(ConvertToPixel(args.Location));
                        CanvasView.InvalidateSurface();
                    }

                    break;

                case TouchActionType.Released:

                    if(ActivePaths.ContainsKey(args.Id))
                    {
                        FinishedPaths.Add(ActivePaths[args.Id]);
                        ActivePaths.Remove(args.Id);
                        CanvasView.InvalidateSurface();
                    }

                    break;

                case TouchActionType.Cancelled:

                    if (ActivePaths.ContainsKey(args.Id))
                    {
                        ActivePaths.Remove(args.Id);
                        CanvasView.InvalidateSurface();
                    }

                break;

            }

        }

        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {

            SKCanvas Canvas = args.Surface.Canvas;
            Canvas.Clear();

            foreach(SKPath i in FinishedPaths)
            {
                Canvas.DrawPath(i, Paint);
            }

            foreach (SKPath path in ActivePaths.Values)
            {
                Canvas.DrawPath(path, Paint);
            }

        }

    }
}


问:
git log: parsing who worked on the repository and when
I'd like to create some statistics for open source projects. I'd like to extract the information when a certain person started to work on a git repository and when they finished on it... or the first and the last commit by an author, with a date.

I can manually extract this information from git log output. However, is there a git built-in way, or one-liner shell script that would help me to analyse this.

Find all repo authors from git log

Get their first and last commit date

答:
I had to do this over multiple repositories, so shell tools provided inflexible. I wrote a quick Python script that does the job. README here.

import sys
import logging
import os.path
from datetime import datetime
from collections import defaultdict
from typing import List
from typing import Optional
from typing import Dict
from dataclasses import dataclass
from dataclasses import field
from pathlib import Path
from git import Repo
from tabulate import tabulate

# If logging is set to debug you will see individual git commands in the console
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("githistory")

@dataclass
class AuthorHistory:
    """Author history information for a single repo"""
    repo: str
    name: str
    email: str
    first_commit_at: datetime = None
    first_commit_message: str = None
    last_commit_at: datetime = None
    last_commit_message: str = None
    commit_count: int = 0

@dataclass
class AuthorHistoryOverMultipleRepos:
    """Author history information spanning over multiple repos"""

    # repo name -> history
    histories: Dict[str, AuthorHistory] = field(default_factory=dict)
    first_commit_at: datetime = datetime(2030, 1, 1)
    last_commit_at: datetime = datetime(1970, 1, 1)
    commit_count: int = 0

    @property
    def email(self):
        return next(iter(self.histories.values())).email

    @property
    def name(self):
        return next(iter(self.histories.values())).name

@dataclass
class RepositoryHistory:
    """History of a single repo"""
    name: str
    commit_count: int = 0

    #: email -> history maps
    authors: Dict[str, AuthorHistory] = field(default_factory=dict)

@dataclass
class FullHistory:
    """History of a project spanning multiple repositories"""
    repos: List[RepositoryHistory] = field(default_factory=list)

    #: Pointers to individiaul author histories
    #: email -> repo -> AuthorHistory
    all_author_histories: Dict[str, AuthorHistoryOverMultipleRepos] = field(default_factory=dict)

def extract_history(path: Path) -> Optional[RepositoryHistory]:
    """Extract history of one git repository.

    @param :repo: Path to git repository
    @param :all_author_histories: Track author work across multiple repos
    """
    logger.info("Extracting history from %s", path)

    r = Repo(path)
    repo_name = os.path.split(path)[-1]

    # Sanity check
    heads = r.heads
    if len(heads) == 0:
        logger.warning("Not a git repository: %s", path)
        return None

    master = heads.master

    history = RepositoryHistory(name=repo_name)
    authors = history.authors

    # This will iterate commits from firs to last
    all_commits = list(r.iter_commits('master'))
    for c in all_commits:  # type: Commit
        # https://gitpython.readthedocs.io/en/stable/reference.html#git.objects.commit.Commit
        # https://stackoverflow.com/questions/58550252/how-to-get-commit-author-name-and-email-with-gitpython
        name = c.author.name
        email = c.author.email

        author = authors.get(email)  # type: AuthorHistory

        if not author:
            # We are initialising this author
            author = AuthorHistory(name, email, repo_name)
            authors[email] = author
            author.first_commit_at = datetime.fromtimestamp(c.committed_date) # Is UNIX time
            author.first_commit_message = c.message
            author.last_commit_at = datetime.fromtimestamp(c.committed_date)
            author.last_commit_message = author.last_commit_message
        else:
            # Adding more commits for the author
            author.last_commit_at = datetime.fromtimestamp(c.committed_date)
            author.last_commit_message = c.message

        author.commit_count += 1
        history.commit_count += 1

    return history

def mine_authors_over_repos(history: List[RepositoryHistory]) -> Dict[str, AuthorHistoryOverMultipleRepos]:
    """Create a history info spanning over multiple repos."""

    all_author_histories = defaultdict(AuthorHistoryOverMultipleRepos)
    for r in history.repos:
        for email, history in r.authors.items():
            all_history = all_author_histories[email]
            all_history.first_commit_at = min(all_history.first_commit_at, history.first_commit_at)
            all_history.last_commit_at = max(all_history.last_commit_at, history.last_commit_at)
            all_history.commit_count += history.commit_count
            all_history.histories[r.name] = history
            print("set history ", r.name, history)

    return all_author_histories

def mine_data(repos: List[str]) -> FullHistory:
    """Extract history from multiple git repositories.

    Will skip directories that do not look like git repos.
    """

    logger.info("Working on %d repositores", len(repos))
    history = FullHistory()
    for repo in repos:
        repo_history = extract_history(Path(repo))
        if repo_history:
            history.repos.append(repo_history)

    history.all_author_histories = mine_authors_over_repos(history)
    return history

def output_author_data(history: FullHistory):
    """Write out information about authors"""

    print("All authors")
    print("*" * 80)

    table = []
    for author in history.all_author_histories.values():
        table.append([author.name, author.email, author.first_commit_at, author.last_commit_at, author.commit_count])

    # Sort by the first commit
    table = sorted(table, key=lambda row: row[2])

    print(tabulate(table, headers=["Email", "Name", "First commit", "Last commit", "Commit count"]))
    print()

def main():
    """Entry point"""
    history = mine_data(sys.argv[1:])
    output_author_data(history)

if __name__ == "__main__":
    main()
```


问:
GMaps api Geocode strange behavior
I'm using gmaps apiv3 webservice to geocode with latlng couple. It's pretty simple but I have a strange behavior for some data.

Eq:

http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&region=fr&latlng=46.16141,-1.149797

Next I open url with a navigator (firefox / chrome) and at line formatted_address the value is :

```<code><formatted_address>57-79 Rue des Merciers, 17000 La Rochelle, France</formatted_address>
</code>```

But when I get xml file through PHP

```<code>$xml = simplexml_load_file($url);
var_dump($xml)
</code>```

result :

```<code>public 'formatted_address' => string '57-79 Rue des Merciers, 17000 Rochelle, France' (length=46)
</code>```

the word 'La' before 'Rochelle' just disapear ... That my problem. And it's not a unique case (I can post more example).

I try also try with file_get_contents, curl, wget ... Same result

答:
This is because the formatted street address is locale-aware and reacts to your browser's accept-language header, which probably is fr-FR.

If you would encode a position in London, you would get Londres in a french-language browser, London in an english one, Lontoo in a finnish one etc.

Use the language parameter to force the language.

```<code>http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&
region=fr&latlng=46.16141,-1.149797&language=fr
</code>```

Title: GMaps api Geocode strange behavior

Body:
I'm using gmaps apiv3 webservice to geocode with latlng couple. It's pretty simple but I have a strange behavior for some data.

Eq:

http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&region=fr&latlng=46.16141,-1.149797

Next I open url with a navigator (firefox / chrome) and at line formatted_address the value is :

<formatted_address>57-79 Rue des Merciers, 17000 La Rochelle, France</formatted_address>

But when I get xml file through PHP

$xml = simplexml_load_file($url);
var_dump($xml)

result :

public 'formatted_address' => string '57-79 Rue des Merciers, 17000 Rochelle, France' (length=46)

the word 'La' before 'Rochelle' just disapear ... That my problem. And it's not a unique case (I can post more example).

I try also try with file_get_contents, curl, wget ... Same result

Body:
This is because the formatted street address is locale-aware and reacts to your browser's accept-language header, which probably is fr-FR.

If you would encode a position in London, you would get Londres in a french-language browser, London in an english one, Lontoo in a finnish one etc.

Use the language parameter to force the language.

http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&
region=fr&latlng=46.16141,-1.149797&language=fr


问:
Doctrine 2 and Postgres, serial field on non primary key columns
How can I use serial datatype in Doctrine 2 on non primary key columns?

Doctrine can use serial column as primary key with generator strategy set to SEQUENCE or IDENTITY but generator can not be used on non primary key columns.

I have table like this:

create table test (
    id integer not null generated by default as identity,
    order serial
)
constraint test_pk primary key (id)
```

<p>Doctrine entity:</p>

```App\Entity\Test:
    type: entity
    table: test

    id:
        id:
            type: integer
            nullable: false
            id: true
            generator:
                strategy: SEQUENCE
            sequenceGenerator:
                sequenceName: test_id_seq
    fields:
        order:
            type: integer
            nullable: false
            column: '"order"'
```

<p>What I want is that when I insert new row into this table, I don't have to specify order explicitly but db should take care of it. </p>

<p>In principle resulting sql code should look like this:</p>

<pre class="lang-sql prettyprint-override"><code>insert into test (DEFAULT, DEFAULT);
</code>```

Without any configuration, doctrine try to insert null into column "order" resulting in error "can't insert null value into not null field"

What I tried

I tried to set default value for "order" property inside php entity class, like this:

private $order = 'DEFAULT'
```

<p>but that erred out as "invalid syntax for integer"</p>

<p>Then I tried to put options into yaml definition like this:</p>

```fields:
        order:
            type: integer
            nullable: false
            column: '"order"'
            options:
                default: DEFAULT
```

<p>That did't make any difference.</p>

<p>Than I tried to make custom type named order but that failed too.</p>

<p>Code for custom type:</p>

<pre class="lang-php prettyprint-override"><code>use Doctrine\DBAL\Types\Type;

class OrderType extends Type
{
    public function getName(): string
    {
        return 'order';
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if (is_numeric($value)) {
            return $value;
        }

        return 'DEFAULT';
    }

    public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform)
    {
        return 'DEFAULT';
    }

    public function canRequireSQLConversion(): bool
    {
        return true;
    }

    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return 'serial';
    }
}
</code>```

This ends in error "SQLSTATE[HY093]: Invalid parameter number: parameter was not defined" which is problem with method convertToDatabaseValueSQL. When I comment it out and use default implementation, error "SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for integer: "DEFAULT""

It still quote word DEFAULT but I need it to be not quoted, it must used as keyword not as string.

I think custom type should work shomehow. In old Zend Framework v1 there was class Zend_Db_Exp which when used in sql statements was not quoted and value was used as is. I think I need something similar here.

Version info

PHP 7.3

Postgres 11

Doctrine ORM 2.6 (I'll upgrade if needed)

答:
DB trigger can be used to manage misbehaving clients, in this case Doctrine 2 based app.

Create trigger function:

```<code>create or replace function public."t_setDefaultValueOnOrderField"()
    returns trigger as
$body$
declare
    fq_table_name text := '"' || TG_TABLE_SCHEMA || '"' || '.' || '"' || TG_TABLE_NAME || '"';
    sequence_name text := pg_get_serial_sequence(fq_table_name, 'order');
begin
    if NEW.order is null then
        NEW.order := nextval(sequence_name);
    end if;

    return NEW;
end;
$body$ language plpgsql;
</code>```

And attach it to table:

create trigger "setDefaultValueOnOrderField"
    before insert
    on public.test
    for each row
execute procedure public."t_setDefaultValueOnOrderField"();
```

This is an ad hoc trigger for order field only, it may be adapted to handle any serial field present in target table.

Until better solution is found, this will remain as accepted answer.

Body:
How can I use serial datatype in Doctrine 2 on non primary key columns?

Doctrine can use serial column as primary key with generator strategy set to SEQUENCE or IDENTITY but generator can not be used on non primary key columns.

I have table like this:

create table test (
    id integer not null generated by default as identity,
    order serial
)
constraint test_pk primary key (id)

Doctrine entity:

App\Entity\Test:
    type: entity
    table: test

    id:
        id:
            type: integer
            nullable: false
            id: true
            generator:
                strategy: SEQUENCE
            sequenceGenerator:
                sequenceName: test_id_seq
    fields:
        order:
            type: integer
            nullable: false
            column: '"order"'

What I want is that when I insert new row into this table, I don't have to specify order explicitly but db should take care of it.

In principle resulting sql code should look like this:

insert into test (DEFAULT, DEFAULT);

Without any configuration, doctrine try to insert null into column "order" resulting in error "can't insert null value into not null field"

What I tried

I tried to set default value for "order" property inside php entity class, like this:

private $order = 'DEFAULT'

but that erred out as "invalid syntax for integer"

Then I tried to put options into yaml definition like this:

fields:
        order:
            type: integer
            nullable: false
            column: '"order"'
            options:
                default: DEFAULT

That did't make any difference.

Than I tried to make custom type named order but that failed too.

Code for custom type:

use Doctrine\DBAL\Types\Type;

class OrderType extends Type
{
    public function getName(): string
    {
        return 'order';
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if (is_numeric($value)) {
            return $value;
        }

        return 'DEFAULT';
    }

    public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform)
    {
        return 'DEFAULT';
    }

    public function canRequireSQLConversion(): bool
    {
        return true;
    }

    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return 'serial';
    }
}

This ends in error "SQLSTATE[HY093]: Invalid parameter number: parameter was not defined" which is problem with method convertToDatabaseValueSQL. When I comment it out and use default implementation, error "SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for integer: "DEFAULT""

It still quote word DEFAULT but I need it to be not quoted, it must used as keyword not as string.

I think custom type should work shomehow. In old Zend Framework v1 there was class Zend_Db_Exp which when used in sql statements was not quoted and value was used as is. I think I need something similar here.

Version info

PHP 7.3

Postgres 11

Doctrine ORM 2.6 (I'll upgrade if needed)

Body:
DB trigger can be used to manage misbehaving clients, in this case Doctrine 2 based app.

Create trigger function:

create or replace function public."t_setDefaultValueOnOrderField"()
    returns trigger as
$body$
declare
    fq_table_name text := '"' || TG_TABLE_SCHEMA || '"' || '.' || '"' || TG_TABLE_NAME || '"';
    sequence_name text := pg_get_serial_sequence(fq_table_name, 'order');
begin
    if NEW.order is null then
        NEW.order := nextval(sequence_name);
    end if;

    return NEW;
end;
$body$ language plpgsql;

And attach it to table:

create trigger "setDefaultValueOnOrderField"
    before insert
    on public.test
    for each row
execute procedure public."t_setDefaultValueOnOrderField"();

This is an ad hoc trigger for order field only, it may be adapted to handle any serial field present in target table.

Until better solution is found, this will remain as accepted answer.


问:
Kivy Launcher closes after loading .kv file with a working python script containing kivy code
I have been learning how to use kivy as an GUI and touch navagation for android. I won't post any code, that may limit any answer that could fix the problem. The problem I'm having is that I cannnot run python scripts with a .kv file named after the Main Class (all lowercase without 'app' in its name) with the build method. Kivy Loads the files, then a black screen, then kivy quits. I have been able to run python scripts that contain kivy code and they
work.

The question is how to get the Kivy Lauuncher for android  (version '1.9.1 1' from google play) to run a python file wtih a .kv file without close after opening.

I have tried tutorals and searched on the web (this site included), even kivy's own web site, and they have not worked.

I Will be greatly appreciate with any help, ideas, or suggestions.

答: Does this work on your PC? Also Kivy Launcher is quite outdated. You should try using Buildozer to make an APK. Also could you share your KV file? Maybe there is an error in that. Hope I helped!</p>


问:
Jenkins - How to access Build number variable and use it as a Prefix/Suffix of a log name during Post build actions
I am trying to use Jenkins' Build Number in the naming of a Log that I would want to be saved as a post build action

Will the below format work

C:\Jenkins\workspace\Jmeter_Jenkins_Test_Job\Jenkins_Results\"${env.BUILD_NUMBER}"results.jtl

答:
Without having laid my hands on a Jenkins installation for quite some time:

Yes, you can do that and it has been done before!

You could do something like:

```<code>pipeline {
    agent any
    stages {
        stage('test') {
             sh 'path/to/jmeter.bat -n -t ${env.WORKSPACE}my_test.jmx -l my_test${env.BUILD_ID}_${env.BUILD_NUMBER}.jtl'
        }
    }
}
</code>```

I would propose to create the HTML dashboard report first though and then publish that in Jenkins - you could use https://jenkins.io/doc/pipeline/steps/htmlpublisher/ to do that. Further you should avoid absolute paths in favor of using the WORKSPACE environment variable (see https://jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables for reference).
If you need some general idea of how to run the test via Jenkins you could have a look at https://code-maven.com/jenkins-pipeline-running-external-programs and https://jmeter.apache.org/usermanual/get-started.html#non_gui

If you already tried to achieve something and need more specific help, please come forward with some more detail.

Body:
Without having laid my hands on a Jenkins installation for quite some time:

Yes, you can do that and it has been done before!

You could do something like:

pipeline {
    agent any
    stages {
        stage('test') {
             sh 'path/to/jmeter.bat -n -t ${env.WORKSPACE}my_test.jmx -l my_test${env.BUILD_ID}_${env.BUILD_NUMBER}.jtl'
        }
    }
}

I would propose to create the HTML dashboard report first though and then publish that in Jenkins - you could use https://jenkins.io/doc/pipeline/steps/htmlpublisher/ to do that. Further you should avoid absolute paths in favor of using the WORKSPACE environment variable (see https://jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables for reference).
If you need some general idea of how to run the test via Jenkins you could have a look at https://code-maven.com/jenkins-pipeline-running-external-programs and https://jmeter.apache.org/usermanual/get-started.html#non_gui

If you already tried to achieve something and need more specific help, please come forward with some more detail.


问:
How to count specific column name in all tables of one SQL Server Database object
I want to count tables that have a specific column name. For instance, dbo.Management has 300 tables. Some tables have ProtectionKey column, and others don't.

I need a list of all the tables that have that column ProtectionKey, or at least a count of them.
I have looked into similar examples but those are either counting ALL columns in a DB or ALL columns in one table.

答:
I would personally use the sys objects for this, as INFORMATION_SCHEMA can return incorrect information:

```<code>SELECT s.[name] AS SchemaName,
       t.[name] AS TableName
FROM sys.schemas s
     JOIN sys.tables t ON s.schema_id = t.schema_id
     JOIN sys.columns c ON t.object_id = c.object_id
WHERE c.[name] = N'ProtectionKey';
</code>```

Body:
I would personally use the sys objects for this, as INFORMATION_SCHEMA can return incorrect information:

SELECT s.[name] AS SchemaName,
       t.[name] AS TableName
FROM sys.schemas s
     JOIN sys.tables t ON s.schema_id = t.schema_id
     JOIN sys.columns c ON t.object_id = c.object_id
WHERE c.[name] = N'ProtectionKey';


问:
Get username in magnolia
I am using the following command to get the username in a custom magnolia class:String userName = MgnlContext.getInstance().getJCRSession("website").getUserID();
Instead of getting the name of the user who is signed on in magnolia when the command was triggered I am getting admin for the value. How can I get the real user name - the one who signed on to magnolia?

答:
Actually to get current user, what you want is to either inject MgnlContext or get it via MgnlContext.getInstance() call.

Once you have context, you call ctx.getUser().getName() to get current user name.

Title: Get username in magnolia


问:
IS there a gui designer for wxwidgets in linux with Eclipse?
I want to build a GUI application using C++ and wxWidgets.
The problem is that I can not find an IDE with GUI (Form Designer) to use. I hope if eclipse has some thing like the QT designer.

any solutions ???

答: While I'm not sure of integrating with Eclipse, you can run wxGlade for designing interfaces, then export the code.</p>


问:
Birthdays in the scope of java.time.LocalDate
I'm trying to select birthdays (independent of the year) within a Collection of java.time.LocalDate . Why LocalDate ? because this type seems the best for birthday.

Let's say I want to filter the birthdays between March 6 and April 30 irrespective of the year.
How to do this ?

If I were to do it, I would replace the year in LocalDate  and use the method isAfter and isBefore.
The fact that I have to change the year is just a plain hack. Or I  used the wrong data type (LocalDate)

答:
```<code>List<LocalDate> birthdays = Arrays.asList(
        LocalDate.of(1990, Month.JANUARY, 5),
        LocalDate.of(1992, Month.MARCH, 7),
        LocalDate.of(1995, Month.MAY, 5));
MonthDay filterFrom = MonthDay.of(Month.MARCH, 6);
MonthDay filterTo = MonthDay.of(Month.APRIL, 30);

List<LocalDate> filteredDates = birthdays.stream()
        .filter(date -> {
            MonthDay md = MonthDay.from(date);
            return md.compareTo(filterFrom) >= 0 && md.compareTo(filterTo) <= 0;
        })
        .collect(Collectors.toList());

System.out.println(filteredDates);
</code>```


问:
find the user entered value or sum the row values
i need get the invoice number which has the particular value in price column, if not all the invoice numbers which have the sum value of that particular value in price column ..how to write an sql query for that

i have attached the data of my table
Data

invoice     price
v1         1000
v2         200
v3         35
v4         500
v5         50
v6         300
v7         400```

expected output :

if(input 500) found =>then found v4

else(sum of(v2,v6)

答:
You can find all combinations of 1 or two invoices that meet your conditions:

```<code>select d1.invoice, d1.price,
       (case when d2.invoice <> d1.invoice then d2.invoice end) as invoice2,
       (case when d2.invoice <> d1.invoice then d2.price end) as price2
from data d1 left join
     data d2
     on d1.invoice <= d2.invoice
where (d1.price = 500 and d2.invoice = d1.invoice) or
      (d1.price + d2.price) = 500
</code>```

Here is a db<>fiddle.

If you want larger combinations, add more joins.

Body:
i need get the invoice number which has the particular value in price column, if not all the invoice numbers which have the sum value of that particular value in price column ..how to write an sql query for that

i have attached the data of my table
Data

invoice     price
v1         1000
v2         200
v3         35
v4         500
v5         50
v6         300
v7         400

expected output :

if(input 500) found =>then found v4

else(sum of(v2,v6)

Body:
You can find all combinations of 1 or two invoices that meet your conditions:

select d1.invoice, d1.price,
       (case when d2.invoice <> d1.invoice then d2.invoice end) as invoice2,
       (case when d2.invoice <> d1.invoice then d2.price end) as price2
from data d1 left join
     data d2
     on d1.invoice <= d2.invoice
where (d1.price = 500 and d2.invoice = d1.invoice) or
      (d1.price + d2.price) = 500

Here is a db<>fiddle.

If you want larger combinations, add more joins.


问:
I'm using Visual studio 2019 and my project's name ends with .Sln insted of .cpp
I'm new to programming I use visual studio 2019 and when I'm creating a new project the project's name always end with .Sln instead of .cpp</p>

答: .sln is the file visual studio uses to organize the project. I believe you will find one or multiple .cpp files in your project directory.</p>


问:
Do ASCII Point Clouds need R G B data?
I am trying to open NASA's Clementine LIDAR data of the Lunar surface (Link: https://pds-geosciences.wustl.edu/missions/clementine/lidar.html). The data is saved as a *.tab file which is really an ASCII file. When I look for the data I need (x,y,z,r,g,b) I can only find data points x,y,z but not r,g,b.

Main Question If my goal is to open this file in CloudCompare and develop a mesh/dem file from this, do I need r,g,b data?

Side Questions If so, how do you recommend I get it from data that is from the 90s? Or atleast, how would I go about opening this.

答: You do not need the RGB data to open it on CloudCompare, just the point coordinates. There is no way of retrieving the radiometric information of this point cloud unless you have some imagery of the same epoch. Then you could associate the RGB to the point cloud by using collinearity equations, for instance.

Title: Do ASCII Point Clouds need R G B data?


问:
Kivy ScreenManager gives me a black screen
I have been trying to create a ping pong game using kivy. I followed the tutorial on their website and it worked perfectly! However I wanted to add a start screen. I looked on Google and saw that I should use Kivy's Screen Manager. I put it in my code but however when I press the start button it just does nothing and gives me a black screen. I have been trying to figure it out, but I do not see what is wrong! Probably becuase I do not have much experience with Kivy. Here is my code.

main.py

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition

class PingPongPaddle(Widget):

    score = NumericProperty(0)

    def bounce_ball(self, ball):
        if self.collide_widget(ball):
            vx, vy = ball.velocity
            offset = (ball.center_y - self.center_y) / (self.height / 2)
            bounced = Vector(-1 * vx, vy)
            vel = bounced * 1.1
            ball.velocity = vel.x, vel.y + offset
class PingPongBall(Widget):
    #Velocity on x and y axis
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)

    #So ball.velocity can be used
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    #Moves the ball one step
    def move(self):
        self.pos = Vector(*self.velocity) + self.pos

class PingPongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)

    def serve_ball(self, vel=(8, 0)):
        self.ball.center = self.center
        self.ball.velocity = vel
    def update(self, dt):
        self.ball.move()
        #Bounce off the paddles
        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)
        #Bounce off top and bottom
        if (self.ball.y < 0) or (self.ball.top > self.height):
            self.ball.velocity_y *= -1

        #Went off the side
        if self.ball.x < self.x:
            self.player2.score += 1
            self.serve_ball(vel=(4, 0))
        if self.ball.x > self.width:
            self.player1.score += 1
            self.serve_ball(vel=(-4, 0))

    def on_touch_move(self, touch):
        #To sense if screen is touched
        if touch.x < self.width / 3:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3:
            self.player2.center_y = touch.y

class GameScreen(Screen):
    def play(self):
        global game
        game = PingPongGame()
        game.serve_ball()
        #Runs every 60th of a second
        Clock.schedule_interval(game.update, 1.0/60.0)
        return game

class MainScreen(Screen):
    pass

class PingPongApp(App):
    def build(self):
        screen_manager = ScreenManager(transition=SlideTransition())

        screen_manager.add_widget(MainScreen(name="main"))
        screen_manager.add_widget(GameScreen(name="game"))
        return screen_manager

if __name__ == "__main__":
    PingPongApp().run()
</code>```

pingpong.kv

```<code>#:kivy 1.11.1

<MainScreen>:
    BoxLayout:
        Button:
            text: "Start!"
            on_press: root.manager.current = "game"
<GameScreen>:
    on_enter: self.play()

<PingPongBall>:
    size: 75, 75
    canvas:
        Ellipse:
            pos: self.pos
            size: self.size

<PingPongPaddle>:
    size: 50, 400
    canvas:
        Rectangle:
            pos:self.pos
            size:self.size

<PingPongGame>:
    ball: PingPong_ball
    player1: player_left
    player2: player_right

    canvas:
        Rectangle:
            pos: self.center_x - 5, 0
            size: 20, self.height

    Label:
        font_size: 140
        center_x: root.width / 4
        top: root.top - 50
        text: str(root.player1.score)

    Label:
        font_size: 140
        center_x: root.width * 3 / 4
        top: root.top - 50
        text: str(root.player2.score)

    Label:
        font_size: 35
        center_x: root.width * 6/7
        top: root.top - 500
        text: "by Me"

    PingPongBall:
        id: PingPong_ball
        center: self.parent.center

    PingPongPaddle:
        id: player_left
        x: root.x
        center_y: root.center_y

    PingPongPaddle:
        id: player_right
        x: root.width - self.width
        center_y: root.center_y

</code>```

Thanks in advance!

答:
I am new around here, but I think this may help When I use Kivy I also import the "screen" and use that. Here it is:

```<code>        self.removeuser = RemoveUser()
    screen = Screen(name="RemoveUser") # This will be the naem of screen to be called
    screen.add_widget(self.removeuser)
    self.screen_manager.add_widget(screen)
</code>```

That should then work, return the self.screen_manager
Then for your Start button make a function which does

```<code>PingPongApp.screen_manger.current = "<name of start screen>"
</code>```

Body:
I have been trying to create a ping pong game using kivy. I followed the tutorial on their website and it worked perfectly! However I wanted to add a start screen. I looked on Google and saw that I should use Kivy's Screen Manager. I put it in my code but however when I press the start button it just does nothing and gives me a black screen. I have been trying to figure it out, but I do not see what is wrong! Probably becuase I do not have much experience with Kivy. Here is my code.

main.py

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition

class PingPongPaddle(Widget):

    score = NumericProperty(0)

    def bounce_ball(self, ball):
        if self.collide_widget(ball):
            vx, vy = ball.velocity
            offset = (ball.center_y - self.center_y) / (self.height / 2)
            bounced = Vector(-1 * vx, vy)
            vel = bounced * 1.1
            ball.velocity = vel.x, vel.y + offset
class PingPongBall(Widget):
    #Velocity on x and y axis
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)

    #So ball.velocity can be used
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    #Moves the ball one step
    def move(self):
        self.pos = Vector(*self.velocity) + self.pos

class PingPongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)

    def serve_ball(self, vel=(8, 0)):
        self.ball.center = self.center
        self.ball.velocity = vel
    def update(self, dt):
        self.ball.move()
        #Bounce off the paddles
        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)
        #Bounce off top and bottom
        if (self.ball.y < 0) or (self.ball.top > self.height):
            self.ball.velocity_y *= -1

        #Went off the side
        if self.ball.x < self.x:
            self.player2.score += 1
            self.serve_ball(vel=(4, 0))
        if self.ball.x > self.width:
            self.player1.score += 1
            self.serve_ball(vel=(-4, 0))

    def on_touch_move(self, touch):
        #To sense if screen is touched
        if touch.x < self.width / 3:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3:
            self.player2.center_y = touch.y

class GameScreen(Screen):
    def play(self):
        global game
        game = PingPongGame()
        game.serve_ball()
        #Runs every 60th of a second
        Clock.schedule_interval(game.update, 1.0/60.0)
        return game

class MainScreen(Screen):
    pass

class PingPongApp(App):
    def build(self):
        screen_manager = ScreenManager(transition=SlideTransition())

        screen_manager.add_widget(MainScreen(name="main"))
        screen_manager.add_widget(GameScreen(name="game"))
        return screen_manager

if __name__ == "__main__":
    PingPongApp().run()

pingpong.kv

#:kivy 1.11.1

<MainScreen>:
    BoxLayout:
        Button:
            text: "Start!"
            on_press: root.manager.current = "game"
<GameScreen>:
    on_enter: self.play()

<PingPongBall>:
    size: 75, 75
    canvas:
        Ellipse:
            pos: self.pos
            size: self.size

<PingPongPaddle>:
    size: 50, 400
    canvas:
        Rectangle:
            pos:self.pos
            size:self.size

<PingPongGame>:
    ball: PingPong_ball
    player1: player_left
    player2: player_right

    canvas:
        Rectangle:
            pos: self.center_x - 5, 0
            size: 20, self.height

    Label:
        font_size: 140
        center_x: root.width / 4
        top: root.top - 50
        text: str(root.player1.score)

    Label:
        font_size: 140
        center_x: root.width * 3 / 4
        top: root.top - 50
        text: str(root.player2.score)

    Label:
        font_size: 35
        center_x: root.width * 6/7
        top: root.top - 500
        text: "by Me"

    PingPongBall:
        id: PingPong_ball
        center: self.parent.center

    PingPongPaddle:
        id: player_left
        x: root.x
        center_y: root.center_y

    PingPongPaddle:
        id: player_right
        x: root.width - self.width
        center_y: root.center_y

Thanks in advance!

Body:
I am new around here, but I think this may help When I use Kivy I also import the "screen" and use that. Here it is:

        self.removeuser = RemoveUser()
    screen = Screen(name="RemoveUser") # This will be the naem of screen to be called
    screen.add_widget(self.removeuser)
    self.screen_manager.add_widget(screen)

That should then work, return the self.screen_manager
Then for your Start button make a function which does

PingPongApp.screen_manger.current = "<name of start screen>"