问:
Sending DM with embeds using discord.py
I have tried many things but I can't get discord.py to send a message with embeds. But I have gotten it to send a normal message when a command is typed using this code.

```<code>@client.event
async def on_message(message):
  msg = message.content

  if msg.startswith('$helpme'):
    await message.author.send("this text would be sent via dm, but with no embeds...")
</code>```

It would be a help menu which the bot would the dm the user when $helpme is typed. Problem is I can't get it to send this embed code.

```<code>  embed=discord.Embed(title=" Help", description="I am here to help!", color=0x0000ff)
  embed.set_author(name="Meerdus", icon_url="https://cdn.discordapp.com/attachments/834885490451808286/939646209092616312/M.png")
  embed.add_field(name="$helpme", value="Shows this menu!", inline=False)
  embed.add_field(name="$kick", value="Kick a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$ban", value="Ban a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$unban", value="Unban a member if you have Administrator permissions.", inline=False)
  embed.add_field(name="$lock", value="Lock a channel if you have the permission to manage channels!", inline=False)
  embed.add_field(name="$meme", value="Display a random clean meme! :)", inline=False)
  embed.add_field(name="$doggo", value="Show a random dog picture and dog fact!", inline=False)
  embed.add_field(name="$kitty", value="Show a random cat picture and cat fact!", inline=False)
  embed.add_field(name="$birdy", value="Show a random bird picture and bird fact!", inline=False)
  embed.add_field(name="$randomnum", value="Display a random number between 1 and 100!", inline=False)
  embed.add_field(name="$tictactoe", value="Play tictactoe with two people by specifing <command> <yourusername> <secondplayersusername>", inline=False)
  embed.add_field(name="DONT ACTUALLY ENTER THE <>", value="You have to enter the things said inside them.", inline=False)
  await ctx.send(embed=embed)
</code>```

答:
Since you aren't using a bot command, you don't use ctx. This is also mainly because you haven't passed (told the function about) ctx. Instead, use message.author.send().

See the examples below:

```<code>message.author.send(embed=embed) # Send to the author
message.channel.send(embed=embed) # Send to the channel
</code>```

Title: Sending DM with embeds using discord.py

Body:
I have tried many things but I can't get discord.py to send a message with embeds. But I have gotten it to send a normal message when a command is typed using this code.

@client.event
async def on_message(message):
  msg = message.content

  if msg.startswith('$helpme'):
    await message.author.send("this text would be sent via dm, but with no embeds...")

It would be a help menu which the bot would the dm the user when $helpme is typed. Problem is I can't get it to send this embed code.

  embed=discord.Embed(title=" Help", description="I am here to help!", color=0x0000ff)
  embed.set_author(name="Meerdus", icon_url="https://cdn.discordapp.com/attachments/834885490451808286/939646209092616312/M.png")
  embed.add_field(name="$helpme", value="Shows this menu!", inline=False)
  embed.add_field(name="$kick", value="Kick a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$ban", value="Ban a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$unban", value="Unban a member if you have Administrator permissions.", inline=False)
  embed.add_field(name="$lock", value="Lock a channel if you have the permission to manage channels!", inline=False)
  embed.add_field(name="$meme", value="Display a random clean meme! :)", inline=False)
  embed.add_field(name="$doggo", value="Show a random dog picture and dog fact!", inline=False)
  embed.add_field(name="$kitty", value="Show a random cat picture and cat fact!", inline=False)
  embed.add_field(name="$birdy", value="Show a random bird picture and bird fact!", inline=False)
  embed.add_field(name="$randomnum", value="Display a random number between 1 and 100!", inline=False)
  embed.add_field(name="$tictactoe", value="Play tictactoe with two people by specifing <command> <yourusername> <secondplayersusername>", inline=False)
  embed.add_field(name="DONT ACTUALLY ENTER THE <>", value="You have to enter the things said inside them.", inline=False)
  await ctx.send(embed=embed)

Body:
Since you aren't using a bot command, you don't use ctx. This is also mainly because you haven't passed (told the function about) ctx. Instead, use message.author.send().

See the examples below:

message.author.send(embed=embed) # Send to the author
message.channel.send(embed=embed) # Send to the channel


来源: stackexchange

问:
Cant see http traffic using Proxyman when connecting to local machine
I am developing an app with a Node.js API with React Native client using Expo.
I am using a IOS emulator to test.

I have my API remotely on NodeChef and locally on my machine for dev.

Im using Proxyman 2.35.4 to watch for traffic. It is woking for the remote API
and I can see traffic under the "Apps" then "Expo" then it has the title of my remote endpoint "xx-xxxx-13442.nodechef.com".

But I cannot see traffic when I connect to the local machine API 192.168.1.4:4000. I have looked
all thru Apps and Domains folder.

Any ideas why?
Malcolm

答:
By default, all local traffic doesn't go through HTTP Proxy Server (Proxyman), so you might not see any localhost traffic.

To fix it, you might set it as an alias name, which you can add in the /etc/hosts file.

Here is the step:

Open /etc/hosts file

Add the following

```<code>127.0.0.1 myserver.local
::1 myserver.local
</code>```

Save

Try to call myserver.local:4000

Then, Proxyman can capture this localhost traffic.

Ref: https://docs.proxyman.io/troubleshooting/couldnt-see-any-request-from-localhost-server

ContentLicense: CC BY-SA 4.0

Body:
By default, all local traffic doesn't go through HTTP Proxy Server (Proxyman), so you might not see any localhost traffic.

To fix it, you might set it as an alias name, which you can add in the /etc/hosts file.

Here is the step:

Open /etc/hosts file

Add the following

127.0.0.1 myserver.local
::1 myserver.local

Save

Try to call myserver.local:4000

Then, Proxyman can capture this localhost traffic.

Ref: https://docs.proxyman.io/troubleshooting/couldnt-see-any-request-from-localhost-server


问:
What exactly is data record in Kafka Streams?
So I've read enough tutorials and official documentation, but everything that I've found on data record is pretty much copy-pasting from one source to another:

A stream partition is an, ordered, replayable, and fault-tolerant sequence of immutable data records, where a data record is defined
as a key-value pair.

Each stream partition is a totally ordered sequence of data records and maps to a Kafka topic partition. A data record in
the stream maps to a Kafka message from that topic.

So what exactly is data record? Since it maps kafka message is it safe to say that it is pretty much the same thing or is it sort of another object that has some sort of information regardig kafka message?

答:
A data record is nothing but a message which is structured as a key-value pair like name=smith or id=101.

Stream is a high-level term used in the context of Kafka-streams and Kafka streams is a high-level API built on top of the core kafka-clients API to provide some additional functionality.

Generally, a stream is a flow of data, in this case it is a collection of messages or data-records.

So, when you say data record, it means a Kafka message only and it is not some other object that has some information (or metadata) about Kafka message. If you want to store that some other information termed as metadata, it is usually stored in headers of the Kafka message/data-record.


问:
How can I find out why my navbar links aren't clickable?
My navbar links aren't clickable and I can't figure out why. I'm trying to create a hero video with a black gradient on top of it. The navbar is transparant and the logo is aligned in the middle. My navbar links aren't working, I can't click them. How can I find out why?

This is the code I've created.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
li {
    list-style-type: none;
}
a {
    text-decoration: none;
    color: white;
}
nav {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.2);
    min-height: 5vh;
    position: absolute;
}

nav img {
    width: 15%;
    height: 15%;
}

.nav-links {
    display: flex;
    margin: 0px 20px;
}

.nav-links li {
    margin: 0px 5vh;
    font-family: 'Roboto', sans-serif;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-size: 14px;
}

.nav-links li:hover {
    cursor: pointer;
}

/***** Index *****/
/* Hero */
.index-hero video {
    width: 100%;
    height: 100vh;
    object-fit:cover;
}

.gradient {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background: linear-gradient(180deg,#000000 0%,#000000 100%);
    opacity: 0.5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
        <ul class="nav-links">
            <li>Home</li>
            <li>Lessen</li>
        </ul>

        <img src="img/logo.png">

        <ul class="nav-links">
            <li>Over ons</li>
            <li>Contact</li>
        </ul>
</nav>

    <header>
        <div class="index-hero">
            <div class="gradient"></div>
            <video
            loop
            muted
            autoplay
            preload="auto"
            src="img/promo.mp4"
            alt="Promotiefilmpje sportschool Burning Heart">
            </video>
        </div>
    </header></code>```

答: Seems like your .gradient element is covering everything else because of its absolute position. You can either define position: relative for header to make that the relative anchor of its .gradient child (which otherwise willl be body - hence the covering), o you can add pointer-events: none to .gradient to "let clicks go though it"

Body:
My navbar links aren't clickable and I can't figure out why. I'm trying to create a hero video with a black gradient on top of it. The navbar is transparant and the logo is aligned in the middle. My navbar links aren't working, I can't click them. How can I find out why?

This is the code I've created.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
li {
    list-style-type: none;
}
a {
    text-decoration: none;
    color: white;
}
nav {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.2);
    min-height: 5vh;
    position: absolute;
}

nav img {
    width: 15%;
    height: 15%;
}

.nav-links {
    display: flex;
    margin: 0px 20px;
}

.nav-links li {
    margin: 0px 5vh;
    font-family: 'Roboto', sans-serif;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-size: 14px;
}

.nav-links li:hover {
    cursor: pointer;
}

/***** Index *****/
/* Hero */
.index-hero video {
    width: 100%;
    height: 100vh;
    object-fit:cover;
}

.gradient {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background: linear-gradient(180deg,#000000 0%,#000000 100%);
    opacity: 0.5;
}

Home

Lessen

Over ons

Contact

            <video
            loop
            muted
            autoplay
            preload="auto"
            src="img/promo.mp4"
            alt="Promotiefilmpje sportschool Burning Heart">
            </video>


问:
flattern nested list with uneven column numbers into data frame in R
I face a challenge of binding a nested list into a dataframe for processing.

Edit: here below is the example of original nested data before I tried to flat them.

```<code>list(list(list(url = "https://lda.senate.gov/api/v1/filings/5e4bbd96-db94-4ea3-a310-7a7fb1e93fff/",
    filing_uuid = "5e4bbd96-db94-4ea3-a310-7a7fb1e93fff", filing_type = "Q1",
    filing_type_display = "1st Quarter - Report", filing_year = 2021L,
    filing_period = "first_quarter", filing_period_display = "1st Quarter (Jan 1 - Mar 31)",
    filing_document_url = "https://lda.senate.gov/filings/public/filing/5e4bbd96-db94-4ea3-a310-7a7fb1e93fff/print/",
    filing_document_content_type = "text/html", income = "15000.00",
    expenses = NULL, expenses_method = NULL, expenses_method_display = NULL,
    posted_by_name = "Christian Smith", dt_posted = "2021-04-30T10:20:59.217000-04:00",
    termination_date = NULL, registrant = list(id = 8214L, url = "https://lda.senate.gov/api/v1/registrants/8214/",
        house_registrant_id = 31113L, name = "CAPSTONE NATIONAL PARTNERS",
        description = "public affairs", address_1 = "501 Capitol Court NE",
        address_2 = "Suite 100", address_3 = NULL, address_4 = NULL,
        city = "Washington", state = "DC", state_display = "District of Columbia",
        zip = "20002", country = "US", country_display = "United States of America",
        ppb_country = "US", ppb_country_display = "United States of America",
        contact_name = "", contact_telephone = "", dt_updated = "2022-01-13T14:47:31.828778-05:00"),
    client = list(id = 111342L, url = "https://lda.senate.gov/api/v1/clients/111342/",
        client_id = 303L, name = "OSHKOSH CORPORATION", general_description = "manufacturing",
        client_government_entity = FALSE, client_self_select = NULL,
        state = "WI", state_display = "Wisconsin", country = "US",
        country_display = "United States of America", ppb_state = "WI",
        ppb_state_display = "Wisconsin", ppb_country = "US",
        ppb_country_display = "United States of America", effective_date = "2016-04-01"),
    lobbying_activities = list(list(general_issue_code = "BUD",
        general_issue_code_display = "Budget/Appropriations",
        description = "FY22 Appropriations", foreign_entity_issues = "",
        lobbyists = list(list(lobbyist = list(id = 63767L, prefix = NULL,
            prefix_display = NULL, first_name = "WILLIAM", nickname = NULL,
            middle_name = NULL, last_name = "STONE", suffix = NULL,
            suffix_display = NULL), covered_position = "Chief of Staff, Dave Obey: House Appropriations Committee",
            new = FALSE)), government_entities = list(list(id = 2L,
            name = "HOUSE OF REPRESENTATIVES"), list(id = 1L,
            name = "SENATE")))), conviction_disclosures = list(),
    foreign_entities = list(), affiliated_organizations = list())),
    list(list(url = "https://lda.senate.gov/api/v1/filings/177b995a-3be2-4127-b962-795e76974617/",
        filing_uuid = "177b995a-3be2-4127-b962-795e76974617",
        filing_type = "Q1", filing_type_display = "1st Quarter - Report",
        filing_year = 2021L, filing_period = "first_quarter",
        filing_period_display = "1st Quarter (Jan 1 - Mar 31)",
        filing_document_url = "https://lda.senate.gov/filings/public/filing/177b995a-3be2-4127-b962-795e76974617/print/",
        filing_document_content_type = "text/html", income = "22500.00",
        expenses = NULL, expenses_method = NULL, expenses_method_display = NULL,
        posted_by_name = "Doyce Boesch", dt_posted = "2021-04-30T11:22:12.233000-04:00",
        termination_date = NULL, registrant = list(id = 400677020L,
            url = "https://lda.senate.gov/api/v1/registrants/400677020/",
            house_registrant_id = NULL, name = "MR. DOYCE BOESCH",
            description = "Government Relations", address_1 = "4515 W Street NW",
            address_2 = NULL, address_3 = NULL, address_4 = NULL,
            city = "Washington", state = "DC", state_display = "District of Columbia",
            zip = "20007", country = "US", country_display = "United States of America",
            ppb_country = "US", ppb_country_display = "United States of America",
            contact_name = "DOYCE BOESCH", contact_telephone = "+1 202-731-9995",
            dt_updated = "2022-01-13T14:59:12.412096-05:00"),
        client = list(id = 194057L, url = "https://lda.senate.gov/api/v1/clients/194057/",
            client_id = 75L, name = "INVESTMENT COMPANY INSTITUTE",
            general_description = "Stock Market and Financial Services",
            client_government_entity = FALSE, client_self_select = FALSE,
            state = "DC", state_display = "District of Columbia",
            country = "US", country_display = "United States of America",
            ppb_state = NULL, ppb_state_display = NULL, ppb_country = "US",
            ppb_country_display = "United States of America",
            effective_date = "2012-07-01"), lobbying_activities = list(
            list(general_issue_code = "FIN", general_issue_code_display = "Financial Institutions/Investments/Securities",
                description = "providing awareness of members positions",
                foreign_entity_issues = "", lobbyists = list(
                  list(lobbyist = list(id = 52828L, prefix = NULL,
                    prefix_display = NULL, first_name = "DOYCE",
                    nickname = NULL, middle_name = NULL, last_name = "BOESCH",
                    suffix = NULL, suffix_display = NULL), covered_position = NULL,
                    new = FALSE)), government_entities = list(
                  list(id = 2L, name = "HOUSE OF REPRESENTATIVES"),
                  list(id = 1L, name = "SENATE")))), conviction_disclosures = list(),
        foreign_entities = list(), affiliated_organizations = list())))
</code>```

So taking this highly nested data, call it

```<code>my.data
</code>```

then I tried to flatten it by

```<code>flat.df <- lapply(my.data, function(i) list(unlist(i, recursive = F)))
</code>```

it sort of worked, but still each element in the flat.df list still have multiple sublists, for example "lobbying_activities", "lobbyists". And they are not expaned(I want the information inside).

But if I set recursive to "TRUE", then the flattened list have duplicated columns and most frustratingly I see some columns got lumped together (for example people's name got into expense column)

Ideally I want to flat such sublists in each table and make the whole thing in one table. Then join them into a dataframe by

```<code>df<- as.data.frame(do.call("rbind", flat.df))
</code>```

答:
tibbles are a nice format, as they support nested data.frames. I would aim for a tibble with 2 rows, a wide format. In it, each nested list element would be its own data.frame, which we could manipulate later when needed. I would do something like this:

```<code>library(tidyverse)
l = unlist(l, recursive = F)
ind_to_nest <- which(map_lgl(l[[1]], is.list))
non_tbl <- map(l, ~ .x[-ind_to_nest])
tbl <- map(l, ~ .x[ind_to_nest])

df <- bind_rows(non_tbl) %>%
  mutate(n = 1:n(), .before = 1) %>%
  mutate(data =  map(tbl,  ~ map(.x, ~flatten(.x) %>% bind_cols))) %>%
  unnest_wider(data, simplify = F)
</code>```

Note that this does throw a bunch of warnings. This is because of the name conflicts present within the list.

```<code>#> New names:
#> * id -> id...5
#> * id -> id...10
</code>```

Can be resolved by specifying a naming policy, or by rethinking how the data is read into R to resolve naming conflicts early.

```<code>#> Outer names are only allowed for unnamed scalar atomic inputs
</code>```

This is a bit tougher to resolve, but this issue is a starting point.

For analysis some cleaning of sub-tibbles can be performed when needed, as different tasks require different shapes.

Body:
I face a challenge of binding a nested list into a dataframe for processing.

Edit: here below is the example of original nested data before I tried to flat them.

list(list(list(url = "https://lda.senate.gov/api/v1/filings/5e4bbd96-db94-4ea3-a310-7a7fb1e93fff/",
    filing_uuid = "5e4bbd96-db94-4ea3-a310-7a7fb1e93fff", filing_type = "Q1",
    filing_type_display = "1st Quarter - Report", filing_year = 2021L,
    filing_period = "first_quarter", filing_period_display = "1st Quarter (Jan 1 - Mar 31)",
    filing_document_url = "https://lda.senate.gov/filings/public/filing/5e4bbd96-db94-4ea3-a310-7a7fb1e93fff/print/",
    filing_document_content_type = "text/html", income = "15000.00",
    expenses = NULL, expenses_method = NULL, expenses_method_display = NULL,
    posted_by_name = "Christian Smith", dt_posted = "2021-04-30T10:20:59.217000-04:00",
    termination_date = NULL, registrant = list(id = 8214L, url = "https://lda.senate.gov/api/v1/registrants/8214/",
        house_registrant_id = 31113L, name = "CAPSTONE NATIONAL PARTNERS",
        description = "public affairs", address_1 = "501 Capitol Court NE",
        address_2 = "Suite 100", address_3 = NULL, address_4 = NULL,
        city = "Washington", state = "DC", state_display = "District of Columbia",
        zip = "20002", country = "US", country_display = "United States of America",
        ppb_country = "US", ppb_country_display = "United States of America",
        contact_name = "", contact_telephone = "", dt_updated = "2022-01-13T14:47:31.828778-05:00"),
    client = list(id = 111342L, url = "https://lda.senate.gov/api/v1/clients/111342/",
        client_id = 303L, name = "OSHKOSH CORPORATION", general_description = "manufacturing",
        client_government_entity = FALSE, client_self_select = NULL,
        state = "WI", state_display = "Wisconsin", country = "US",
        country_display = "United States of America", ppb_state = "WI",
        ppb_state_display = "Wisconsin", ppb_country = "US",
        ppb_country_display = "United States of America", effective_date = "2016-04-01"),
    lobbying_activities = list(list(general_issue_code = "BUD",
        general_issue_code_display = "Budget/Appropriations",
        description = "FY22 Appropriations", foreign_entity_issues = "",
        lobbyists = list(list(lobbyist = list(id = 63767L, prefix = NULL,
            prefix_display = NULL, first_name = "WILLIAM", nickname = NULL,
            middle_name = NULL, last_name = "STONE", suffix = NULL,
            suffix_display = NULL), covered_position = "Chief of Staff, Dave Obey: House Appropriations Committee",
            new = FALSE)), government_entities = list(list(id = 2L,
            name = "HOUSE OF REPRESENTATIVES"), list(id = 1L,
            name = "SENATE")))), conviction_disclosures = list(),
    foreign_entities = list(), affiliated_organizations = list())),
    list(list(url = "https://lda.senate.gov/api/v1/filings/177b995a-3be2-4127-b962-795e76974617/",
        filing_uuid = "177b995a-3be2-4127-b962-795e76974617",
        filing_type = "Q1", filing_type_display = "1st Quarter - Report",
        filing_year = 2021L, filing_period = "first_quarter",
        filing_period_display = "1st Quarter (Jan 1 - Mar 31)",
        filing_document_url = "https://lda.senate.gov/filings/public/filing/177b995a-3be2-4127-b962-795e76974617/print/",
        filing_document_content_type = "text/html", income = "22500.00",
        expenses = NULL, expenses_method = NULL, expenses_method_display = NULL,
        posted_by_name = "Doyce Boesch", dt_posted = "2021-04-30T11:22:12.233000-04:00",
        termination_date = NULL, registrant = list(id = 400677020L,
            url = "https://lda.senate.gov/api/v1/registrants/400677020/",
            house_registrant_id = NULL, name = "MR. DOYCE BOESCH",
            description = "Government Relations", address_1 = "4515 W Street NW",
            address_2 = NULL, address_3 = NULL, address_4 = NULL,
            city = "Washington", state = "DC", state_display = "District of Columbia",
            zip = "20007", country = "US", country_display = "United States of America",
            ppb_country = "US", ppb_country_display = "United States of America",
            contact_name = "DOYCE BOESCH", contact_telephone = "+1 202-731-9995",
            dt_updated = "2022-01-13T14:59:12.412096-05:00"),
        client = list(id = 194057L, url = "https://lda.senate.gov/api/v1/clients/194057/",
            client_id = 75L, name = "INVESTMENT COMPANY INSTITUTE",
            general_description = "Stock Market and Financial Services",
            client_government_entity = FALSE, client_self_select = FALSE,
            state = "DC", state_display = "District of Columbia",
            country = "US", country_display = "United States of America",
            ppb_state = NULL, ppb_state_display = NULL, ppb_country = "US",
            ppb_country_display = "United States of America",
            effective_date = "2012-07-01"), lobbying_activities = list(
            list(general_issue_code = "FIN", general_issue_code_display = "Financial Institutions/Investments/Securities",
                description = "providing awareness of members positions",
                foreign_entity_issues = "", lobbyists = list(
                  list(lobbyist = list(id = 52828L, prefix = NULL,
                    prefix_display = NULL, first_name = "DOYCE",
                    nickname = NULL, middle_name = NULL, last_name = "BOESCH",
                    suffix = NULL, suffix_display = NULL), covered_position = NULL,
                    new = FALSE)), government_entities = list(
                  list(id = 2L, name = "HOUSE OF REPRESENTATIVES"),
                  list(id = 1L, name = "SENATE")))), conviction_disclosures = list(),
        foreign_entities = list(), affiliated_organizations = list())))

So taking this highly nested data, call it

my.data

then I tried to flatten it by

flat.df <- lapply(my.data, function(i) list(unlist(i, recursive = F)))

it sort of worked, but still each element in the flat.df list still have multiple sublists, for example "lobbying_activities", "lobbyists". And they are not expaned(I want the information inside).

But if I set recursive to "TRUE", then the flattened list have duplicated columns and most frustratingly I see some columns got lumped together (for example people's name got into expense column)

Ideally I want to flat such sublists in each table and make the whole thing in one table. Then join them into a dataframe by

df<- as.data.frame(do.call("rbind", flat.df))

Body:
tibbles are a nice format, as they support nested data.frames. I would aim for a tibble with 2 rows, a wide format. In it, each nested list element would be its own data.frame, which we could manipulate later when needed. I would do something like this:

library(tidyverse)
l = unlist(l, recursive = F)
ind_to_nest <- which(map_lgl(l[[1]], is.list))
non_tbl <- map(l, ~ .x[-ind_to_nest])
tbl <- map(l, ~ .x[ind_to_nest])

df <- bind_rows(non_tbl) %>%
  mutate(n = 1:n(), .before = 1) %>%
  mutate(data =  map(tbl,  ~ map(.x, ~flatten(.x) %>% bind_cols))) %>%
  unnest_wider(data, simplify = F)

Note that this does throw a bunch of warnings. This is because of the name conflicts present within the list.

#> New names:
#> * id -> id...5
#> * id -> id...10

Can be resolved by specifying a naming policy, or by rethinking how the data is read into R to resolve naming conflicts early.

#> Outer names are only allowed for unnamed scalar atomic inputs

This is a bit tougher to resolve, but this issue is a starting point.

For analysis some cleaning of sub-tibbles can be performed when needed, as different tasks require different shapes.


答:
Add z-index:1; to your navbar element in css code.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
li {
    list-style-type: none;
}
a {
    text-decoration: none;
    color: white;
}
nav {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.2);
    min-height: 5vh;
    position: absolute;
   z-index:1;
}

nav img {
    width: 15%;
    height: 15%;
}

.nav-links {
    display: flex;
    margin: 0px 20px;
}

.nav-links li {
    margin: 0px 5vh;
    font-family: 'Roboto', sans-serif;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-size: 14px;
}

.nav-links li:hover {
    cursor: pointer;
}

/***** Index *****/
/* Hero */
.index-hero video {
    width: 100%;
    height: 100vh;
    object-fit:cover;
}

.gradient {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background: linear-gradient(180deg,#000000 0%,#000000 100%);
    opacity: 0.5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
        <ul class="nav-links">
            <li>Home</li>
            <li>Lessen</li>
        </ul>

        <img src="img/logo.png">

        <ul class="nav-links">
            <li>Over ons</li>
            <li>Contact</li>
        </ul>
</nav>

    <header>
        <div class="index-hero">
            <div class="gradient"></div>
            <video
            loop
            muted
            autoplay
            preload="auto"
            src="img/promo.mp4"
            alt="Promotiefilmpje sportschool Burning Heart">
            </video>
        </div>
    </header></code>```

Title: How can I find out why my navbar links aren't clickable?

Body:
Add z-index:1; to your navbar element in css code.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
li {
    list-style-type: none;
}
a {
    text-decoration: none;
    color: white;
}
nav {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.2);
    min-height: 5vh;
    position: absolute;
   z-index:1;
}

nav img {
    width: 15%;
    height: 15%;
}

.nav-links {
    display: flex;
    margin: 0px 20px;
}

.nav-links li {
    margin: 0px 5vh;
    font-family: 'Roboto', sans-serif;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-size: 14px;
}

.nav-links li:hover {
    cursor: pointer;
}

/***** Index *****/
/* Hero */
.index-hero video {
    width: 100%;
    height: 100vh;
    object-fit:cover;
}

.gradient {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background: linear-gradient(180deg,#000000 0%,#000000 100%);
    opacity: 0.5;
}

<nav>
        <ul class="nav-links">
            <li><a href="home.html">Home</a></li>
            <li><a href="home.html">Lessen</a></li>
        </ul>

        <img src="img/logo.png">

        <ul class="nav-links">
            <li><a href="home.html">Over ons</a></li>
            <li><a href="home.html">Contact</a></li>
        </ul>
</nav>

    <header>
        <div class="index-hero">
            <div class="gradient"></div>
            <video
            loop
            muted
            autoplay
            preload="auto"
            src="img/promo.mp4"
            alt="Promotiefilmpje sportschool Burning Heart">
            </video>
        </div>
    </header>


问:
Azure Datafactory , multi level complex csv structure
We have to deliver a rather complex csv structure and we would like to use Data factory for this.
The structure has multiple levels with a global header and trailer+ a subheader (per topic) and it's detail lines.
The first column defines which type of line it is. I've simplified the real format just to highlight the questions I have.

HEADER - common data like export date and number sequence
SUBHEADER - topic name 1
DETAIL - detail line of above topic
DETAIL - detail line of above topic
DETAIL - detail line of above topic
SUBHEADER - topic name 2
DETAIL - detail line of above topic
DETAIL - detail line of above topic
DETAIL - detail line of above topic
TRAILER - A closing line with total linecount

The source data would be the detail lines + the topic name.

There are 2 problems I'm unable to solve :

How do I convert the source data into the complex SUBHEADER + DETAIL format. To be honest no clue on how to approach this.

Is there a way to add the global header + trailer with total linecount via Datafactory? An alternative would be doing this with an azure function.

All suggestions are welcome ...

Regards,
Sven Peeters

答:
You have a couple of choices with Azure Data Factory:

take an ELT approach where you use some type of compute (eg a SQL database, Databricks, Azure Batch, Azure Function or Azure Synapse serverless SQL pools if you're working in Synapse) to do the hard work structuring the file and outputting it.  ADF is really just doing the orchestration (telling other processes what to do in what order) and handling the output.  The compute is handling the fiddly bit.

take an ETL approach and use Mapping Data Flows.  This is a low-code approach which uses on-demand Spark clusters in the background.  You do not have to manage them.

I would be tempted to use SQL to do this, particularly if you already have some in your infrastructure.  A simplified example:

```<code>;WITH cte AS (
SELECT 10 sortOrder, 'someHeader' main
UNION ALL
SELECT 20, 'col1, col2, col3'
--FROM someTable
UNION ALL
SELECT 30, 'someFooter'
)
SELECT main
FROM cte
ORDER BY sortOrder;
</code>```

If you've got time, why not try both approaches as a proof-of-concept, see which works best for you, your data and your organisation.  Look at factors such at time to develop, maintainability, how flexible, cost etc

Body:
You have a couple of choices with Azure Data Factory:

take an ELT approach where you use some type of compute (eg a SQL database, Databricks, Azure Batch, Azure Function or Azure Synapse serverless SQL pools if you're working in Synapse) to do the hard work structuring the file and outputting it.  ADF is really just doing the orchestration (telling other processes what to do in what order) and handling the output.  The compute is handling the fiddly bit.

take an ETL approach and use Mapping Data Flows.  This is a low-code approach which uses on-demand Spark clusters in the background.  You do not have to manage them.

I would be tempted to use SQL to do this, particularly if you already have some in your infrastructure.  A simplified example:

;WITH cte AS (
SELECT 10 sortOrder, 'someHeader' main
UNION ALL
SELECT 20, 'col1, col2, col3'
--FROM someTable
UNION ALL
SELECT 30, 'someFooter'
)
SELECT main
FROM cte
ORDER BY sortOrder;

If you've got time, why not try both approaches as a proof-of-concept, see which works best for you, your data and your organisation.  Look at factors such at time to develop, maintainability, how flexible, cost etc


问:
VS Code insert predefined characters at the end of current line
I would like to assign a keyboard shortcut which-

puts the cursor at the end of current line

and then, insert ->

I googled a lot. But not found any satisfactory solution.

Any idea ?

答:
If your cursor doesn't start at the end of the line you will need to use a macro extension to run two commands.  Using multi-command below, make this keybinding (in your keybindings.json):

```<code>{
  "key": "alt+w",           // whatever keybinding you like
  "command": "extension.multiCommand.execute",
  "args": {
    "sequence": [
      "cursorEnd",
      {
        "command": "type",
        "args": { "text": "->" }
      }
    ]
  },
  // "when": "editorLangId == php"  // for example
}
</code>```

Body:
If your cursor doesn't start at the end of the line you will need to use a macro extension to run two commands.  Using multi-command below, make this keybinding (in your keybindings.json):

{
  "key": "alt+w",           // whatever keybinding you like
  "command": "extension.multiCommand.execute",
  "args": {
    "sequence": [
      "cursorEnd",
      {
        "command": "type",
        "args": { "text": "->" }
      }
    ]
  },
  // "when": "editorLangId == php"  // for example
}


问:
How to auto increment counter by repeteaded values in a column
I Have a data frame with the column name and I need to create the column seq, which allows me identify the different times that a name appears in the data frame, it's important to preserve the order.

```<code>import pandas as pd

data = {'name': ['Tom', 'Joseph','Joseph','Joseph', 'Tom', 'Tom', 'John','Tom','Tom','John','Joseph']
        , 'seq': ['Tom 0', 'Joseph 0','Joseph 0','Joseph 0', 'Tom 1', 'Tom 1', 'John 0','Tom 2','Tom 2','John 1','Joseph 1']}

df = pd.DataFrame(data)

print(df)

</code>```
```<code>      name       seq
0      Tom     Tom 0
1   Joseph  Joseph 0
2   Joseph  Joseph 0
3   Joseph  Joseph 0
4      Tom     Tom 1
5      Tom     Tom 1
6     John    John 0
7      Tom     Tom 2
8      Tom     Tom 2
9     John    John 1
10  Joseph  Joseph 1
</code>```

答:
Assuming your data frame is indexes sequentiallly (0, 1, 2, 3, ...):

Group the data frame by name

For each group, apply a gap-and-island algorithm: every time the index jumps by more than 1, create a new island

def sequencer(group):
    idx = group.index.to_series()
    # Every time the index has a gap >1, create a new island
    return idx.diff().ne(1).cumsum().sub(1)

seq = df.groupby('name').apply(sequencer).droplevel(0).rename('seq')
df.merge(seq, left_index=True, right_index=True)
```

Body:
I Have a data frame with the column name and I need to create the column seq, which allows me identify the different times that a name appears in the data frame, it's important to preserve the order.

import pandas as pd

data = {'name': ['Tom', 'Joseph','Joseph','Joseph', 'Tom', 'Tom', 'John','Tom','Tom','John','Joseph']
        , 'seq': ['Tom 0', 'Joseph 0','Joseph 0','Joseph 0', 'Tom 1', 'Tom 1', 'John 0','Tom 2','Tom 2','John 1','Joseph 1']}

df = pd.DataFrame(data)

print(df)

      name       seq
0      Tom     Tom 0
1   Joseph  Joseph 0
2   Joseph  Joseph 0
3   Joseph  Joseph 0
4      Tom     Tom 1
5      Tom     Tom 1
6     John    John 0
7      Tom     Tom 2
8      Tom     Tom 2
9     John    John 1
10  Joseph  Joseph 1


问:
Azure AD - Insufficient privileges to perform requested operation by the application '00000003-0000-0000-c000-000000000000'
I work on a task that should invite users and add them in my azure active directory list. Before being able to access my app, the invited user should verify through email. This is the code I use:

```<code>IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(_config["AzureAd:ClientId"])
    .WithTenantId(_config["AzureAd:TenantId"])
    .WithClientSecret(_config["AzureAd:ClientSecret"])
    .Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var invitation = new Invitation
{
    InvitedUserEmailAddress = "mail@hotmail.com",
    InviteRedirectUrl = "https://url.com/",
    SendInvitationMessage = true

await graphClient.Invitations
    .Request()
    .AddAsync(invitation);
</code>```

I found this snippet somewhere on the internet and judging by the comments, it seems to work. However, when I run my app and call this functionality, I get an error that says

Code: Unauthorized Message: Insufficient privileges to perform requested operation by the application '00000003-0000-0000-c000-000000000000'. ControllerName=MSGraphInviteAPI, ActionName=CreateInvite, URL absolute path=/...

In API permissions, I have a User.Invite.All permission under Microsoft Graph. Besides this I have User.Read as well but I don't think it's relevant for this at the moment. Has some of you stumbled upon an error like this and managed to successfully solve it? If so, would you be kind to share the solution?

答:
You are using client_credentials flow. Which means it is not a User who is performing this task, but rather service credentials. You would need to provide Application permissions, rather than what you have set - Delegated Permissions.

If you don't see Application Permissions, its because you created an Azure AD B2C Application Registration. Rather, create the App Reg with the first option Accounts in this organizational directory only (Contoso only - Single tenant) .

These are the docs you need:

AAD Client Cred flow

MS Graph API daemon app

This is correct method for AAD and AAD B2C tenant today.

Body:
I work on a task that should invite users and add them in my azure active directory list. Before being able to access my app, the invited user should verify through email. This is the code I use:

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(_config["AzureAd:ClientId"])
    .WithTenantId(_config["AzureAd:TenantId"])
    .WithClientSecret(_config["AzureAd:ClientSecret"])
    .Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var invitation = new Invitation
{
    InvitedUserEmailAddress = "mail@hotmail.com",
    InviteRedirectUrl = "https://url.com/",
    SendInvitationMessage = true

await graphClient.Invitations
    .Request()
    .AddAsync(invitation);

I found this snippet somewhere on the internet and judging by the comments, it seems to work. However, when I run my app and call this functionality, I get an error that says

Code: Unauthorized Message: Insufficient privileges to perform requested operation by the application '00000003-0000-0000-c000-000000000000'. ControllerName=MSGraphInviteAPI, ActionName=CreateInvite, URL absolute path=/...

In API permissions, I have a User.Invite.All permission under Microsoft Graph. Besides this I have User.Read as well but I don't think it's relevant for this at the moment. Has some of you stumbled upon an error like this and managed to successfully solve it? If so, would you be kind to share the solution?


问:
How to Handle Variant in SCSS using BEM Methodology
I'm  trying to figure out this stupid yet annoying issue that I face up with  BEM. Currently for my application, I follow the BEM methodology for  creating UI Elements. For instance :

```<code><div class="card">
    <h2 class="card__title">Sample Title </h2>
    <h3 class="card__subtitle"> Sub Title </h3>
    <button class="card__action"> Action Button </button>
</div>
</code>```

The scss for this will be :

```<code>.card{
     &__title{color:red}
     &__subtitle{color:violet}
     &__subtitle{bakground:black}
}
</code>```

Now if I need to add a new variant of the card, I will be adding it as "card--modifier".

```<code>.card{
    &--variant{background-color:white}
    &__title{color:red}
    &__subtitle{color:violet}
    &__subtitle{bakground:black}
}
</code>```

Now, without breaking this nesting in scss, how can I modify the properties of child under the variant ?

答:
In situations like this I don't make a big fuss about repeating a classname or two.

If in case of card--variant you want for example the card__title to have a blue font color, you could just add the necessairy changes at the end of your rules (order is important, keep your specifity low and add special cases at the end)

```<code>.card {
   &__title { color: red; }
   &__subtitle { color: violet; }
   &__action { background-color: black; }

   &--variant {
       .card__title { color: blue; }
   }
}
</code>```

If for some reason you adamantly don't want to duplicate a name, you can capture the block-level name in a variable and use string interpolation:

```<code>.card {
   $block: &;
   &__title { color: red; }
   &__subtitle { color: violet; }
   &__action { background-color: black; }

   &--variant {
       .#{$block}__title { color: blue; }
   }
}
</code>```

Body:
I'm  trying to figure out this stupid yet annoying issue that I face up with  BEM. Currently for my application, I follow the BEM methodology for  creating UI Elements. For instance :

Sample Title

 Sub Title

    <button class="card__action"> Action Button </button>

The scss for this will be :

.card{
     &__title{color:red}
     &__subtitle{color:violet}
     &__subtitle{bakground:black}
}

Now if I need to add a new variant of the card, I will be adding it as "card--modifier".

.card{
    &--variant{background-color:white}
    &__title{color:red}
    &__subtitle{color:violet}
    &__subtitle{bakground:black}
}

Now, without breaking this nesting in scss, how can I modify the properties of child under the variant ?

Body:
In situations like this I don't make a big fuss about repeating a classname or two.

If in case of card--variant you want for example the card__title to have a blue font color, you could just add the necessairy changes at the end of your rules (order is important, keep your specifity low and add special cases at the end)

.card {
   &__title { color: red; }
   &__subtitle { color: violet; }
   &__action { background-color: black; }

   &--variant {
       .card__title { color: blue; }
   }
}

If for some reason you adamantly don't want to duplicate a name, you can capture the block-level name in a variable and use string interpolation:

.card {
   $block: &;
   &__title { color: red; }
   &__subtitle { color: violet; }
   &__action { background-color: black; }

   &--variant {
       .#{$block}__title { color: blue; }
   }
}


问:
R : y[x] & x[y] when x,y vectors
Silly question but for real i cant undestand what is happening here (Screenshot) ,especially in x[y]. In y[x] i undestand that he is getting the similar objects for x & y. But in x[y] he is getting objects that y is not having

答:
Data

```<code>x
[1]  2  4  6  8 10 12 14

y
[1] 1 2 3 4 5 6 7
</code>```

Explanation

The following returns the yth position of x, which is in this case, the first 7 elements of x (note that the first element of a vector in R has an index of 1 but not 0)

```<code>x[y]
[1]  2  4  6  8 10 12 14
</code>```

Similarly, this returns the xth position of y, which is the second, the 4th ... and the 14th element of y. However, since y only has 7 elements, it returns missing values (NA) after the seventh index.

```<code>y[x]
[1]  2  4  6 NA NA NA NA
</code>```

Title: R : y[x] & x[y] when x,y vectors

Body:
Data

x
[1]  2  4  6  8 10 12 14

y
[1] 1 2 3 4 5 6 7

Explanation

The following returns the yth position of x, which is in this case, the first 7 elements of x (note that the first element of a vector in R has an index of 1 but not 0)

x[y]
[1]  2  4  6  8 10 12 14

Similarly, this returns the xth position of y, which is the second, the 4th ... and the 14th element of y. However, since y only has 7 elements, it returns missing values (NA) after the seventh index.

y[x]
[1]  2  4  6 NA NA NA NA


问:
GA4 (Google Analytics) sessions based on UTM params
I am trying to fetch sessions from GA4 which are relevant to specific UTM params.

In GA3 we were able to use segments (sessions::condition::ga:source==X;ga:medium==Y) but I can not find a way to do this on GA4.

```<code>POST https://analyticsdata.googleapis.com/v1beta/#{property}:runReport`
</code>```

Payload like this:

```<code>body = {
  "metrics": [
    {
      "name": "sessions::condition::ga:source==X;ga:medium==Y"
    }
  ],
  "dimensions": [
    {
      "name": "date"
    }
  ],
  "dateRanges": [
    {
      "startDate": '2022-01-01',
      "endDate": '2022-01-30',
      "name": "current_year"
    }
  ]
}
</code>```

Returns: Field sessions::condition::ga:source==X;ga:medium==Y is not a valid metric.. Is there a way to do this via new API?

Should I use dimension filter to achieve that? I need to query on both source&medium but it is not clear how do I do this?

```<code>  "dimensionFilter": {
      "filter": {
        "fieldName": "firstUserMedium",
        "stringFilter": {
          "value": "Y"
        }
      }
    }
</code>```

答:
A dimension filter on sessionSource & sessionMedium returns sessions that have those specific utm_source & utm_medium values. See the dimensions & metrics page for a description of these and other dimensions & metrics.

The needed dimension filter is similar to the following. See Dimension Filters in Creating a Report for more info.

```<code>"dimensionFilter": {
  "andGroup": {
    "expressions": [
      {
        "filter": {
          "fieldName": "sessionSource",
          "stringFilter": {
            "value": "X"
          }
        }
      },
      {
        "filter": {
          "fieldName": "sessionMedium",
          "stringFilter": {
            "value": "Y"
          }
        }
      }
    ]
  }
},
</code>```

Segments are not yet available today in the GA4 Data API.

Body:
I am trying to fetch sessions from GA4 which are relevant to specific UTM params.

In GA3 we were able to use segments (sessions::condition::ga:source==X;ga:medium==Y) but I can not find a way to do this on GA4.

POST https://analyticsdata.googleapis.com/v1beta/#{property}:runReport`

Payload like this:

body = {
  "metrics": [
    {
      "name": "sessions::condition::ga:source==X;ga:medium==Y"
    }
  ],
  "dimensions": [
    {
      "name": "date"
    }
  ],
  "dateRanges": [
    {
      "startDate": '2022-01-01',
      "endDate": '2022-01-30',
      "name": "current_year"
    }
  ]
}

Returns: Field sessions::condition::ga:source==X;ga:medium==Y is not a valid metric.. Is there a way to do this via new API?

Should I use dimension filter to achieve that? I need to query on both source&medium but it is not clear how do I do this?

  "dimensionFilter": {
      "filter": {
        "fieldName": "firstUserMedium",
        "stringFilter": {
          "value": "Y"
        }
      }
    }

Body:
A dimension filter on sessionSource & sessionMedium returns sessions that have those specific utm_source & utm_medium values. See the dimensions & metrics page for a description of these and other dimensions & metrics.

The needed dimension filter is similar to the following. See Dimension Filters in Creating a Report for more info.

"dimensionFilter": {
  "andGroup": {
    "expressions": [
      {
        "filter": {
          "fieldName": "sessionSource",
          "stringFilter": {
            "value": "X"
          }
        }
      },
      {
        "filter": {
          "fieldName": "sessionMedium",
          "stringFilter": {
            "value": "Y"
          }
        }
      }
    ]
  }
},

Segments are not yet available today in the GA4 Data API.


问:
Very basic JSON question
I have this JSON data:

```<code>var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];
</code>```

How can I loop through all the objects inside people and output their names along with their ages like so:

```<code>John 25
Jame 49
followed by the rest...
</code>```

答:
Use a for loop: http://www.w3schools.com/js/js_loop_for.asp

```<code>for (var i = 0; i < people.length; i++)
{
     document.write(people[i].name + ' ' + people[i].age + '<br />');
}
</code>```

or the each function in jQuery: http://api.jquery.com/jQuery.each/

```<code>$.each(people, function(i, o) {
   document.write(o.name + ' ' + o.age + '<br />');
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Very basic JSON question

Body:
I have this JSON data:

var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];

How can I loop through all the objects inside people and output their names along with their ages like so:

John 25
Jame 49
followed by the rest...

Body:
Use a for loop: http://www.w3schools.com/js/js_loop_for.asp

for (var i = 0; i < people.length; i++)
{
     document.write(people[i].name + ' ' + people[i].age + '<br />');
}

or the each function in jQuery: http://api.jquery.com/jQuery.each/

$.each(people, function(i, o) {
   document.write(o.name + ' ' + o.age + '<br />');
});


问:
onTouch, onLongClick together in Android
I'm adding ImageViews to parent layout dynamically and performing zoom in/out operations with onTouch on the added image.

I want to remove the added view with an onLongPress of it.

```<code>img.setOnLongClickListener(longClickAction);
img.setOnTouchListener(touchAction);

</code>```

onLongPress:

```<code>OnLongClickListener longClickAction = new OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        parentLayout.removeView((ImageView)v);
        return false;
    }
};
</code>```

onTouch:

```<code>OnTouchListener touchAction = new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        ImageView i = (ImageView)v;

        // Perform zoom operation onTouch of ImageView
        zoom(i, event);
        return true;
    }
};
</code>```

Why do only the onTouch events work?

How can I get them both to work?

What should I do to remove the added view?

答:
you cant achive this togither by setOnLongClickListener and setOnTouchListener
because when you return true inside onTouch method it assume that you handle all touch events  you can achieve long click by post delay and call method after time out but you need to check if is still pressing or action up fired
may be this code snapshot help you</p>
```<code> mBinding.iv2.setOnTouchListener(object : View.OnTouchListener {

        var stillPress = false
        override fun onTouch(view: View?, motionEvent: MotionEvent?): Boolean {
            if(motionEvent?.action == MotionEvent.ACTION_DOWN){
                 stillPress = true
                Handler(Looper.getMainLooper()).postDelayed({
                    if(stillPress)
                        zoomImageFromThumb(view!!,R.drawable.ic_baseline_adb_24)
                },1000)
            }

            if(motionEvent?.action == MotionEvent.ACTION_UP){
                stillPress = false
                mBinding.expandedImage.performClick()
            }
            return true

        }
    })
</code>```

Body:
I'm adding ImageViews to parent layout dynamically and performing zoom in/out operations with onTouch on the added image.

I want to remove the added view with an onLongPress of it.

img.setOnLongClickListener(longClickAction);
img.setOnTouchListener(touchAction);

onLongPress:

OnLongClickListener longClickAction = new OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        parentLayout.removeView((ImageView)v);
        return false;
    }
};

onTouch:

OnTouchListener touchAction = new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        ImageView i = (ImageView)v;

        // Perform zoom operation onTouch of ImageView
        zoom(i, event);
        return true;
    }
};

Why do only the onTouch events work?

How can I get them both to work?

What should I do to remove the added view?

Body:
you cant achive this togither by setOnLongClickListener and setOnTouchListener
because when you return true inside onTouch method it assume that you handle all touch events  you can achieve long click by post delay and call method after time out but you need to check if is still pressing or action up fired
may be this code snapshot help you

 mBinding.iv2.setOnTouchListener(object : View.OnTouchListener {

        var stillPress = false
        override fun onTouch(view: View?, motionEvent: MotionEvent?): Boolean {
            if(motionEvent?.action == MotionEvent.ACTION_DOWN){
                 stillPress = true
                Handler(Looper.getMainLooper()).postDelayed({
                    if(stillPress)
                        zoomImageFromThumb(view!!,R.drawable.ic_baseline_adb_24)
                },1000)
            }

            if(motionEvent?.action == MotionEvent.ACTION_UP){
                stillPress = false
                mBinding.expandedImage.performClick()
            }
            return true

        }
    })


问:
FTPS data connection with TLS/SSL via proxy fails with log entry "Replacing PASV mode reply address <PROXY_IP> with <FTPS_IP>"
I have an issue while connecting to a FTPS server with TLS/SSL Implicit encryption via PROXY.

I am following the custom Apache FTPS Client (commons-net-3.8.0) solution provided from Java FTPS client through HTTP proxy

My server connection is working, but unable to list or file transfer, getting below error:

425 Can't open data connection for transfer of "<REMOVED_FOR_SECURITY>"

Data connection / File transfer is working fine from Windows WinSCP and Linux LFTP.

WinSCP Log:

2022-02-06 16:25:04.874 --------------------------------------------------------------------------
2022-02-06 16:25:04.876 WinSCP Version 5.15.5 (Build 9925) (OS 10.0.19042 - Windows 10 Enterprise)
2022-02-06 16:25:04.877 Configuration: C:\Users\<LOGIN_SER>\AppData\Roaming\WinSCP.ini
2022-02-06 16:25:04.879 Log level: Normal
2022-02-06 16:25:04.879 Local account: HBEU\<LOGIN_SER>
2022-02-06 16:25:04.879 Working directory: C:\Program Files\WinSCP-5.15.5
2022-02-06 16:25:04.879 Process ID: 16452
2022-02-06 16:25:04.883 Command-line: C:\Program Files\WinSCP-5.15.5\WinSCP.exe
2022-02-06 16:25:04.885 Time zone: Current: GMT+3 (Arab Standard Time), No DST
2022-02-06 16:25:04.885 Login time: Sunday, February 6, 2022 4:25:04 PM
2022-02-06 16:25:04.885 --------------------------------------------------------------------------
2022-02-06 16:25:04.885 Session name: FTPS TEST (Site)
2022-02-06 16:25:04.885 Host name: <FTPS_HOST_NAME> (Port: <FTPS_PORT>)
2022-02-06 16:25:04.885 User name: <FTPS_USER_NAME> (Password: No, Key file: No, Passphrase: No)
2022-02-06 16:25:04.885 Transfer Protocol: FTP
2022-02-06 16:25:04.885 Ping type: Dummy, Ping interval: 30 sec; Timeout: 15 sec
2022-02-06 16:25:04.885 Disable Nagle: No
2022-02-06 16:25:04.885 Proxy: HTTP
2022-02-06 16:25:04.885 HostName: <PROXY_HOST_NAME> (Port: <PROXY_PORT>); Username: ; Passwd: No
2022-02-06 16:25:04.885 Send buffer: 262144
2022-02-06 16:25:04.885 UTF: Auto
2022-02-06 16:25:04.885 FTPS: Implicit TLS/SSL [Client certificate: No]
2022-02-06 16:25:04.885 FTP: Passive: Yes [Force IP: Auto]; MLSD: Auto [List all: Auto]; HOST: Auto
2022-02-06 16:25:04.885 Session reuse: Yes
2022-02-06 16:25:04.885 TLS/SSL versions: TLSv1.0-TLSv1.2
2022-02-06 16:25:04.885 Local directory: <LOCAL_DIRECTORY>, Remote directory: <REMOTE_DIRECTORY>, Update: Yes, Cache: Yes
2022-02-06 16:25:04.885 Cache directory changes: Yes, Permanent: Yes
2022-02-06 16:25:04.885 Recycle bin: Delete to: No, Overwritten to: No, Bin path:
2022-02-06 16:25:04.885 Timezone offset: 0h 0m
2022-02-06 16:25:04.885 --------------------------------------------------------------------------
2022-02-06 16:25:04.953 Connecting to <FTPS_HOST_NAME>:<FTPS_PORT> ...
2022-02-06 16:25:04.953 HTTP proxy command: CONNECT <FTPS_HOST_NAME>:<FTPS_PORT HTTP/1.1
2022-02-06 16:25:04.953 Host: <FTPS_HOST_NAME>:<FTPS_PORT>
2022-02-06 16:25:04.989 Connection with proxy established, performing handshake...
2022-02-06 16:25:04.989 HTTP proxy response: HTTP/1.1 200 Connection established
2022-02-06 16:25:04.989 HTTP proxy headers:
2022-02-06 16:25:04.989 Connected with <FTPS_HOST_NAME>:<FTPS_PORT>, negotiating TLS connection...
2022-02-06 16:25:05.038 Verifying certificate for "" with fingerprint <REMOVED_FOR_SECURITY> and 20 failures
2022-02-06 16:25:05.038 Certificate common name "*.<FTPS_DOMAIN_NAME>" matches hostname
2022-02-06 16:25:05.138 Certificate verified against Windows certificate store
2022-02-06 16:25:05.138 Using TLSv1.2, cipher TLSv1/SSLv3: ECDHE-RSA-AES256-GCM-SHA384, 2048 bit RSA, ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  Enc=AESGCM(256) Mac=AEAD
2022-02-06 16:25:05.191 TLS connection established. Waiting for welcome message...
2022-02-06 16:25:05.191 220 SIJIL FTP
2022-02-06 16:25:05.191 USER <FTPS_USER_NAME>
2022-02-06 16:25:05.191 331 Password required for <FTPS_USER_NAME>
2022-02-06 16:25:06.977 PASS *************
2022-02-06 16:25:07.013 230 Logged on
2022-02-06 16:25:07.013 SYST
2022-02-06 16:25:07.049 215 UNIX emulated by FileZilla
2022-02-06 16:25:07.049 FEAT
2022-02-06 16:25:07.085 211-Features:
2022-02-06 16:25:07.085  MDTM
2022-02-06 16:25:07.086  REST STREAM
2022-02-06 16:25:07.086  SIZE
2022-02-06 16:25:07.086  MLST type*;size*;modify*;
2022-02-06 16:25:07.086  MLSD
2022-02-06 16:25:07.086  AUTH SSL
2022-02-06 16:25:07.086  AUTH TLS
2022-02-06 16:25:07.086  PROT
2022-02-06 16:25:07.088  PBSZ
2022-02-06 16:25:07.088  UTF8
2022-02-06 16:25:07.088  CLNT
2022-02-06 16:25:07.088  MFMT
2022-02-06 16:25:07.088  EPSV
2022-02-06 16:25:07.088  EPRT
2022-02-06 16:25:07.088 211 End
2022-02-06 16:25:07.088 CLNT WinSCP-release-5.15.5
2022-02-06 16:25:07.122 200 Don't care
2022-02-06 16:25:07.123 OPTS UTF8 ON
2022-02-06 16:25:07.159 202 UTF8 mode is always enabled. No need to send this command.
2022-02-06 16:25:07.160 PBSZ 0
2022-02-06 16:25:07.198 200 PBSZ=0
2022-02-06 16:25:07.199 PROT P
2022-02-06 16:25:07.235 200 Protection level set to P
2022-02-06 16:25:07.248 Connected
2022-02-06 16:25:07.248 --------------------------------------------------------------------------
2022-02-06 16:25:07.248 Using FTP protocol.
2022-02-06 16:25:07.250 Doing startup conversation with host.
2022-02-06 16:25:07.264 PWD
2022-02-06 16:25:07.303 257 "/" is current directory.
2022-02-06 16:25:07.303 Changing directory to "<REMOTE_DIRECTORY>".
2022-02-06 16:25:07.303 CWD <REMOTE_DIRECTORY>
2022-02-06 16:25:07.340 250 CWD successful. "<REMOTE_DIRECTORY>" is current directory.
2022-02-06 16:25:07.340 Getting current directory name.
2022-02-06 16:25:07.341 PWD
2022-02-06 16:25:07.384 257 "<REMOTE_DIRECTORY>" is current directory.
2022-02-06 16:25:07.458 Retrieving directory listing...
2022-02-06 16:25:07.458 TYPE A
2022-02-06 16:25:07.493 200 Type set to A
2022-02-06 16:25:07.493 PASV
2022-02-06 16:25:07.530 227 Entering Passive Mode (<REMOVED_FOR_SECURITY>)
2022-02-06 16:25:07.530 Error retrieving server address, cannot test if address is routable
2022-02-06 16:25:07.530 MLSD
2022-02-06 16:25:07.530 Connecting to <PROXY_IP>:<PROXY_DYNAMIC_PORT> ...
2022-02-06 16:25:07.534 HTTP proxy command: CONNECT <PROXY_IP>:<PROXY_DYNAMIC_PORT> HTTP/1.1
2022-02-06 16:25:07.534 Host: <PROXY_IP>:<PROXY_DYNAMIC_PORT>
2022-02-06 16:25:07.534 Connection with proxy established, performing handshake...
2022-02-06 16:25:07.586 HTTP proxy response: HTTP/1.1 200 Connection established
2022-02-06 16:25:07.587 HTTP proxy headers:
2022-02-06 16:25:07.608 Session ID reused
2022-02-06 16:25:07.610 Using TLSv1.2, cipher TLSv1/SSLv3: ECDHE-RSA-AES256-GCM-SHA384, 2048 bit RSA, ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  Enc=AESGCM(256) Mac=AEAD
2022-02-06 16:25:07.610 TLS connection established
2022-02-06 16:25:07.619 150 Opening data channel for directory listing of "<REMOTE_DIRECTORY>"
2022-02-06 16:25:07.620 226 Successfully transferred "<REMOTE_DIRECTORY>"
2022-02-06 16:25:07.630 Data connection closed
2022-02-06 16:25:07.631 type=file;modify=20220203072851;size=21; test.txt
2022-02-06 16:25:07.631 type=file;modify=20220203072851;size=21; test_1.txt
2022-02-06 16:25:07.631 Directory listing successful
2022-02-06 16:25:07.632 ..;D;0;1899-12-30T03:00:00.000Z;0;"" [0];"" [0];---------;0
2022-02-06 16:25:07.632 test.txt;-;21;2022-02-03T07:28:51.000Z;3;"" [0];"" [0];---------;0
2022-02-06 16:25:07.632 test_1.txt;-;21;2022-02-03T07:28:51.000Z;3;"" [0];"" [0];---------;0
2022-02-06 16:25:07.659 Startup conversation with host finished.
```
<p>Apache Log:</p>
<pre class="lang-none prettyprint-override"><code>220 SIJIL FTP
USER *******
331 Password required for <FTPS_USER_NAME>
PASS *******
230 Logged on
PBSZ 0
200 PBSZ=0
PROT P
200 Protection level set to P
PWD
257 "/" is current directory.
/
CWD <REMOTE_DIRECTORY>
250 CWD successful. "<REMOTE_DIRECTORY>" is current directory.
PWD
257 "<REMOTE_DIRECTORY>" is current directory.
<REMOTE_DIRECTORY>
PASV
227 Entering Passive Mode (<REMOVED_FOR_SECURITY>)
[Replacing PASV mode reply address <PROXY_IP> with <FTPS_IP>]
MLSD
425 Can't open data connection for transfer of "<REMOTE_DIRECTORY>"
List size: 0
QUIT
221 Goodbye
</code>```

答:
I do not know your network/proxy setup, so I cannot really explain the behaviour of FTPClient. Your server seems to return IP address of the proxy in the PASV response. The default NAT resolver of FTPClient decides that the address is wrong (is it a local network host address?) and choses to use original FTP server's address instead.

While WinSCP does not do that and connects to the IP that the server returned.

To avoid the NAT resolver from messing with the address, use FTPClient.setPassiveNatWorkaround (though that's deprecated):

```<code>ftpClient.setPassiveNatWorkaround(false);
</code>```

or equivalent FTPClient.setPassiveNatWorkaroundStrategy:

```<code>ftpClient.setPassiveNatWorkaroundStrategy(null);
</code>```

Body:
I have an issue while connecting to a FTPS server with TLS/SSL Implicit encryption via PROXY.

I am following the custom Apache FTPS Client (commons-net-3.8.0) solution provided from Java FTPS client through HTTP proxy

My server connection is working, but unable to list or file transfer, getting below error:

425 Can't open data connection for transfer of "<REMOVED_FOR_SECURITY>"

Data connection / File transfer is working fine from Windows WinSCP and Linux LFTP.

WinSCP Log:

2022-02-06 16:25:04.874 --------------------------------------------------------------------------
2022-02-06 16:25:04.876 WinSCP Version 5.15.5 (Build 9925) (OS 10.0.19042 - Windows 10 Enterprise)
2022-02-06 16:25:04.877 Configuration: C:\Users\<LOGIN_SER>\AppData\Roaming\WinSCP.ini
2022-02-06 16:25:04.879 Log level: Normal
2022-02-06 16:25:04.879 Local account: HBEU\<LOGIN_SER>
2022-02-06 16:25:04.879 Working directory: C:\Program Files\WinSCP-5.15.5
2022-02-06 16:25:04.879 Process ID: 16452
2022-02-06 16:25:04.883 Command-line: C:\Program Files\WinSCP-5.15.5\WinSCP.exe
2022-02-06 16:25:04.885 Time zone: Current: GMT+3 (Arab Standard Time), No DST
2022-02-06 16:25:04.885 Login time: Sunday, February 6, 2022 4:25:04 PM
2022-02-06 16:25:04.885 --------------------------------------------------------------------------
2022-02-06 16:25:04.885 Session name: FTPS TEST (Site)
2022-02-06 16:25:04.885 Host name: <FTPS_HOST_NAME> (Port: <FTPS_PORT>)
2022-02-06 16:25:04.885 User name: <FTPS_USER_NAME> (Password: No, Key file: No, Passphrase: No)
2022-02-06 16:25:04.885 Transfer Protocol: FTP
2022-02-06 16:25:04.885 Ping type: Dummy, Ping interval: 30 sec; Timeout: 15 sec
2022-02-06 16:25:04.885 Disable Nagle: No
2022-02-06 16:25:04.885 Proxy: HTTP
2022-02-06 16:25:04.885 HostName: <PROXY_HOST_NAME> (Port: <PROXY_PORT>); Username: ; Passwd: No
2022-02-06 16:25:04.885 Send buffer: 262144
2022-02-06 16:25:04.885 UTF: Auto
2022-02-06 16:25:04.885 FTPS: Implicit TLS/SSL [Client certificate: No]
2022-02-06 16:25:04.885 FTP: Passive: Yes [Force IP: Auto]; MLSD: Auto [List all: Auto]; HOST: Auto
2022-02-06 16:25:04.885 Session reuse: Yes
2022-02-06 16:25:04.885 TLS/SSL versions: TLSv1.0-TLSv1.2
2022-02-06 16:25:04.885 Local directory: <LOCAL_DIRECTORY>, Remote directory: <REMOTE_DIRECTORY>, Update: Yes, Cache: Yes
2022-02-06 16:25:04.885 Cache directory changes: Yes, Permanent: Yes
2022-02-06 16:25:04.885 Recycle bin: Delete to: No, Overwritten to: No, Bin path:
2022-02-06 16:25:04.885 Timezone offset: 0h 0m
2022-02-06 16:25:04.885 --------------------------------------------------------------------------
2022-02-06 16:25:04.953 Connecting to <FTPS_HOST_NAME>:<FTPS_PORT> ...
2022-02-06 16:25:04.953 HTTP proxy command: CONNECT <FTPS_HOST_NAME>:<FTPS_PORT HTTP/1.1
2022-02-06 16:25:04.953 Host: <FTPS_HOST_NAME>:<FTPS_PORT>
2022-02-06 16:25:04.989 Connection with proxy established, performing handshake...
2022-02-06 16:25:04.989 HTTP proxy response: HTTP/1.1 200 Connection established
2022-02-06 16:25:04.989 HTTP proxy headers:
2022-02-06 16:25:04.989 Connected with <FTPS_HOST_NAME>:<FTPS_PORT>, negotiating TLS connection...
2022-02-06 16:25:05.038 Verifying certificate for "" with fingerprint <REMOVED_FOR_SECURITY> and 20 failures
2022-02-06 16:25:05.038 Certificate common name "*.<FTPS_DOMAIN_NAME>" matches hostname
2022-02-06 16:25:05.138 Certificate verified against Windows certificate store
2022-02-06 16:25:05.138 Using TLSv1.2, cipher TLSv1/SSLv3: ECDHE-RSA-AES256-GCM-SHA384, 2048 bit RSA, ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  Enc=AESGCM(256) Mac=AEAD
2022-02-06 16:25:05.191 TLS connection established. Waiting for welcome message...
2022-02-06 16:25:05.191 220 SIJIL FTP
2022-02-06 16:25:05.191 USER <FTPS_USER_NAME>
2022-02-06 16:25:05.191 331 Password required for <FTPS_USER_NAME>
2022-02-06 16:25:06.977 PASS *************
2022-02-06 16:25:07.013 230 Logged on
2022-02-06 16:25:07.013 SYST
2022-02-06 16:25:07.049 215 UNIX emulated by FileZilla
2022-02-06 16:25:07.049 FEAT
2022-02-06 16:25:07.085 211-Features:
2022-02-06 16:25:07.085  MDTM
2022-02-06 16:25:07.086  REST STREAM
2022-02-06 16:25:07.086  SIZE
2022-02-06 16:25:07.086  MLST type*;size*;modify*;
2022-02-06 16:25:07.086  MLSD
2022-02-06 16:25:07.086  AUTH SSL
2022-02-06 16:25:07.086  AUTH TLS
2022-02-06 16:25:07.086  PROT
2022-02-06 16:25:07.088  PBSZ
2022-02-06 16:25:07.088  UTF8
2022-02-06 16:25:07.088  CLNT
2022-02-06 16:25:07.088  MFMT
2022-02-06 16:25:07.088  EPSV
2022-02-06 16:25:07.088  EPRT
2022-02-06 16:25:07.088 211 End
2022-02-06 16:25:07.088 CLNT WinSCP-release-5.15.5
2022-02-06 16:25:07.122 200 Don't care
2022-02-06 16:25:07.123 OPTS UTF8 ON
2022-02-06 16:25:07.159 202 UTF8 mode is always enabled. No need to send this command.
2022-02-06 16:25:07.160 PBSZ 0
2022-02-06 16:25:07.198 200 PBSZ=0
2022-02-06 16:25:07.199 PROT P
2022-02-06 16:25:07.235 200 Protection level set to P
2022-02-06 16:25:07.248 Connected
2022-02-06 16:25:07.248 --------------------------------------------------------------------------
2022-02-06 16:25:07.248 Using FTP protocol.
2022-02-06 16:25:07.250 Doing startup conversation with host.
2022-02-06 16:25:07.264 PWD
2022-02-06 16:25:07.303 257 "/" is current directory.
2022-02-06 16:25:07.303 Changing directory to "<REMOTE_DIRECTORY>".
2022-02-06 16:25:07.303 CWD <REMOTE_DIRECTORY>
2022-02-06 16:25:07.340 250 CWD successful. "<REMOTE_DIRECTORY>" is current directory.
2022-02-06 16:25:07.340 Getting current directory name.
2022-02-06 16:25:07.341 PWD
2022-02-06 16:25:07.384 257 "<REMOTE_DIRECTORY>" is current directory.
2022-02-06 16:25:07.458 Retrieving directory listing...
2022-02-06 16:25:07.458 TYPE A
2022-02-06 16:25:07.493 200 Type set to A
2022-02-06 16:25:07.493 PASV
2022-02-06 16:25:07.530 227 Entering Passive Mode (<REMOVED_FOR_SECURITY>)
2022-02-06 16:25:07.530 Error retrieving server address, cannot test if address is routable
2022-02-06 16:25:07.530 MLSD
2022-02-06 16:25:07.530 Connecting to <PROXY_IP>:<PROXY_DYNAMIC_PORT> ...
2022-02-06 16:25:07.534 HTTP proxy command: CONNECT <PROXY_IP>:<PROXY_DYNAMIC_PORT> HTTP/1.1
2022-02-06 16:25:07.534 Host: <PROXY_IP>:<PROXY_DYNAMIC_PORT>
2022-02-06 16:25:07.534 Connection with proxy established, performing handshake...
2022-02-06 16:25:07.586 HTTP proxy response: HTTP/1.1 200 Connection established
2022-02-06 16:25:07.587 HTTP proxy headers:
2022-02-06 16:25:07.608 Session ID reused
2022-02-06 16:25:07.610 Using TLSv1.2, cipher TLSv1/SSLv3: ECDHE-RSA-AES256-GCM-SHA384, 2048 bit RSA, ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  Enc=AESGCM(256) Mac=AEAD
2022-02-06 16:25:07.610 TLS connection established
2022-02-06 16:25:07.619 150 Opening data channel for directory listing of "<REMOTE_DIRECTORY>"
2022-02-06 16:25:07.620 226 Successfully transferred "<REMOTE_DIRECTORY>"
2022-02-06 16:25:07.630 Data connection closed
2022-02-06 16:25:07.631 type=file;modify=20220203072851;size=21; test.txt
2022-02-06 16:25:07.631 type=file;modify=20220203072851;size=21; test_1.txt
2022-02-06 16:25:07.631 Directory listing successful
2022-02-06 16:25:07.632 ..;D;0;1899-12-30T03:00:00.000Z;0;"" [0];"" [0];---------;0
2022-02-06 16:25:07.632 test.txt;-;21;2022-02-03T07:28:51.000Z;3;"" [0];"" [0];---------;0
2022-02-06 16:25:07.632 test_1.txt;-;21;2022-02-03T07:28:51.000Z;3;"" [0];"" [0];---------;0
2022-02-06 16:25:07.659 Startup conversation with host finished.

Apache Log:

220 SIJIL FTP
USER *******
331 Password required for <FTPS_USER_NAME>
PASS *******
230 Logged on
PBSZ 0
200 PBSZ=0
PROT P
200 Protection level set to P
PWD
257 "/" is current directory.
/
CWD <REMOTE_DIRECTORY>
250 CWD successful. "<REMOTE_DIRECTORY>" is current directory.
PWD
257 "<REMOTE_DIRECTORY>" is current directory.
<REMOTE_DIRECTORY>
PASV
227 Entering Passive Mode (<REMOVED_FOR_SECURITY>)
[Replacing PASV mode reply address <PROXY_IP> with <FTPS_IP>]
MLSD
425 Can't open data connection for transfer of "<REMOTE_DIRECTORY>"
List size: 0
QUIT
221 Goodbye

Body:
I do not know your network/proxy setup, so I cannot really explain the behaviour of FTPClient. Your server seems to return IP address of the proxy in the PASV response. The default NAT resolver of FTPClient decides that the address is wrong (is it a local network host address?) and choses to use original FTP server's address instead.

While WinSCP does not do that and connects to the IP that the server returned.

To avoid the NAT resolver from messing with the address, use FTPClient.setPassiveNatWorkaround (though that's deprecated):

ftpClient.setPassiveNatWorkaround(false);

or equivalent FTPClient.setPassiveNatWorkaroundStrategy:

ftpClient.setPassiveNatWorkaroundStrategy(null);


问:
Firestore write not succeeding or failing
I am attempting to write the contents of a custom object to FireBase Firestore. When the method to write to the database is called, neither my OnSuccessListener nor my OnFailureListener seems to be triggering and the data is not writing to the store.

I am getting the following exception in my debug log:

```<code>2022-02-04 17:14:45.363 22150-22227/com.skillstorm.helloworld W/Firestore: (24.0.1) [WriteStream]: (915220b) Stream closed with status: Status{code=UNAVAILABLE, description=null, cause=java.net.SocketException: socket failed: EPERM (Operation not permitted)
    at java.net.Socket.createImpl(Socket.java:492)
    at java.net.Socket.<init>(Socket.java:446)
    at java.net.Socket.<init>(Socket.java:250)
    at javax.net.DefaultSocketFactory.createSocket(SocketFactory.java:285)
    at io.grpc.okhttp.OkHttpClientTransport$4.run(OkHttpClientTransport.java:558)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:919)
</code>```

Here is the code for my custom object:

```<code>public class Task implements Serializable {
// Class properties
private String title;
private Date dateCreated;
private boolean completed;
private Date dueDate;
private String description;

// Constructors
public Task (String title, Date dateCreated, boolean completed, Date dueDate) {
    this.title = title;
    this.dateCreated = dateCreated;
    this.completed = completed;
    this.dueDate = dueDate;

    this.description = generateDescription(title, dueDate, completed);
}

public  Task() {}

// Getters / Setters
public String getTitle() {
    return  this.title;
}

public void setTitle(String title) {
    this.title = title;
    this.description = generateDescription(this.title, this.dueDate, this.completed);
}

public Date getDateCreated() {
    return this.dateCreated;
}

public void setDateCreated(Date dateCreated) {
    this.dateCreated = dateCreated;
}

public boolean getCompleted() {
    return this.completed;
}

public void setCompleted(boolean completed) {
    this.completed = completed;
    this.description = generateDescription(this.title, this.dueDate, this.completed);
}

public Date getDueDate() {
    return this.dueDate;
}

public void setDueDate(Date dueDate) {
    this.dueDate = dueDate;
    this.description = generateDescription(this.title, this.dueDate, this.completed);
}

public String getDescription() {
    return this.description;
}

public void setDescription(String description) {
    this.description = generateDescription(this.title, this.dueDate, this.completed);
}

// Custom methods
private String generateDescription (String taskTitle, Date taskDueDate, boolean isCompleted) {
    String generatedDescription = "'" + taskTitle + "'";

    if (taskDueDate != null) {
        generatedDescription = generatedDescription + " due on " + taskDueDate.toString();
    }

    if (isCompleted) {
        generatedDescription = generatedDescription + " has been completed!";
    }

    else {
        generatedDescription = generatedDescription + " has not yet been completed.";
    }

    return generatedDescription;
}}
</code>```

Here is the method attempting to write to the database:

```<code>private void updateTaskList(Task task) {
    CollectionReference databaseTasks = database.collection("Tasks");

    databaseTasks.add(task).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
        @Override
        public void onSuccess(DocumentReference documentReference) {
            Toast.makeText(MainActivity.this, "Your task has been added to the database!", Toast.LENGTH_LONG).show();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(MainActivity.this, "Your task could not be added to the database...", Toast.LENGTH_LONG).show();
        }
    });
}
</code>```

And here is the onActivityResult() method in my Main Activity that is calling the method to write to the database:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 0) {
        if (resultCode == Activity.RESULT_OK) {
            Task newTask = (Task) data.getSerializableExtra("New Task");

            taskList.add(newTask);

            populateTaskList();

            updateTaskList(newTask);
        }
    }
}
</code>```

Finally, here is the rule from my Firestore instance:

```<code>rules_version = '2';
service cloud.firestore {
 match /databases/{database}/documents {
match /{document=**} {
  allow read, write: if false;
}}}
</code>```

答:
Solved. Here are the steps I had to take to resolve:

Uninstall app from the test device.

Change Firestore rules to:

rules_version= '2';
service cloud.firestore{
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}

(Note: This is not good practice and is only a quick solution for development purposes)

Run the app again and write to Firestore seems to work now

Body:
I am attempting to write the contents of a custom object to FireBase Firestore. When the method to write to the database is called, neither my OnSuccessListener nor my OnFailureListener seems to be triggering and the data is not writing to the store.

I am getting the following exception in my debug log:

2022-02-04 17:14:45.363 22150-22227/com.skillstorm.helloworld W/Firestore: (24.0.1) [WriteStream]: (915220b) Stream closed with status: Status{code=UNAVAILABLE, description=null, cause=java.net.SocketException: socket failed: EPERM (Operation not permitted)
    at java.net.Socket.createImpl(Socket.java:492)
    at java.net.Socket.<init>(Socket.java:446)
    at java.net.Socket.<init>(Socket.java:250)
    at javax.net.DefaultSocketFactory.createSocket(SocketFactory.java:285)
    at io.grpc.okhttp.OkHttpClientTransport$4.run(OkHttpClientTransport.java:558)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:919)

Here is the code for my custom object:

public class Task implements Serializable {
// Class properties
private String title;
private Date dateCreated;
private boolean completed;
private Date dueDate;
private String description;

// Constructors
public Task (String title, Date dateCreated, boolean completed, Date dueDate) {
    this.title = title;
    this.dateCreated = dateCreated;
    this.completed = completed;
    this.dueDate = dueDate;

    this.description = generateDescription(title, dueDate, completed);
}

public  Task() {}

// Getters / Setters
public String getTitle() {
    return  this.title;
}

public void setTitle(String title) {
    this.title = title;
    this.description = generateDescription(this.title, this.dueDate, this.completed);
}

public Date getDateCreated() {
    return this.dateCreated;
}

public void setDateCreated(Date dateCreated) {
    this.dateCreated = dateCreated;
}

public boolean getCompleted() {
    return this.completed;
}

public void setCompleted(boolean completed) {
    this.completed = completed;
    this.description = generateDescription(this.title, this.dueDate, this.completed);
}

public Date getDueDate() {
    return this.dueDate;
}

public void setDueDate(Date dueDate) {
    this.dueDate = dueDate;
    this.description = generateDescription(this.title, this.dueDate, this.completed);
}

public String getDescription() {
    return this.description;
}

public void setDescription(String description) {
    this.description = generateDescription(this.title, this.dueDate, this.completed);
}

// Custom methods
private String generateDescription (String taskTitle, Date taskDueDate, boolean isCompleted) {
    String generatedDescription = "'" + taskTitle + "'";

    if (taskDueDate != null) {
        generatedDescription = generatedDescription + " due on " + taskDueDate.toString();
    }

    if (isCompleted) {
        generatedDescription = generatedDescription + " has been completed!";
    }

    else {
        generatedDescription = generatedDescription + " has not yet been completed.";
    }

    return generatedDescription;
}}

Here is the method attempting to write to the database:

private void updateTaskList(Task task) {
    CollectionReference databaseTasks = database.collection("Tasks");

    databaseTasks.add(task).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
        @Override
        public void onSuccess(DocumentReference documentReference) {
            Toast.makeText(MainActivity.this, "Your task has been added to the database!", Toast.LENGTH_LONG).show();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(MainActivity.this, "Your task could not be added to the database...", Toast.LENGTH_LONG).show();
        }
    });
}

And here is the onActivityResult() method in my Main Activity that is calling the method to write to the database:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 0) {
        if (resultCode == Activity.RESULT_OK) {
            Task newTask = (Task) data.getSerializableExtra("New Task");

            taskList.add(newTask);

            populateTaskList();

            updateTaskList(newTask);
        }
    }
}

Finally, here is the rule from my Firestore instance:

rules_version = '2';
service cloud.firestore {
 match /databases/{database}/documents {
match /{document=**} {
  allow read, write: if false;
}}}


问:
Open-source radix/mtrie implementation in C?
I intend to use RADIX / MTRIE as my preferred data-structure for a routing implementation.

Is there a decent open source implementation available (apart from freebsd-net) which I can use for my purpose, or do I need to write one myself?

答: If you cant find anything else, you can always port this java version from Google Code.

OwnerDisplayName: harty

OwnerDisplayName: Prakash

ContentLicense: CC BY-SA 2.5


问:
Persisting data suited for enums
Most projects have some sort of data that are essentially static between releases and well-suited for use as an enum, like statuses, transaction types, error codes, etc. For example's sake, I'll just use a common status enum:

```<code>public enum Status {
    ACTIVE(10, "Active");
    EXPIRED(11, "Expired");
    /* other statuses... */

    /* constructors, getters, etc. */
}
</code>```

I'd like to know what others do in terms of persistence regarding data like these. I see a few options, each of which have some obvious advantages and disadvantages:

Persist the possible statuses in a status table and keep all of the possible status domain objects cached for use throughout the application

Only use an enum and don't persist the list of available statuses, creating a data consistency holy war between me and my DBA

Persist the statuses and maintain an enum in the code, but don't tie them together, creating duplicated data

My preference is the second option, although my DBA claims that our end users might want to access the raw data to generate reports, and not persisting the statuses would lead to an incomplete data model (counter-argument: this could be solved with documentation).

Is there a convention that most people use here? What are peoples' experiences with each and are there other alternatives?

Edit:

After thinking about it for a while, my real persistence struggle comes with handling the id values that are tied to the statuses in the database. These values would be inserted as default data when installing the application. At this point they'd have ids that are usable as foreign keys in other tables. I feel like my code needs to know about these ids so that I can easily retrieve the status objects and assign them to other objects. What do I do about this? I could add another field, like "code", to look stuff up by, or just look up statuses by name, which is icky.

答: While I am not familiar with the idea of "attributes" in Java (and I don't know what language you're using), I've generally used the idea of a code table (or domain specific tables) and I've attributed my enum values with more specific data, such as human readable strings (for instance, if my enum value is NewStudent, I would attribute it with "New Student" as a display value). I then use Reflection to examine the data in the database and insert or update records in order to bring them in line with my code, using the actual enum value as the key ID.</p>

OwnerDisplayName: robhruska

Title: Persisting data suited for enums

Body:
Most projects have some sort of data that are essentially static between releases and well-suited for use as an enum, like statuses, transaction types, error codes, etc. For example's sake, I'll just use a common status enum:

public enum Status {
    ACTIVE(10, "Active");
    EXPIRED(11, "Expired");
    /* other statuses... */

    /* constructors, getters, etc. */
}

I'd like to know what others do in terms of persistence regarding data like these. I see a few options, each of which have some obvious advantages and disadvantages:

Persist the possible statuses in a status table and keep all of the possible status domain objects cached for use throughout the application

Only use an enum and don't persist the list of available statuses, creating a data consistency holy war between me and my DBA

Persist the statuses and maintain an enum in the code, but don't tie them together, creating duplicated data

My preference is the second option, although my DBA claims that our end users might want to access the raw data to generate reports, and not persisting the statuses would lead to an incomplete data model (counter-argument: this could be solved with documentation).

Is there a convention that most people use here? What are peoples' experiences with each and are there other alternatives?

Edit:

After thinking about it for a while, my real persistence struggle comes with handling the id values that are tied to the statuses in the database. These values would be inserted as default data when installing the application. At this point they'd have ids that are usable as foreign keys in other tables. I feel like my code needs to know about these ids so that I can easily retrieve the status objects and assign them to other objects. What do I do about this? I could add another field, like "code", to look stuff up by, or just look up statuses by name, which is icky.

OwnerDisplayName: Adam Robinson


问:
Running first Android application - error message
I am getting this error when I am trying to launch my first Hello World Android application. I am doing the tutorial based on Sams Teach Yourself Android Application Development in 24 Hours.How can I resolve this?

[2011-08-18 02:33:28 - droidapp] ------------------------------
  [2011-08-18 02:33:28 - droidapp] Android Launch!
  [2011-08-18 02:33:28 - droidapp] adb is running normally.
  [2011-08-18 02:33:28 - droidapp] Performing com.droid.app.DroidappActivity activity launch
  [2011-08-18 02:33:28 - droidapp] Automatic Target Mode: Preferred AVD 'firstdroid' is not available. Launching new emulator.
  [2011-08-18 02:33:28 - droidapp] Launching a new emulator with Virtual Device 'firstdroid'

[2011-08-18 02:33:30 - Emulator] invalid command-line parameter:
  Files\Android\android-sdk\tools/emulator-arm.exe. [2011-08-18 02:33:30
  - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
  [2011-08-18 02:33:30 - Emulator] please use -help for more
  information

答:
Change the path of the SDK your path to Program Files\Android\android-sdk tools/emulator-arm.exe. Put the SDK directly in the drive, that is, d:\Android\android-sdk-tools\emulator-arm.exe.

Note: also remove spaces from the path by renaming the folder name.


问:
how to copy to clipboard text between h2 tags in selenium python
what i try to do here is get email code for verification. so I log in to the email, select and copy the 6 digits code from the email and paste it to the other tab. everything is done except i can not double click to select the 6 digit code and copy it to clipboard. the code is between h2 tag and nothing else, like this: 639094 where 639094 is actually the code which i need to be copied. how can i find the code element or whatever and copy it? here is a screen shot of the email and the chrome inspect element if anything helps.

this is the code that I use to copy the code:

```<code>codeID = driver.find_element(By.XPATH,
'//table[@class="main"]//tr//td//p//h2').text

ActionChains = ActionChains(driver)
ActionChains.double_click(codeID).perform()
time.sleep(2)
codeID.send_keys(Keys.CONTROL + 'c')
text = pyperclip.paste()
print(text)
</code>```

screen shot

答: driver.find_element_by_xpath('//table[@class="main"]//tr//td//h2').text this will give you the text/code

Body:
what i try to do here is get email code for verification. so I log in to the email, select and copy the 6 digits code from the email and paste it to the other tab. everything is done except i can not double click to select the 6 digit code and copy it to clipboard. the code is between h2 tag and nothing else, like this: 639094 where 639094 is actually the code which i need to be copied. how can i find the code element or whatever and copy it? here is a screen shot of the email and the chrome inspect element if anything helps.

this is the code that I use to copy the code:

codeID = driver.find_element(By.XPATH,
'//table[@class="main"]//tr//td//p//h2').text

ActionChains = ActionChains(driver)
ActionChains.double_click(codeID).perform()
time.sleep(2)
codeID.send_keys(Keys.CONTROL + 'c')
text = pyperclip.paste()
print(text)

screen shot


答:
Create a boolean mask to know if the name has changed from the previous row. Then filter out the second, third, ... names of a sequence before grouping by name. cumcount increment the sequence number and finally concatenate name and sequence number.

```<code># Boolean mask
m = df['name'].ne(df['name'].shift())

# Create sequence number
seq = df.loc[m].groupby('name').cumcount().astype(str) \
        .reindex(df.index, fill_value=pd.NA).ffill()

# Concatenate name and seq
df['seq'] = df['name'] + ' ' + seq
</code>```

Output:

```<code>>>> df
      name       seq
0      Tom     Tom 0
1   Joseph  Joseph 0
2   Joseph  Joseph 0
3   Joseph  Joseph 0
4      Tom     Tom 1
5      Tom     Tom 1
6     John    John 0
7      Tom     Tom 2
8      Tom     Tom 2
9     John    John 1
10  Joseph  Joseph 1

>>> m
0      True
1      True
2     False
3     False
4      True
5     False
6      True
7      True
8     False
9      True
10     True
Name: name, dtype: bool
</code>```

Title: How to auto increment counter by repeteaded values in a column

Body:
Create a boolean mask to know if the name has changed from the previous row. Then filter out the second, third, ... names of a sequence before grouping by name. cumcount increment the sequence number and finally concatenate name and sequence number.

# Boolean mask
m = df['name'].ne(df['name'].shift())

# Create sequence number
seq = df.loc[m].groupby('name').cumcount().astype(str) \
        .reindex(df.index, fill_value=pd.NA).ffill()

# Concatenate name and seq
df['seq'] = df['name'] + ' ' + seq

Output:

>>> df
      name       seq
0      Tom     Tom 0
1   Joseph  Joseph 0
2   Joseph  Joseph 0
3   Joseph  Joseph 0
4      Tom     Tom 1
5      Tom     Tom 1
6     John    John 0
7      Tom     Tom 2
8      Tom     Tom 2
9     John    John 1
10  Joseph  Joseph 1

>>> m
0      True
1      True
2     False
3     False
4      True
5     False
6      True
7      True
8     False
9      True
10     True
Name: name, dtype: bool


问:
blazor hide current div and show new one
I m tried to click @onclick="@Toggle" and hide current div and then show the new div , but its not worked for me

here the issue

#my current div is not hide and new div section not showing there

any one know the solution

thanks

code here

```<code>      <div class="sh-agreement-tp" style="background-color: #fff; padding: 20px;">

                        @*  AgreementTemplate section one *@
                        <Row Gutter="(24, 24)">
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6"><a  @onclick="@Toggle" >
                                <Card class="sh-agreement-tm" Bordered="false">
                                    <Body>
                                        <div style="text-align:center"> <p style="margin-bottom: 0rem;">Industry One</p></div>
                                    </Body>
                                </Card>
                            </a>
                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">
                                <Body>
                                    <div style="text-align:center"> <p style="margin-bottom: 0rem;">Industry  Two</p></div>
                                </Body>
                            </Card>
                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">
                                <Body>
                                    <div style="text-align:center"> <p style="margin-bottom: 0rem;">Industry Three</p></div>
                                </Body>
                            </Card>
                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">
                                <Body>
                                    <div style="text-align:center"> <p style="margin-bottom: 0rem;">Industry Four</p></div>
                                </Body>
                            </Card>
                            </Col>
                        </Row>

<div><p hidden="@(!HideLabel)">New section here </p></div>

    </div>
                        @*  END of AgreementTemplate section one *@

 @code {
      private bool HideLabel   {get;set;} = false;
      private void Toggle()
      {
         HideLabel =   !HideLabel;
      }
 }
</code>```

答:
You are doing it a wrong way, you can hide any div or paragraph like this

To hide div

```<code><div style="visibility: @(HideLabel ? "hidden" : "visible")"><p>New section here </p></div>
</code>```

To hide paragraph

```<code><div><p style="visibility: @(HideLabel ? "hidden" : "visible")">New section here </p></div>
</code>```

Body:
I m tried to click @onclick="@Toggle" and hide current div and then show the new div , but its not worked for me

here the issue

#my current div is not hide and new div section not showing there

any one know the solution

thanks

code here

                        @*  AgreementTemplate section one *@
                        <Row Gutter="(24, 24)">
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                                <Card class="sh-agreement-tm" Bordered="false">

Industry One

                                </Card>

                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">

Industry  Two

                            </Card>
                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">

Industry Three

                            </Card>
                            </Col>
                            <Col Xs="24" Sm="24" Md="24" Lg="6" Xl="6">
                            <Card class="sh-agreement-tm" Bordered="false">

Industry Four

                            </Card>
                            </Col>
                        </Row>

New section here

                        @*  END of AgreementTemplate section one *@

 @code {
      private bool HideLabel   {get;set;} = false;
      private void Toggle()
      {
         HideLabel =   !HideLabel;
      }
 }

Body:
You are doing it a wrong way, you can hide any div or paragraph like this

To hide div

<div style="visibility: @(HideLabel ? "hidden" : "visible")"><p>New section here </p></div>

To hide paragraph

<div><p style="visibility: @(HideLabel ? "hidden" : "visible")">New section here </p></div>