问:
useLayoutEffect is not working properly. What is the error?
Error Generated here:

```<code>    useLayoutEffect(()=>{
        const reInput = document.getElementById('confpassword');

        reInput.onkeydown = function () {
            document.getElementById('messageCheck').style.display = "block";
        }
        reInput.onblur = function () {
            document.getElementById('messageCheck').style.display = "none";
        }
    })
</code>```

My Input field is associated with it...

```<code><RStyle.Detailsform id="confpassword" type={confirmpassInputType} name="conf-password" minLength="8" required onChange={inputChange} onKeyDown={confirmPassChange}/>
</code>```

My Error Message Div

```<code><RStyle.ErrorMessageCont>
  <RStyle.ErrorMessage1 id="messageCheck">
    <p id="passCheck" className="invalid">
       <VscError className='errorIcon' style={errorIcon} />
       <VscCheck className='validIcon' style={validIcon} /> Password's Match
    </p>
  </RStyle.ErrorMessage1>
</RStyle.ErrorMessageCont>

</code>```

Error Message

答:
When using React, the way events are handled are slightly different than classic js, as instead of performing actions directly to the DOM you would do them through the virtual DOM instead.

Here's the equivalent of what you want to achieve, in React standards:

import { useState } from 'react';

const Component = () => {
  /**
   * Here you essentially set the state of the component
   * @see https://reactjs.org/docs/hooks-intro.html
   */
  const [showErrorMessage, setShowErrorMessage] = useState(false);

  /**
   * Here we set the state of the error message on true,
   * so to display it with the condition below (showErrorMessage && ( .. ))
   */
  const handleOnKeyDown = () => {
    setShowErrorMessage(true);
    confirmPassChange();
  };

  /**
   * Here we set the error message state on false so to hide it onBlur
   */
  const handleOnBlur = () => {
    setShowErrorMessage(false);
  };

  return (
    <>
      {showErrorMessage && (
        <RStyle.ErrorMessageCont>
          <RStyle.ErrorMessage1 id="messageCheck">

              <VscError className="errorIcon" style={errorIcon} />
              <VscCheck className="validIcon" style={validIcon} /> Password's Match

          </RStyle.ErrorMessage1>
        </RStyle.ErrorMessageCont>
      )}

      <RStyle.Detailsform
        id="confpassword"
        type={confirmpassInputType}
        name="conf-password"
        minLength="8"
        required
        onChange={inputChange}
        onKeyDown={handleOnKeyDown}
        onBlur={handleOnBlur} // Note the events are listened directly from the component
      />
    </>
  );
};
```

Body:
Error Generated here:

    useLayoutEffect(()=>{
        const reInput = document.getElementById('confpassword');

        reInput.onkeydown = function () {
            document.getElementById('messageCheck').style.display = "block";
        }
        reInput.onblur = function () {
            document.getElementById('messageCheck').style.display = "none";
        }
    })

My Input field is associated with it...

<RStyle.Detailsform id="confpassword" type={confirmpassInputType} name="conf-password" minLength="8" required onChange={inputChange} onKeyDown={confirmPassChange}/>

My Error Message Div

<RStyle.ErrorMessageCont>
  <RStyle.ErrorMessage1 id="messageCheck">

       <VscError className='errorIcon' style={errorIcon} />
       <VscCheck className='validIcon' style={validIcon} /> Password's Match

  </RStyle.ErrorMessage1>
</RStyle.ErrorMessageCont>

Error Message

Body:
When using React, the way events are handled are slightly different than classic js, as instead of performing actions directly to the DOM you would do them through the virtual DOM instead.

Here's the equivalent of what you want to achieve, in React standards:

import { useState } from 'react';

const Component = () => {
  /**
   * Here you essentially set the state of the component
   * @see https://reactjs.org/docs/hooks-intro.html
   */
  const [showErrorMessage, setShowErrorMessage] = useState(false);

  /**
   * Here we set the state of the error message on true,
   * so to display it with the condition below (showErrorMessage && ( .. ))
   */
  const handleOnKeyDown = () => {
    setShowErrorMessage(true);
    confirmPassChange();
  };

  /**
   * Here we set the error message state on false so to hide it onBlur
   */
  const handleOnBlur = () => {
    setShowErrorMessage(false);
  };

  return (
    <>
      {showErrorMessage && (
        <RStyle.ErrorMessageCont>
          <RStyle.ErrorMessage1 id="messageCheck">
            <p id="passCheck" className="invalid">
              <VscError className="errorIcon" style={errorIcon} />
              <VscCheck className="validIcon" style={validIcon} /> Password's Match
            </p>
          </RStyle.ErrorMessage1>
        </RStyle.ErrorMessageCont>
      )}

      <RStyle.Detailsform
        id="confpassword"
        type={confirmpassInputType}
        name="conf-password"
        minLength="8"
        required
        onChange={inputChange}
        onKeyDown={handleOnKeyDown}
        onBlur={handleOnBlur} // Note the events are listened directly from the component
      />
    </>
  );
};


来源: stackexchange

问:
Nest can't resolve dependencies of the TypeOrmCoreModule
src/contact/contact.module.ts

```<code>import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ContactController } from './contact.controller';
import { Contact } from './contact.entity';
import { ContactRepository } from './contact.repo';
import { ContactService } from './contact.service';

@Module({
  imports: [
     TypeOrmModule.forFeature([
      Contact,
    ]),
  ],
  controllers: [ContactController],
  providers: [ContactService, ContactRepository],
})
export class ContactModule {}
</code>```

src/app.module.ts

```<code>import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { getMetadataArgsStorage } from 'typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ContactModule } from './contact/contact.module';

@Module({
  imports: [
   TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'db',
      entities: getMetadataArgsStorage().tables.map(tbl => tbl.target),
      synchronize: true,
    }),
    ContactModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
</code>```

npm new start:dev

Give this kind of error where I try to find possibly every solution on the internet but what mistake I'm doing I don't know, I got an error like.

nest -v (8.1.6)

```<code>ERROR [ExceptionHandler] Nest can't resolve dependencies of the TypeOrmCoreModule (TypeOrmModuleOptions, ?). Please make sure that the argument ModuleRef at index [1] is available in the TypeOrmCoreModule context.

Potential solutions:
- If ModuleRef is a provider, is it part of the current TypeOrmCoreModule?
- If ModuleRef is exported from a separate @Module, is that module imported within TypeOrmCoreModule?
  @Module({
    imports: [ /* the Module containing ModuleRef */ ]
  })
</code>```

答:
I was having this problem because of a bad installation of typeorm.

Works for me:

1- Delete node_module

2- Run npm i

3- Run npm install --save @nestjs/typeorm typeorm mysql2 again im my project.

ContentLicense: CC BY-SA 4.0

Body:
src/contact/contact.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ContactController } from './contact.controller';
import { Contact } from './contact.entity';
import { ContactRepository } from './contact.repo';
import { ContactService } from './contact.service';

@Module({
  imports: [
     TypeOrmModule.forFeature([
      Contact,
    ]),
  ],
  controllers: [ContactController],
  providers: [ContactService, ContactRepository],
})
export class ContactModule {}

src/app.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { getMetadataArgsStorage } from 'typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ContactModule } from './contact/contact.module';

@Module({
  imports: [
   TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'db',
      entities: getMetadataArgsStorage().tables.map(tbl => tbl.target),
      synchronize: true,
    }),
    ContactModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

npm new start:dev

Give this kind of error where I try to find possibly every solution on the internet but what mistake I'm doing I don't know, I got an error like.

nest -v (8.1.6)

ERROR [ExceptionHandler] Nest can't resolve dependencies of the TypeOrmCoreModule (TypeOrmModuleOptions, ?). Please make sure that the argument ModuleRef at index [1] is available in the TypeOrmCoreModule context.

Potential solutions:
- If ModuleRef is a provider, is it part of the current TypeOrmCoreModule?
- If ModuleRef is exported from a separate @Module, is that module imported within TypeOrmCoreModule?
  @Module({
    imports: [ /* the Module containing ModuleRef */ ]
  })


问:
What is the real difference between "Bastard Injection" and "Poor Man's Injection"
From the Dependency Injection in .NET book I know that the object graph should be created at the Composition Root of the application which makes a lot of sense to me when you are using an IoC Container.

In all the applications I've seen when an attempt to use DI is being made, there are always two constructors:

the one with the dependencies as parameters and

the "default" one with no parameters which in turn calls the other one "newing" up all the dependencies

In the aforementioned book, however, this is called the "Bastard Injection anti-pattern" and that is what I used to know as "Poor Man's Injection".

Now considering all this, I would say then that "Poor Man's Injection" would be just not using an IoC Container and instead coding all the object graph by hand on the said Composition Root.

So my questions are:

Am I understanding these concepts correctly or am I completely off track?

If you still need to register all the dependencies in the IoC container vs. coding them by hand in the exact same Composition Root, what's the real benefit of using an IoC container?

If I have misunderstood what "Poor Man's Injection" really is, could someone please clarify it?

答:
When it comes to DI, there's a lot of conflicting use of terminology out there. The term Poor Man's DI is no exception. To some people, it means one thing and to others it means something different.

One of the things I wanted to do with the book was to supply a consistent pattern language for DI. When it came to all of those terms with conflicting use, I had two options: Come up with a completely new term, or pick the most prevalent use (according to my subjective judgment).

In general, I've preferred to re-use existing terminology instead of making up a completely new (and thus alien) pattern language. That means that in certain cases (such as Poor Man's DI), you may have a different notion of what the name is than the definition given in the book. That often happens with patterns books.

At least I find it reassuring that the book seems to have done its job of explaining exactly both Poor Man's DI and Bastard Injection, because the interpretation given in the O.P. is spot on.

Regarding the real benefit of a DI Container I will refer you to this answer: Arguments against Inversion of Control containers

P.S. 2018-04-13: I'd like to point out that I've years ago come to acknowledge that the term Poor Man's DI does a poor (sic!) job of communicating the essence of the principle, so for years, now, I've instead called it Pure DI.

P.P.S. 2020-07-17: We removed the term Bastard Injection from the second edition. In the second edition we simply use the more general term Control Freak to specify that your code "depend[s] on a Volatile Dependency in any place other than a Composition Root."


问:
How to render conditional content in react
I am trying to figure out how to tweak this boilerplate repo, so that on the index page, I can either render one page for the logged in user, or another for anyone else. The boilerplate index renders the same page, always, but adds an extra bit to it if there is an authenticated user.

Currently, when I try:

```<code>return (
    <Box>
      <Head>
        <title>title</title>
      </Head>
      <div>
      <Limiter pt={20} minH="calc(100vh - 65px)">
        <Center flexDir="column">
        {!me  &&
            <Box textStyle='h1' mb={8} mt={8} textAlign="center" >
              <HomeLandingPage />
            </Box>
        }
        {me && router.replace("/dashboard")}

        </Center>
      </Limiter>
      </div>
    </Box>
  )
</code>```

I get no errors in the terminal, but I get this error in the browser:

Error: Objects are not valid as a React child (found: [object
Promise]). If you meant to render a collection of children, use an
array instead.

If I remove the second condition (ie me is true), I can render the HomeLandingPage without an error, but I  just get an empty page if !me is false. The same is not true if I delete the !me condition and just try to render the logged in user page. I get the same error as when I try to use both alternatives.

I don't know where to put an array to deal with this. Some posts about this error resolved their problems by putting everything inside a div tag. I'm using ChakraUI, which calls a div a Box, which I am using, but I tried adding extra divs at each level of the home page to try and find a version that works - none did.

I was trying to rely on the login redirect on successful authentication handler, which has:

```<code>  const onSubmit = (data: LoginInput) => {
    return form.handler(() => login({ variables: { data } }), {
      onSuccess: async (data) => {
        await fetch("/api/login", {
          method: "post",
          body: JSON.stringify({ [LOGIN_TOKEN_KEY]: data.login.token }),
        })
        client.writeQuery<MeQuery>({ query: MeDocument, data: { me: data.login.user } })
        router.replace(redirect || "/dashboard")
        // router.replace('/dashboard')
        // router.replace('/profile/index')
        // console.log(redirect, REDIRECT_PATH)

      },
    })
  }
</code>```

I expected this handler to redirect to the /dashboard on successful login - but it does not.

If I remove the me handler from the index.tsx page, I just get an empty page page when I authenticate, and I can then add /dashboard to the browser url to navigate to the page that I am trying to redirect to on successful authentication.

My first line of enquiry to solve this is why I can't have a redirect in the home page if me is true.

Are there any clues that could inspire the direction of my research into next steps?

答:
You're trying to render a function which returns a promise. Instead, put it outside of the render code, so that it can redirect you to the desired location. Your routing will take care of rendering the dashboard component once redirected.</p>
```<code>if (me) {
  router.replace("/dashboard");
  return <LoadingSpinner />; // or some indication that we're redirecting
}

// this will only be rendered for a guest user
return (
  <Box>
    <Head>
      <title>title</title>
    </Head>
    <div>
    <Limiter pt={20} minH="calc(100vh - 65px)">
      <Center flexDir="column">
        <Box textStyle='h1' mb={8} mt={8} textAlign="center" >
          <HomeLandingPage />
        </Box>
      </Center>
    </Limiter>
    </div>
  </Box>
)
</code>```

Body:
I am trying to figure out how to tweak this boilerplate repo, so that on the index page, I can either render one page for the logged in user, or another for anyone else. The boilerplate index renders the same page, always, but adds an extra bit to it if there is an authenticated user.

Currently, when I try:

return (
    <Box>

        <title>title</title>

      <Limiter pt={20} minH="calc(100vh - 65px)">

        {!me  &&
            <Box textStyle='h1' mb={8} mt={8} textAlign="center" >
              <HomeLandingPage />
            </Box>
        }
        {me && router.replace("/dashboard")}

      </Limiter>

    </Box>
  )

I get no errors in the terminal, but I get this error in the browser:

Error: Objects are not valid as a React child (found: [object
Promise]). If you meant to render a collection of children, use an
array instead.

If I remove the second condition (ie me is true), I can render the HomeLandingPage without an error, but I  just get an empty page if !me is false. The same is not true if I delete the !me condition and just try to render the logged in user page. I get the same error as when I try to use both alternatives.

I don't know where to put an array to deal with this. Some posts about this error resolved their problems by putting everything inside a div tag. I'm using ChakraUI, which calls a div a Box, which I am using, but I tried adding extra divs at each level of the home page to try and find a version that works - none did.

I was trying to rely on the login redirect on successful authentication handler, which has:

  const onSubmit = (data: LoginInput) => {
    return form.handler(() => login({ variables: { data } }), {
      onSuccess: async (data) => {
        await fetch("/api/login", {
          method: "post",
          body: JSON.stringify({ [LOGIN_TOKEN_KEY]: data.login.token }),
        })
        client.writeQuery<MeQuery>({ query: MeDocument, data: { me: data.login.user } })
        router.replace(redirect || "/dashboard")
        // router.replace('/dashboard')
        // router.replace('/profile/index')
        // console.log(redirect, REDIRECT_PATH)

      },
    })
  }

I expected this handler to redirect to the /dashboard on successful login - but it does not.

If I remove the me handler from the index.tsx page, I just get an empty page page when I authenticate, and I can then add /dashboard to the browser url to navigate to the page that I am trying to redirect to on successful authentication.

My first line of enquiry to solve this is why I can't have a redirect in the home page if me is true.

Are there any clues that could inspire the direction of my research into next steps?

Body:
You're trying to render a function which returns a promise. Instead, put it outside of the render code, so that it can redirect you to the desired location. Your routing will take care of rendering the dashboard component once redirected.

if (me) {
  router.replace("/dashboard");
  return <LoadingSpinner />; // or some indication that we're redirecting
}

// this will only be rendered for a guest user
return (
  <Box>
    <Head>
      <title>title</title>
    </Head>
    <div>
    <Limiter pt={20} minH="calc(100vh - 65px)">
      <Center flexDir="column">
        <Box textStyle='h1' mb={8} mt={8} textAlign="center" >
          <HomeLandingPage />
        </Box>
      </Center>
    </Limiter>
    </div>
  </Box>
)


问:
Programmatically Set an href Link in React
I have a product that I want to programatically set a Checkout Session URL and then redirect a user when they click on an  tag.

```<code>const PlanComponent = () => {

    const [tiers, setTiers] = useState([]);

    async function CheckoutSessionUrl(tierId) {
        var result = null

        await CreateCheckoutSession(
            "PRODUCT_ID",
            tierId,
            "UID"
        ).then(function(response) {
            result = response
        })
        return result;
    };

    async function LoadProducts() {
        var result = []
        await GetProducts("PRODUCT_ID").then(function(response) {
          for (var i = 0; i < response.length; i++) {
              var tier_id = response[i]["tier_id"]
              CheckoutSessionUrl(tier_id).then(function(tier_response) {
                  response[i]["url"] = tier_response;
              })
          }
          console.log("printing tiers");
          console.log(response);

          return response;
        }).then(function(response){
            result = response;
            setTiers(result)
            return result;
        });

        return result;

    }

    useEffect(() => {
      // Some initialization logic here
      LoadProducts().then(function(response) {
        console.log("setting tiers")
        console.log(response)
        //setTiers(response)
      })

    }, []);

  return (
    <div className="bg-white">
      <div className="max-w-7xl mx-auto py-24 px-4 sm:px-6 lg:px-8">
        <div className="sm:flex sm:flex-col sm:align-center">
          <h1 className="text-5xl font-extrabold text-gray-900 sm:text-center">Pricing Plans</h1>
          <p className="mt-5 text-xl text-gray-500 sm:text-center">
            Start building for free, then add a site plan to go live. Account plans unlock additional features.
          </p>

        </div>
        <div className="mt-12 space-y-4 sm:mt-16 sm:space-y-0 sm:grid sm:grid-cols-2 sm:gap-6 lg:max-w-4xl lg:mx-auto xl:max-w-none xl:mx-0 xl:grid-cols-4">
          {tiers.map((tier) => (
            <div key={tier.name} className="border border-gray-200 rounded-lg shadow-sm divide-y divide-gray-200">
              <div className="p-6">
                <h2 className="text-lg leading-6 font-medium text-gray-900">{tier.name}</h2>
                <p className="mt-4 text-sm text-gray-500">{tier.description}</p>
                <p className="mt-8">
                  <span className="text-4xl font-extrabold text-gray-900">${tier.price}</span>{' '}
                  <span className="text-base font-medium text-gray-500">/mo</span>
                </p>

                    <a
                    href={tier.url}
                    className="mt-8 block w-full bg-gray-800 border border-gray-800 rounded-md py-2 text-sm font-semibold text-white text-center hover:bg-gray-900"
                    >
                    Buy {tier.name}
                    </a>

              </div>
              <div className="pt-6 pb-8 px-6">
                <h3 className="text-xs font-medium text-gray-900 tracking-wide uppercase">What's included</h3>
                <ul role="list" className="mt-6 space-y-4">
                  {tier.users.map((feature) => (
                    <li key={feature} className="flex space-x-3">
                      {/*<CheckIcon className="flex-shrink-0 h-5 w-5 text-green-500" aria-hidden="true" />*/}
                      <span className="text-sm text-gray-500">{feature}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
</code>```

so if you look at the href={tier.url} it's not being set correctly. I feel like I'm not doing this correctly. Would love some feedback on how to actually get this working properly. IT looks like the tier.url new field isn't being set correctly (doesn't exist in the initial request but all the other attributes work).

The other option I wanted to do was when a user clicked a Button, it would generate a URL and redirect a user to that new external url but the navigation kept breaking.

答:
Oh I found out what was happening. I needed to replace

```<code> await GetProducts("PRODUCT_ID").then(function(response) {
</code>```

with

```<code> await GetProducts("PRODUCT_ID").then(async function(response) {
</code>```

Body:
I have a product that I want to programatically set a Checkout Session URL and then redirect a user when they click on an  tag.

const PlanComponent = () => {

    const [tiers, setTiers] = useState([]);

    async function CheckoutSessionUrl(tierId) {
        var result = null

        await CreateCheckoutSession(
            "PRODUCT_ID",
            tierId,
            "UID"
        ).then(function(response) {
            result = response
        })
        return result;
    };

    async function LoadProducts() {
        var result = []
        await GetProducts("PRODUCT_ID").then(function(response) {
          for (var i = 0; i < response.length; i++) {
              var tier_id = response[i]["tier_id"]
              CheckoutSessionUrl(tier_id).then(function(tier_response) {
                  response[i]["url"] = tier_response;
              })
          }
          console.log("printing tiers");
          console.log(response);

          return response;
        }).then(function(response){
            result = response;
            setTiers(result)
            return result;
        });

        return result;

    }

    useEffect(() => {
      // Some initialization logic here
      LoadProducts().then(function(response) {
        console.log("setting tiers")
        console.log(response)
        //setTiers(response)
      })

    }, []);

  return (

Pricing Plans

            Start building for free, then add a site plan to go live. Account plans unlock additional features.

          {tiers.map((tier) => (

{tier.name}

{tier.description}

                  ${tier.price}{' '}
                  /mo

                    Buy {tier.name}

What's included

                  {tier.users.map((feature) => (

                      {/*<CheckIcon className="flex-shrink-0 h-5 w-5 text-green-500" aria-hidden="true" />*/}
                      {feature}

                  ))}

          ))}

  )
}

so if you look at the href={tier.url} it's not being set correctly. I feel like I'm not doing this correctly. Would love some feedback on how to actually get this working properly. IT looks like the tier.url new field isn't being set correctly (doesn't exist in the initial request but all the other attributes work).

The other option I wanted to do was when a user clicked a Button, it would generate a URL and redirect a user to that new external url but the navigation kept breaking.

Body:
Oh I found out what was happening. I needed to replace

 await GetProducts("PRODUCT_ID").then(function(response) {

with

 await GetProducts("PRODUCT_ID").then(async function(response) {


问:
Where's docker's daemon.json? (missing)
From docs:

The default location of the configuration file on Linux is
  /etc/docker/daemon.json

But I don't have it on my fresh docker installation:

```<code># docker --version
Docker version 17.03.1-ce, build c6d412e
# ls -la /etc/docker/
total 12
drwx------  2 root root 4096 Apr 28 17:58 .
drwxr-xr-x 96 root root 4096 Apr 28 17:58 ..
-rw-------  1 root root  244 Apr 28 17:58 key.json
# lsb_release -cs
trusty
</code>```

答:
Docker 19+, Mac

Config file is now available in ~/.docker/daemon.json

Title: Where's docker's daemon.json? (missing)

Body:
From docs:

The default location of the configuration file on Linux is
  /etc/docker/daemon.json

But I don't have it on my fresh docker installation:

# docker --version
Docker version 17.03.1-ce, build c6d412e
# ls -la /etc/docker/
total 12
drwx------  2 root root 4096 Apr 28 17:58 .
drwxr-xr-x 96 root root 4096 Apr 28 17:58 ..
-rw-------  1 root root  244 Apr 28 17:58 key.json
# lsb_release -cs
trusty


问:
Bluetooth "out of band" (OOB) pairing on Android?
I've been searching the internet and haven't seen anything in the way of how to exactly implement OOB pairing. I was hoping somebody here could point me to some example code to help me out.  The chat example in the Android developers site didn't really dive into this type of pairing at all.

Basically, I have an Android tablet that I want to securely pair with a device, written in C++, that has no built in display/IO mechanism.   The tablet to be paired will act as the GUI/IO interface and I'll send message back and fourth over Bluetooth.  Thus I want to securely pair the tablet with each device through the OOB paring scheme.

I understand the concept of OOB but I'm having difficulty finding the proper methods to call when looking on the android.developers.com site for my android client code.  Also when looking at the bluez stuff I can't find much to go on for my C++ written server.

The basic use case is the user will connect the tablet to the device via a USB connection.  The USB connection will facilitate the passing of keys/mac addresses for each device and then using that information pair Bluetooth with each other.

I can figure out the USB part but once I have the keys and necessary information on the client and server I can't seem to track down the correct methods to call for both ends to successfully and securely pair.

I already have a client/server talking via an insecure connection so really the only part I'm having trouble with is the actually pairing on both ends.  As once I'm paired I can used a secureRFComm to do all of my future messaging.

答:
I have my issue 95% solved but I have hit a small road block.  First I'll update this post with a more concrete answer to the original question and post my question at the end.

To recap, my task is to use out of band (oob) pairing to securely pair an android tablet using Honeycomb 3.2 to a beagle board through USB.  I can't post specific code, but I'll give you all the steps needed to get this done.

On the beagle board, I have the bluez 4.96 stack installed with the dbusoob plugin installed.  To confirm this is set up correctly install 2 Bluetooth dongles on the beagle board and run the OOB Test Code found in in the bluez archive in the test folder.  This is a python script.  The script should successfully pair the 2 Bluetooth dongles, if not bluez is probably not setup correctly.

To get USB communications with a tablet working you need to install mtpfs and mtp-tools.  These are used to mount your tablet.  They way I solved getting OOB information between the 2 devices were to mount the tablet on the beagle board.  Once mounted the tablet and beagle board can write out a file with the information needed.

On the android side OOB is not supported in the public API so things get tricky.  I believe this is because Honeycomb 3.2 does not have a bluez stack that officially supports OOB bonding, but Google has some kind of implementation coded in.  I believe this because if you look at gingerbread source code for the Bluetooth Adapter and Bluetooth Device classes you can see OOB methods available but not exposed through the documented API.

These methods are still public so you can call them through reflection.  Using reflection you can also get all of the method signatures in a class.  This is how I figured out what methods I had available to me.

Beware though that many are not documented and it's not obvious what some do.  The important ones to make note of are the readOutOfBandData() in the adapter class and setDeviceOutOfandData() in the device class.

Another gotcha you might run into is when you write your oob data to a file on the tablet to be read by the beagle board.  Since android uses mtp you must index your file after it is written to the internal sdcard storage.  To solve this you need to make use of the MediaScannerConnection class and the scanFile() method.

Hopefully the above helps anybody else with this same issue.

Now on to my question.  I have my android application working great and my beagle board code is the testOOB example updated to have one end read OOB information from a file.  Now the issue I see is when executed everybody sees each other great, but on the tablet I still get a message asking if I want to pair with device xyz.  There are no keys or numbers.  It just asks "Pair with Device XYZ" or something along those lines.

If I press "pair" it's all paired from the tablets point of view, BUT the python script returns that the paring failed.  The python script on the beagle board is calling the actual method to do the bonding between the devices.  Even when I have the android initiate the createBond call I see the same outcome.  I can guarantee that I have set the required OOB data on both ends before trying to pair in both cases so that doesn't seem to be it.

So my issues that I'm hoping somebody can help me with are:

1) Why do I even get a message on android if the OOB data is exchanged properly?  Is there another call I'm missing and on which end?

2)  Why does the beagle board python script return paring failed even thought I press "pair" popup displayed on the tablet.  The tablet and blues monitor both show the devices as paired.  Some again I'm leaning towards the idea that I am missing something.

Thanks to anybody that can help :)

EDIT:

To add more information here is the logcat output:

```<code>D/UIBluetooth( 4363): !!!!!! Start Bond !!!!!!
D/BluetoothService( 1703): Setting out of band data for: 00:02:76:24:C2:8F:[-37, -1, 65, -42, -121, -75, -60, -4, -47, -86, -88, 14, 64, 83, 16, 96]:[-112, 34, 121, -97, 15, -54, -83, -
93, 104, -83, -124, -25, 89, 114, 66, 62]
D/BluetoothBondState( 1703): 00:02:76:24:C2:8F bond state 10 -> 11 (0)
D/UIBluetooth( 4363): createOobBond Successful
V/BluetoothEventManager( 2174): Received android.bluetooth.device.action.BOND_STATE_CHANGED
D/BluetoothEventLoop( 1703): Property Changed: Devices : 1
D/BluetoothEventLoop( 1703): Device property changed: 00:02:76:24:C2:8F property: Connected value: true
I/BluetoothEventLoop.cpp( 1703): agent_event_filter: Received method org.bluez.Agent:RequestOobData
I/BluetoothEventLoop.cpp( 1703): agent_event_filter: Received method org.bluez.Agent:RequestOobData
</code>```

The last two line seems to be triggering the popup on Android to either Pair/Cancel with the Device in questions.  I would like Android to know to just auto bond and not even ask.  I could be missing a call or doing something out of order for all I know.  The last thing I do in my code is to create the bond which seems to be the obvious place to do it....

Thanks for any suggestions!

Body:
I have my issue 95% solved but I have hit a small road block.  First I'll update this post with a more concrete answer to the original question and post my question at the end.

To recap, my task is to use out of band (oob) pairing to securely pair an android tablet using Honeycomb 3.2 to a beagle board through USB.  I can't post specific code, but I'll give you all the steps needed to get this done.

On the beagle board, I have the bluez 4.96 stack installed with the dbusoob plugin installed.  To confirm this is set up correctly install 2 Bluetooth dongles on the beagle board and run the OOB Test Code found in in the bluez archive in the test folder.  This is a python script.  The script should successfully pair the 2 Bluetooth dongles, if not bluez is probably not setup correctly.

To get USB communications with a tablet working you need to install mtpfs and mtp-tools.  These are used to mount your tablet.  They way I solved getting OOB information between the 2 devices were to mount the tablet on the beagle board.  Once mounted the tablet and beagle board can write out a file with the information needed.

On the android side OOB is not supported in the public API so things get tricky.  I believe this is because Honeycomb 3.2 does not have a bluez stack that officially supports OOB bonding, but Google has some kind of implementation coded in.  I believe this because if you look at gingerbread source code for the Bluetooth Adapter and Bluetooth Device classes you can see OOB methods available but not exposed through the documented API.

These methods are still public so you can call them through reflection.  Using reflection you can also get all of the method signatures in a class.  This is how I figured out what methods I had available to me.

Beware though that many are not documented and it's not obvious what some do.  The important ones to make note of are the readOutOfBandData() in the adapter class and setDeviceOutOfandData() in the device class.

Another gotcha you might run into is when you write your oob data to a file on the tablet to be read by the beagle board.  Since android uses mtp you must index your file after it is written to the internal sdcard storage.  To solve this you need to make use of the MediaScannerConnection class and the scanFile() method.

Hopefully the above helps anybody else with this same issue.

Now on to my question.  I have my android application working great and my beagle board code is the testOOB example updated to have one end read OOB information from a file.  Now the issue I see is when executed everybody sees each other great, but on the tablet I still get a message asking if I want to pair with device xyz.  There are no keys or numbers.  It just asks "Pair with Device XYZ" or something along those lines.

If I press "pair" it's all paired from the tablets point of view, BUT the python script returns that the paring failed.  The python script on the beagle board is calling the actual method to do the bonding between the devices.  Even when I have the android initiate the createBond call I see the same outcome.  I can guarantee that I have set the required OOB data on both ends before trying to pair in both cases so that doesn't seem to be it.

So my issues that I'm hoping somebody can help me with are:

1) Why do I even get a message on android if the OOB data is exchanged properly?  Is there another call I'm missing and on which end?

2)  Why does the beagle board python script return paring failed even thought I press "pair" popup displayed on the tablet.  The tablet and blues monitor both show the devices as paired.  Some again I'm leaning towards the idea that I am missing something.

Thanks to anybody that can help :)

EDIT:

To add more information here is the logcat output:

D/UIBluetooth( 4363): !!!!!! Start Bond !!!!!!
D/BluetoothService( 1703): Setting out of band data for: 00:02:76:24:C2:8F:[-37, -1, 65, -42, -121, -75, -60, -4, -47, -86, -88, 14, 64, 83, 16, 96]:[-112, 34, 121, -97, 15, -54, -83, -
93, 104, -83, -124, -25, 89, 114, 66, 62]
D/BluetoothBondState( 1703): 00:02:76:24:C2:8F bond state 10 -> 11 (0)
D/UIBluetooth( 4363): createOobBond Successful
V/BluetoothEventManager( 2174): Received android.bluetooth.device.action.BOND_STATE_CHANGED
D/BluetoothEventLoop( 1703): Property Changed: Devices : 1
D/BluetoothEventLoop( 1703): Device property changed: 00:02:76:24:C2:8F property: Connected value: true
I/BluetoothEventLoop.cpp( 1703): agent_event_filter: Received method org.bluez.Agent:RequestOobData
I/BluetoothEventLoop.cpp( 1703): agent_event_filter: Received method org.bluez.Agent:RequestOobData

The last two line seems to be triggering the popup on Android to either Pair/Cancel with the Device in questions.  I would like Android to know to just auto bond and not even ask.  I could be missing a call or doing something out of order for all I know.  The last thing I do in my code is to create the bond which seems to be the obvious place to do it....

Thanks for any suggestions!

ContentLicense: CC BY-SA 3.0


问:
How to copy last row of data in all worksheets and paste it into one worksheet
Currently I have a lot of sheets in my Excel file but I want to get the last row of data in sheets that start with "6" as their names as the other sheets are not relevant. In the sheets that start with 6 are all in the same format but have different number of rows, I am interested in extracting the last row in all those sheets (columns D:J) and placing it into a "master sheet". Since I am quite new to VBA, how would I go about doing that? Thanks in advance!

What I have currently that can copy one sheet and paste into my master sheet "Sheet2":

```<code>   With Sheets("6363")
        With Range(.Cells(.Rows.Count, "D").End(xlUp), _
                   .Cells(.Cells(.Rows.Count, "D").End(xlUp).row, .Columns.Count).End(xlToLeft))
            Worksheets("Sheet2").Range("D1").Resize(, .Columns.Count).Value = .Value
        End With
    End With
</code>```

答:
This will copy the last row, columns D-J, from every sheet with a name that starts with '6'.

It will put the copied data into the next empty row, starting at column D, of 'Sheet2'.

Sub CopySix()
Dim wsSrc As Worksheet
Dim wsDst As Worksheet
Dim rngSrc As Range
Dim rngDst As Range

    Set wsDst = ActiveWorkbook.Sheets("Sheet2")

    Set rngDst = wsDst.Range("D" & Rows.Count).End(xlUp).Offset(1)

    For Each wsSrc In ActiveWorkbook.Sheets
        If Left(wsSrc.Name, 1) = "6" Then
            Set rngSrc = wsSrc.Range("D" & Rows.Count).End(xlUp).Resize(, 7)
            rngDst.Resize(, 7).Value = rngSrc.Value
            Set rngDst = rngDst.Offset(1)
        End If
    Next wsSrc

End Sub

```

Body:
Currently I have a lot of sheets in my Excel file but I want to get the last row of data in sheets that start with "6" as their names as the other sheets are not relevant. In the sheets that start with 6 are all in the same format but have different number of rows, I am interested in extracting the last row in all those sheets (columns D:J) and placing it into a "master sheet". Since I am quite new to VBA, how would I go about doing that? Thanks in advance!

What I have currently that can copy one sheet and paste into my master sheet "Sheet2":

   With Sheets("6363")
        With Range(.Cells(.Rows.Count, "D").End(xlUp), _
                   .Cells(.Cells(.Rows.Count, "D").End(xlUp).row, .Columns.Count).End(xlToLeft))
            Worksheets("Sheet2").Range("D1").Resize(, .Columns.Count).Value = .Value
        End With
    End With


问:
Which database should I use to store in real time my exact location from an Android application and then display it in my website (tracking system)?
I'm kind of new at backend development, and I should to create a website (tracking) display the location of my phone, this location I have to retrieve from an android application.

My question is which database should I use? sql, nosql ?? mongoDB, Phpmyadmin !!

答: Your use case seems to be suitable for time series in mongo, check here:https://docs.mongodb.com/manual/core/timeseries-collections/</p>


问:
Re-installing OpenCV (last time with dll "bundle" (exe) and now through opencv-python-contrib on Windows
I have a problem and after searching without any solutions its time for my first question on this forum.

About a month ago i downloaded openCV (opencv-4.5.5-vc14...exe) and installed it.
After about a month i now wanted to try some other trackers and therefore i need contrib.

So, i deleted the openCV directory. (this could have been stupid but i did).

When i install opencv-python-contrib (following instructions on github/opencv/opencv-python)

```<code>d:\OpenCV>pip install opencv-contrib-python
Collecting opencv-contrib-python
  Using cached opencv_contrib_python-4.5.5.62-cp36-abi3-win_amd64.whl (42.2 MB)
Requirement already satisfied: numpy>=1.17.3 in c:\users\martin\appdata\roaming\python\python39\site-packages (from opencv-contrib-python) (1.22.2)
Installing collected packages: opencv-contrib-python
Successfully installed opencv-contrib-python-4.5.5.62

d:\OpenCV>python
Python 3.9.10 (tags/v3.9.10:f2f3f53, Jan 17 2022, 15:14:21) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> print (cv2.__version__)
4.5.5
>>>
</code>```

i get 4.5.5 (and no contrib add on).

I have updated pip and i have tried removing the version of python that i used in my earlier install.

I have checked path in environmental setting removing everything about opencv

What is it i´m missing?

When i uninstall (pip uninstall opencv-contrib-python) and try to import cv2 there is an error and files i have built in VS turns crazy.

When i reboot my computer and install (pip install opencv-contrib-python) we are happy campers again (besides contrib not working). as from the installation contrib is successfully installed but when i try a contrib command it does not work and the cv2.version says its not there.

Edit = When i open Visual studio/environment i have the opencv-contrib-python (4.5.5.62).

In my python/site-package i have a opencv_contrib_python-4.5.5.62.dist-info directory containning;

installer

license

license-3rd-party

metadata

record

request

top_level

wheel

Could anyone check their directory and see if they have the same so that i know that everything got installed?

I also have a cv2 map containing (amongst other files and directoris) cv2.pyd

Is there a PATH i need to fix?

Does anyone have any ideas?

Is there some information that i should provide?

I´m open to all suggestions, high and low ;)

i can use opencv in VS without any problems, its just the contrib that is missing.

sorry for my English, i´m a swede and English is far from something i brag about on my resume.

Best,

Martin

答: Well now its working. I could not really say how, but it does so; problem solved..</p>

Body:
I have a problem and after searching without any solutions its time for my first question on this forum.

About a month ago i downloaded openCV (opencv-4.5.5-vc14...exe) and installed it.
After about a month i now wanted to try some other trackers and therefore i need contrib.

So, i deleted the openCV directory. (this could have been stupid but i did).

When i install opencv-python-contrib (following instructions on github/opencv/opencv-python)

d:\OpenCV>pip install opencv-contrib-python
Collecting opencv-contrib-python
  Using cached opencv_contrib_python-4.5.5.62-cp36-abi3-win_amd64.whl (42.2 MB)
Requirement already satisfied: numpy>=1.17.3 in c:\users\martin\appdata\roaming\python\python39\site-packages (from opencv-contrib-python) (1.22.2)
Installing collected packages: opencv-contrib-python
Successfully installed opencv-contrib-python-4.5.5.62

d:\OpenCV>python
Python 3.9.10 (tags/v3.9.10:f2f3f53, Jan 17 2022, 15:14:21) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> print (cv2.__version__)
4.5.5
>>>

i get 4.5.5 (and no contrib add on).

I have updated pip and i have tried removing the version of python that i used in my earlier install.

I have checked path in environmental setting removing everything about opencv

What is it i´m missing?

When i uninstall (pip uninstall opencv-contrib-python) and try to import cv2 there is an error and files i have built in VS turns crazy.

When i reboot my computer and install (pip install opencv-contrib-python) we are happy campers again (besides contrib not working). as from the installation contrib is successfully installed but when i try a contrib command it does not work and the cv2.version says its not there.

Edit = When i open Visual studio/environment i have the opencv-contrib-python (4.5.5.62).

In my python/site-package i have a opencv_contrib_python-4.5.5.62.dist-info directory containning;

installer

license

license-3rd-party

metadata

record

request

top_level

wheel

Could anyone check their directory and see if they have the same so that i know that everything got installed?

I also have a cv2 map containing (amongst other files and directoris) cv2.pyd

Is there a PATH i need to fix?

Does anyone have any ideas?

Is there some information that i should provide?

I´m open to all suggestions, high and low ;)

i can use opencv in VS without any problems, its just the contrib that is missing.

sorry for my English, i´m a swede and English is far from something i brag about on my resume.

Best,

Martin


问:
FMCW radar: understanding of doppler fft
I am using fmcw radar to find out distance and speed of moving objects using stm32l476 microcontroller. I transmit the modulation signal as sawtooth waveform and I read the recieved signal in the digital form using ADC function available. Then, I copy this recieved ADC data into fft_in array(converting it into float32_t)(fft_in array size = 512). After copying this fft_in array, I apply fft on this array and process it for finding out range of the object. Until here everything works fine.

Now, in order to find velocity of the object, first, I copy this arrays(fft_in) as rows of the matrix for 64 chirps(Matrix size[64][512]). Then, I take Peak range bin column and apply fft for this column array. So while processing this column array by applying fft, its length reduce to half[32 elements]. Then finding out peak value bin multiplied by frequnecy resolution gives the phase differnce 'w' from which velocity can be calculated as "=/ ".

while running this algorithm, I find that when object is stationery, I get peak value at 22th element(out of 32 elements). what does this imply?

I have sampling frequency for ADC as 24502hz. So per bin value for range estimation is 47.8566hz (24502/512).

I have 64 chirps and Tc is 0.006325s. So 1/0.006325 gives 158.10Hz.What would be per velocity bin resolution, Is it 2.47Hz(158.10/64)? I have bit confusion in this concept.How does 2nd fft works for finding out velocity in fmcw radar?

答:
Infineon has excellent resources on this topic, see this FAQ for the basics: https://www.infineon.com/dgdl/Infineon-Radar%20FAQ-PI-v02_00-EN.pdf?fileId=5546d46266f85d6301671c76d2a00614

If you want to know more details, check out the P2G Software User Manual:
https://www.infineon.com/dgdl/Infineon-P2G_Software_User_Manual-UserManual-v01_01-EN.pdf?fileId=5546d4627762291e017769040a233324 (Chapter 4)

There is even the software available with all the algorithms (including FMCW). How to get the software with the "Infineon Toolbox" is described here: https://www.mouser.com/pdfdocs/Infineon_Position2Go_QS.pdf

Some hints from me:

I suggest applying a window function before the fft https://en.wikipedia.org/wiki/Window_function and remove the mean.

Read about frequency mixers https://en.wikipedia.org/wiki/Frequency_mixer


问:
Conversions to arrays of unknown bound: g++ vs. clang++
Note: this is the follow-up question for this question.

Sample code (t334.cpp):

```<code>typedef int T0;
typedef T0  T1[];
typedef T1* T2[];

T1 x1 = { 13 };
T2 x2 = { &x1 };
</code>```

Invocations:

```<code>$ g++ t334.cpp -std=c++11 -pedantic -Wall -Wextra -c
t334.cpp:6:11: warning: conversions to arrays of unknown bound are only available with ‘-std=c++20’ or ‘-std=gnu++20’ [-Wpedantic]
    6 | T2 x2 = { &x1 };
      |           ^~~

$ clang++ t334.cpp -std=c++11 -pedantic -Wall -Wextra -c
t334.cpp:6:11: error: cannot initialize an array element of type 'T1 *' (aka 'T0 (*)[]') with an rvalue of type 'T0 (*)[1]'
T2 x2 = { &x1 };
          ^~~
</code>```

Can someone explain, what is wrong with this C++ code?

Note: the equivalent C code is valid, because int (*)[] and int (*)[1] are compatible. Meaning that in C++ they aren't?

答:
The first definition is of an array of known bound that is deduced from the initializer. It has the same effect as:

```<code>int x1[1] = {13};
</code>```

That means x1 has type int[1], and &x1 has type int (*)[1].

The second definition is trying to initialize a variable of type int (*)[] from a (brace-enclosed) expression of type int (*)[1]. In other words, it requires a conversion from a pointer to array with known bound to a pointer to array with unknown bound.

Just like GCC tells you, this type of conversion only became allowed starting in C++20. If you compile your code with a recent version of Clang with -std=c++20, it should compile. See https://godbolt.org/z/4zb5xx658

Body:
Note: this is the follow-up question for this question.

Sample code (t334.cpp):

typedef int T0;
typedef T0  T1[];
typedef T1* T2[];

T1 x1 = { 13 };
T2 x2 = { &x1 };

Invocations:

$ g++ t334.cpp -std=c++11 -pedantic -Wall -Wextra -c
t334.cpp:6:11: warning: conversions to arrays of unknown bound are only available with ‘-std=c++20’ or ‘-std=gnu++20’ [-Wpedantic]
    6 | T2 x2 = { &x1 };
      |           ^~~

$ clang++ t334.cpp -std=c++11 -pedantic -Wall -Wextra -c
t334.cpp:6:11: error: cannot initialize an array element of type 'T1 *' (aka 'T0 (*)[]') with an rvalue of type 'T0 (*)[1]'
T2 x2 = { &x1 };
          ^~~

Can someone explain, what is wrong with this C++ code?

Note: the equivalent C code is valid, because int (*)[] and int (*)[1] are compatible. Meaning that in C++ they aren't?

Body:
The first definition is of an array of known bound that is deduced from the initializer. It has the same effect as:

int x1[1] = {13};

That means x1 has type int[1], and &x1 has type int (*)[1].

The second definition is trying to initialize a variable of type int (*)[] from a (brace-enclosed) expression of type int (*)[1]. In other words, it requires a conversion from a pointer to array with known bound to a pointer to array with unknown bound.

Just like GCC tells you, this type of conversion only became allowed starting in C++20. If you compile your code with a recent version of Clang with -std=c++20, it should compile. See https://godbolt.org/z/4zb5xx658


问:
Count and Mark TRUE if Range in a Single Row Contains 3 or More Instances of TRUE
So, I'm wanting to count the number of cells in a row (U5:X5) that contain TRUE, and if the range contains 3 or more instances of TRUE, I want to mark the cell TRUE, showing that yes, there are 3 or more instances of TRUE in the range.

What I have so far is not working...

```<code>=IF(COUNTIF(U5:X5,"TRUE") >= 3,"TRUE","")
</code>```

Here's a Google Sheet that you can edit.

Thanks for your help!

答:
I removed the quotation marks around the TRUEs in your formulas and entered the following in J2:</p>
```<code>=ArrayFormula(IF(A2:A="",,MMult(N(F2:I),{1;1;1;1})>=3))
</code>```

Body:
So, I'm wanting to count the number of cells in a row (U5:X5) that contain TRUE, and if the range contains 3 or more instances of TRUE, I want to mark the cell TRUE, showing that yes, there are 3 or more instances of TRUE in the range.

What I have so far is not working...

=IF(COUNTIF(U5:X5,"TRUE") >= 3,"TRUE","")

Here's a Google Sheet that you can edit.

Thanks for your help!

Body:
I removed the quotation marks around the TRUEs in your formulas and entered the following in J2:

=ArrayFormula(IF(A2:A="",,MMult(N(F2:I),{1;1;1;1})>=3))


问:
Printing using JS and @media print CSS but content pushed down
My content in the print preview window is displaying down about 5 or 6 lines.

Since I've already dealt with height, margin & padding, I'm unsure what's keeping it down.  I can't check with inspect because it's inside a print preview window. I'm just experimenting with a few things so no rush.  I will post an answer if I figure it out.

JS - called from onclick();

```<code>function print1() {
    window.print();
}
</code>```

CSS

```<code>    @media print{
    body *:not(#OFP_here){
        visibility: hidden;
        height:0px;
        margin: 0px;
        padding: 0px;
    }
</code>```

Update: 3 lines are due to a table that gets built by JS, even though I have accounted for the table in @media.

答:
visibility: hidden; will "hide"  those elements in the sense that their contents are hidden. But the space they occupy without that rule will still appear as empty space, which I suppose is what you are referring to.

Use display: none instead, which will actually hide the affected elements and not leave any empty space.

Body:
My content in the print preview window is displaying down about 5 or 6 lines.

Since I've already dealt with height, margin & padding, I'm unsure what's keeping it down.  I can't check with inspect because it's inside a print preview window. I'm just experimenting with a few things so no rush.  I will post an answer if I figure it out.

JS - called from onclick();

function print1() {
    window.print();
}

CSS

    @media print{
    body *:not(#OFP_here){
        visibility: hidden;
        height:0px;
        margin: 0px;
        padding: 0px;
    }

Update: 3 lines are due to a table that gets built by JS, even though I have accounted for the table in @media.


问:
How to display the most frequently occurring letter and the number of matches using streams?
I have a method that creates a list of random English letters and counts how many times each letter appears in the list. How to display only the letter that occurs most often and how many times does this letter occur in this list?</p>
```<code>public class StreamPractice {

    public static void main(String[] args) {
        System.out.println(mostFrequentlyOccurringLetter());
    }

    private static Map<String, Integer> mostFrequentlyOccurringLetter() {
        return new Random().ints(100, 65, 91)
                .mapToObj(i -> String.valueOf((char) i))
                .collect(Collectors.toMap(Function.identity(), value -> 1, Integer::sum));
    }

}
</code>```

答:
The easiest solution is to use groupingBy  and store the count of each letter in a map. Then just stream the entry set and use max to get the entry with the highest number.

```<code>Map<String, Long> occurrences = new Random().ints(100, 65, 91)
    .mapToObj(i -> String.valueOf((char) i))
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting());
Optional<Map.Entry<String, Long>> max = occurrences.entrySet()
    .stream()
    .max(Comparator.comparing(Map.Entry::getValue));
</code>```

Body:
I have a method that creates a list of random English letters and counts how many times each letter appears in the list. How to display only the letter that occurs most often and how many times does this letter occur in this list?

public class StreamPractice {

    public static void main(String[] args) {
        System.out.println(mostFrequentlyOccurringLetter());
    }

    private static Map<String, Integer> mostFrequentlyOccurringLetter() {
        return new Random().ints(100, 65, 91)
                .mapToObj(i -> String.valueOf((char) i))
                .collect(Collectors.toMap(Function.identity(), value -> 1, Integer::sum));
    }

}

Body:
The easiest solution is to use groupingBy  and store the count of each letter in a map. Then just stream the entry set and use max to get the entry with the highest number.

Map<String, Long> occurrences = new Random().ints(100, 65, 91)
    .mapToObj(i -> String.valueOf((char) i))
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting());
Optional<Map.Entry<String, Long>> max = occurrences.entrySet()
    .stream()
    .max(Comparator.comparing(Map.Entry::getValue));


问:
Fast method of getting all the descendants of a parent
With the parent-child relationships data frame as below:

```<code>  parent_id child_id
1         1        2
2         2        3
3         3        4
</code>```

The goal is to achieve the following, i.e. expanded version of previous data frame where all the descendants (children, grandchildren, etc.) are assigned to each parent (and incl. the parent/child itself):

```<code>   parent_id child_id
1          1        1
2          1        2
3          1        3
4          1        4
5          2        2
6          2        3
7          2        4
8          3        3
9          3        4
10         4        4
</code>```

The question I have: What is the fastest possible way (or one of them) of achieving that in R?

I've already tried various methods - from a for loop, SQL recursion to using igraph (as described here). They are all rather slow, and some of them are also prone to crashing when dealing with a larger number of combinations.

Below are examples with sqldf and igraph, benchmarked on a slightly larger data frame than above.

```<code>library(sqldf)
library(purrr)
library(dplyr)
library(igraph)

df <- data.frame(parent_id = 1:1000L)
df$child_id <- df$parent_id + 1L

# SQL recursion

sqlQuery <- 'with recursive
             dfDescendants (parent_id, child_id)
             as
             (select parent_id, child_id from df
             union all
             select d.parent_id, s.child_id from dfDescendants d
             join df s
             on d.child_id = s.parent_id)
             select distinct parent_id, parent_id as child_id from dfDescendants
             union
             select distinct child_id as parent_id, child_id from dfDescendants
             union
             select * from dfDescendants;'

sqldf(sqlQuery)

# igraph with purrr

df_g = graph_from_data_frame(df, directed = TRUE)

map(V(df_g), ~ names(subcomponent(df_g, .x, mode = "out"))) %>%
  map_df(~ data.frame(child_id = .x), .id = "parent_id")
</code>```

Benchmark (excl. query creation in sqldf and conversion to graph in igraph):

```<code>set.seed(23423)

microbenchmark::microbenchmark(
  sqldf = sqldf(sqlQuery),
  tidyigraph = map(V(df_g), ~ names(subcomponent(df_g, .x, mode = "out"))) %>%
    map_df(~ data.frame(child_id = .x), .id = "parent_id"),
  times = 5
)

#    Unit: seconds
#           expr      min       lq     mean   median       uq      max neval
#          sqldf 7.815179 8.002836 8.113392 8.084038 8.315207 8.349701     5
#     tidyigraph 5.784239 5.806539 5.883241 5.889171 5.964906 5.971350     5
</code>```

答:
igraph is of course a good way to answer graph questions (see also Bioconductor's graph + RBGL packages), but I think this has an iterative solution in R.

It seems like a reasonable approach is to perform a depth-first graph traversal (I was expecting a fancier solution). This is actually quite easy to implement efficiently in R. Suppose vectors pid and cid describe the links between parent and child nodes in the graph (as in the data.frame in the question). Represent each node as a positive integer.

```<code>all_nodes <- unique(c(parent_id, child_id)  # all nodes
uid <- match(all_nodes, all_nodes)
pid <- match(parent_id, all_nodes)
cid <- match(child_id, all_nodes)
</code>```

and form an edge list from each node to all its children.

```<code>edge_list <- unname(split(cid, factor(pid, levels = uid)))
edge_lengths <- lengths(edge_list)
</code>```

The child nodes of the current child nodes is edge_list[cid], and the number of level 2 child nodes associated with each original parent node is rep(pid, edge_lengths[cid]). So the path from any node to any other reachable node is traversed by the simple iteration

```<code>while (length(pid)) {
    pid <- rep(pid, edge_lengths[cid])
    cid <- unlist(edge_list[cid])
}
</code>```

@jblood94 points out that the traverse has to keep track of edges already visited. We can implement this efficiently (in time, not space!) by creating a logical vector of visited edges. We use a 'factory' pattern, where we create a function that retains state (the logical vector of nodes visited). The vector is indexed by the unique id (key) of the edge pid * n + cid. We're interested in keys that are not duplicated, and have not been already visited.

```<code>visitor <- function(uid, n_max = 3000) {
    n <- length(uid)
    if (n <= n_max) {
        ## over-allocate, to support `key = pid * n + cid`
        visited <- logical((n + 1L) * n) # FALSE on construction
    } else {
        stop("length(uid) greater than n_max = ", n_max)
    }
    function(pid, cid) {
        key <- pid * n + cid
        to_visit <- !(duplicated(key) | visited[key])
        visited[key[to_visit]] <<- TRUE  # update nodes that we will now visit
        to_visit
    }
}
</code>```

Thus

```<code>> visit = visitor(1:10)
> visit(1:3, 2:4)
[1] TRUE TRUE TRUE
> visit(2:4, 3:5)
[1] FALSE FALSE  TRUE
</code>```

Here is a more complete implementation of the entire solution, with additional book-keeping

```<code>visitor <- function(uid, n_max = 3000) {
    n <- length(uid)
    if (n <= n_max) {
        ## over-allocate, to support `key = pid * n + cid`
        visited <- logical((n + 1L) * n) # FALSE on construction
    } else {
        stop("length(uid) greater than n_max = ", n_max)
    }
    function(pid, cid) {
        key <- pid * n + cid
        to_visit <- !(duplicated(key) | visited[key])
        visited[key[to_visit]] <<- TRUE
        to_visit
    }
}

ancestor_descendant <- function(df) {
    ## encode parent and child to unique integer values
    ids <- unique(c(df$parent_id, df$child_id))
    uid <- match(ids, ids)
    pid <- match(df$parent_id, ids)
    cid <- match(df$child_id, ids)
    n <- length(uid)

    ## edge list of parent-offspring relationships, based on unique
    ## integer values; list is ordered by id, all ids are present, ids
    ## without children have zero-length elements. Use `unname()` so
    ## that edge_list is always indexed by integer
    edge_list <- unname(split(cid, factor(pid, levels = uid), drop = FALSE))
    edge_lengths <- lengths(edge_list)

    visit <- visitor(uid)
    keep <- visit(uid, uid) # all TRUE
    aid = did = list(uid) # results -- all uid's are there own ancestor / descendant
    i = 1L

    while (length(pid)) {
        ## only add new edges
        keep <- visit(pid, cid)
        ## record current generation ancestors and descendants
        pid <- pid[keep]
        cid <- cid[keep]
        i <- i + 1L
        aid[[i]] <- pid
        did[[i]] <- cid

        ## calculate next generation pid and cid.
        pid <- rep(pid, edge_lengths[cid])
        cid <- unlist(edge_list[cid])
    }
    ## decode results to original ids and clean up return value
    df <- data.frame(
        ancestor_id = ids[unlist(aid)],
        descendant_id = ids[unlist(did)]
    )
    df <- df[order(df$ancestor_id, df$descendant_id),]
    rownames(df) <- NULL
    df
}
</code>```

This seems to be correct and performant, at least superficially

```<code>## Original example
df <- data.frame(parent_id = 1:1000L)
df$child_id <- df$parent_id + 1L
df = df[sample(nrow(df)),]
system.time(result <- ancestor_descendant(df))
##  user  system elapsed
## 0.243   0.001   0.245
dim(result)
## [1] 501501      2

## updated example from comments
df <- data.frame(parent_id = 1:1000L)
df$child_id <- df$parent_id + 1L
df <- rbind(df, data.frame(parent_id = 1000L, child_id = 1002L))
system.time(result <- ancestor_descendant(df))
##  user  system elapsed
## 0.195   0.001   0.195
dim(result)
## [1] 502502      2

## problematic case from @jblood94
df <- data.frame(
    parent_id=c(1, 1, 2),
    child_id = c(2, 3, 3)
)
ancestor_descendant(df)
##   ancestor_id descendant_id
## 1           1             1
## 2           1             2
## 3           1             3
## 4           2             2
## 5           2             3
## 6           3             3

## previously failed without filtering re-visited nodes
df <- data.frame(
    parent_id = rep(1:100, each = 2),
    child_id = c(2, rep(3:101, each = 2), 102)
)
system.time(result <- ancestor_descendant(df))
##  user  system elapsed
## 0.005   0.000   0.006
dim(result)
## [1] 5252    2
</code>```

Body:
With the parent-child relationships data frame as below:

  parent_id child_id
1         1        2
2         2        3
3         3        4

The goal is to achieve the following, i.e. expanded version of previous data frame where all the descendants (children, grandchildren, etc.) are assigned to each parent (and incl. the parent/child itself):

   parent_id child_id
1          1        1
2          1        2
3          1        3
4          1        4
5          2        2
6          2        3
7          2        4
8          3        3
9          3        4
10         4        4

The question I have: What is the fastest possible way (or one of them) of achieving that in R?

I've already tried various methods - from a for loop, SQL recursion to using igraph (as described here). They are all rather slow, and some of them are also prone to crashing when dealing with a larger number of combinations.

Below are examples with sqldf and igraph, benchmarked on a slightly larger data frame than above.

library(sqldf)
library(purrr)
library(dplyr)
library(igraph)

df <- data.frame(parent_id = 1:1000L)
df$child_id <- df$parent_id + 1L

# SQL recursion

sqlQuery <- 'with recursive
             dfDescendants (parent_id, child_id)
             as
             (select parent_id, child_id from df
             union all
             select d.parent_id, s.child_id from dfDescendants d
             join df s
             on d.child_id = s.parent_id)
             select distinct parent_id, parent_id as child_id from dfDescendants
             union
             select distinct child_id as parent_id, child_id from dfDescendants
             union
             select * from dfDescendants;'

sqldf(sqlQuery)

# igraph with purrr

df_g = graph_from_data_frame(df, directed = TRUE)

map(V(df_g), ~ names(subcomponent(df_g, .x, mode = "out"))) %>%
  map_df(~ data.frame(child_id = .x), .id = "parent_id")

Benchmark (excl. query creation in sqldf and conversion to graph in igraph):

set.seed(23423)

microbenchmark::microbenchmark(
  sqldf = sqldf(sqlQuery),
  tidyigraph = map(V(df_g), ~ names(subcomponent(df_g, .x, mode = "out"))) %>%
    map_df(~ data.frame(child_id = .x), .id = "parent_id"),
  times = 5
)

#    Unit: seconds
#           expr      min       lq     mean   median       uq      max neval
#          sqldf 7.815179 8.002836 8.113392 8.084038 8.315207 8.349701     5
#     tidyigraph 5.784239 5.806539 5.883241 5.889171 5.964906 5.971350     5

Body:
igraph is of course a good way to answer graph questions (see also Bioconductor's graph + RBGL packages), but I think this has an iterative solution in R.

It seems like a reasonable approach is to perform a depth-first graph traversal (I was expecting a fancier solution). This is actually quite easy to implement efficiently in R. Suppose vectors pid and cid describe the links between parent and child nodes in the graph (as in the data.frame in the question). Represent each node as a positive integer.

all_nodes <- unique(c(parent_id, child_id)  # all nodes
uid <- match(all_nodes, all_nodes)
pid <- match(parent_id, all_nodes)
cid <- match(child_id, all_nodes)

and form an edge list from each node to all its children.

edge_list <- unname(split(cid, factor(pid, levels = uid)))
edge_lengths <- lengths(edge_list)

The child nodes of the current child nodes is edge_list[cid], and the number of level 2 child nodes associated with each original parent node is rep(pid, edge_lengths[cid]). So the path from any node to any other reachable node is traversed by the simple iteration

while (length(pid)) {
    pid <- rep(pid, edge_lengths[cid])
    cid <- unlist(edge_list[cid])
}

@jblood94 points out that the traverse has to keep track of edges already visited. We can implement this efficiently (in time, not space!) by creating a logical vector of visited edges. We use a 'factory' pattern, where we create a function that retains state (the logical vector of nodes visited). The vector is indexed by the unique id (key) of the edge pid * n + cid. We're interested in keys that are not duplicated, and have not been already visited.

visitor <- function(uid, n_max = 3000) {
    n <- length(uid)
    if (n <= n_max) {
        ## over-allocate, to support `key = pid * n + cid`
        visited <- logical((n + 1L) * n) # FALSE on construction
    } else {
        stop("length(uid) greater than n_max = ", n_max)
    }
    function(pid, cid) {
        key <- pid * n + cid
        to_visit <- !(duplicated(key) | visited[key])
        visited[key[to_visit]] <<- TRUE  # update nodes that we will now visit
        to_visit
    }
}

Thus

> visit = visitor(1:10)
> visit(1:3, 2:4)
[1] TRUE TRUE TRUE
> visit(2:4, 3:5)
[1] FALSE FALSE  TRUE

Here is a more complete implementation of the entire solution, with additional book-keeping

visitor <- function(uid, n_max = 3000) {
    n <- length(uid)
    if (n <= n_max) {
        ## over-allocate, to support `key = pid * n + cid`
        visited <- logical((n + 1L) * n) # FALSE on construction
    } else {
        stop("length(uid) greater than n_max = ", n_max)
    }
    function(pid, cid) {
        key <- pid * n + cid
        to_visit <- !(duplicated(key) | visited[key])
        visited[key[to_visit]] <<- TRUE
        to_visit
    }
}

ancestor_descendant <- function(df) {
    ## encode parent and child to unique integer values
    ids <- unique(c(df$parent_id, df$child_id))
    uid <- match(ids, ids)
    pid <- match(df$parent_id, ids)
    cid <- match(df$child_id, ids)
    n <- length(uid)

    ## edge list of parent-offspring relationships, based on unique
    ## integer values; list is ordered by id, all ids are present, ids
    ## without children have zero-length elements. Use `unname()` so
    ## that edge_list is always indexed by integer
    edge_list <- unname(split(cid, factor(pid, levels = uid), drop = FALSE))
    edge_lengths <- lengths(edge_list)

    visit <- visitor(uid)
    keep <- visit(uid, uid) # all TRUE
    aid = did = list(uid) # results -- all uid's are there own ancestor / descendant
    i = 1L

    while (length(pid)) {
        ## only add new edges
        keep <- visit(pid, cid)
        ## record current generation ancestors and descendants
        pid <- pid[keep]
        cid <- cid[keep]
        i <- i + 1L
        aid[[i]] <- pid
        did[[i]] <- cid

        ## calculate next generation pid and cid.
        pid <- rep(pid, edge_lengths[cid])
        cid <- unlist(edge_list[cid])
    }
    ## decode results to original ids and clean up return value
    df <- data.frame(
        ancestor_id = ids[unlist(aid)],
        descendant_id = ids[unlist(did)]
    )
    df <- df[order(df$ancestor_id, df$descendant_id),]
    rownames(df) <- NULL
    df
}

This seems to be correct and performant, at least superficially

## Original example
df <- data.frame(parent_id = 1:1000L)
df$child_id <- df$parent_id + 1L
df = df[sample(nrow(df)),]
system.time(result <- ancestor_descendant(df))
##  user  system elapsed
## 0.243   0.001   0.245
dim(result)
## [1] 501501      2

## updated example from comments
df <- data.frame(parent_id = 1:1000L)
df$child_id <- df$parent_id + 1L
df <- rbind(df, data.frame(parent_id = 1000L, child_id = 1002L))
system.time(result <- ancestor_descendant(df))
##  user  system elapsed
## 0.195   0.001   0.195
dim(result)
## [1] 502502      2

## problematic case from @jblood94
df <- data.frame(
    parent_id=c(1, 1, 2),
    child_id = c(2, 3, 3)
)
ancestor_descendant(df)
##   ancestor_id descendant_id
## 1           1             1
## 2           1             2
## 3           1             3
## 4           2             2
## 5           2             3
## 6           3             3

## previously failed without filtering re-visited nodes
df <- data.frame(
    parent_id = rep(1:100, each = 2),
    child_id = c(2, rep(3:101, each = 2), 102)
)
system.time(result <- ancestor_descendant(df))
##  user  system elapsed
## 0.005   0.000   0.006
dim(result)
## [1] 5252    2