问:
Track total execution time of multi-thread java program
I have a java program that checks if numbers are prime. I tried to make it parallel by checking different numbers using separate threads.

Here is my sequential program, primeSeq.java:

import java.io.*;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

class primeSeq {

    static boolean isPrime(long n) {
        // Check base cases:
        // n < 2, n is 2 or 3, n is divisible by 2 or 3
        if(n < 2) return false;
        if(n == 2 || n == 3) return true;
        if(n%2 == 0 || n%3 == 0) return false;

        // Check if divisible by all numbers 6k +-1 up to sqrt(n)
        long sqrtN = (long)Math.sqrt(n)+1;
        for(long i = 6L; i <= sqrtN; i += 6) {
            if(n%(i-1) == 0 || n%(i+1) == 0) return false;
        }
        return true;
    }

    public static void main(String args[]) throws ParseException
    {
        if (args.length == 0){
            System.out.println("No args provided.");
        }
        else
        {
            long startTime = System.nanoTime();

            for(int i=0;i< args.length;i++)
            {
                long single_startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
                boolean isPrime = isPrime(Long.parseLong(args[i]));
                long single_endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
                System.out.println(args[i] + ": " + isPrime + "\tStart time: " + single_startTime + "\tEnd time: " + single_endTime + "\tElapsed time: " + (single_endTime - single_startTime));

            }

            long endTime = System.nanoTime();
            System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");
        }
    }
}
```

<p>And here is my attempt at parallelizing it, primePar.java:</p>

<pre class="lang-java prettyprint-override"><code>import java.io.*;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

class MyThread extends Thread
{
    boolean isPrime(long n) {
        // Check base cases:
        // n < 2, n is 2 or 3, n is divisible by 2 or 3
        if(n < 2) return false;
        if(n == 2 || n == 3) return true;
        if(n%2 == 0 || n%3 == 0) return false;

        // Check if divisible by all numbers 6k +-1 up to sqrt(n)
        long sqrtN = (long)Math.sqrt(n)+1;
        for(long i = 6L; i <= sqrtN; i += 6) {
            if(n%(i-1) == 0 || n%(i+1) == 0) return false;
        }
        return true;
    }

    String threadName;
    public MyThread(String threadName)
    {
        super(threadName);
        this.threadName = threadName;
    }

    @Override
    public void run()
    {
        long startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        boolean isPrime = isPrime(Long.parseLong(threadName));
        long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        System.out.println(threadName + ": " + isPrime + "\tStart time: " + startTime + "\tEnd time: " + endTime + "\tElapsed time: " + (endTime - startTime));
    }
}

class primePar {
    public static void main(String args[]) throws ParseException
    {
        if (args.length == 0){
            System.out.println("No args provided.");
        }
        else
        {
            long startTime = System.nanoTime();

            for(int i=0;i< args.length;i++)
            {

                Thread newThread = new MyThread(args[i]);
                newThread.start();
            }

            long endTime = System.nanoTime();
            System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");
        }
    }
}
</code>```

Here is the output of these:

PrimeSeq:

```<code>$ java primeSeq 1000000000000037 1000000000000091 1000000000000159 1000000000000187
1000000000000037: true  Start time: 143773080   End time: 143773182 Elapsed time: 102
1000000000000091: true  Start time: 143773183   End time: 143773284 Elapsed time: 101
1000000000000159: true  Start time: 143773284   End time: 143773400 Elapsed time: 116
1000000000000187: true  Start time: 143773400   End time: 143773510 Elapsed time: 110
Total time: 430 milliseconds
</code>```

PrimePar:

```<code>$ java primePar 1000000000000037 1000000000000091 1000000000000159 1000000000000187
Total time: 0 milliseconds
1000000000000091: true  Start time: 144449191   End time: 144449354 Elapsed time: 163
1000000000000159: true  Start time: 144449191   End time: 144449355 Elapsed time: 164
1000000000000187: true  Start time: 144449191   End time: 144449357 Elapsed time: 166
1000000000000037: true  Start time: 144449191   End time: 144449370 Elapsed time: 179
</code>```

It seems that my parallel program is performing correctly since all the threads start at the same time. However, the total execution time is not what I wanted (it says 0 milliseconds). How can I change it so that it tracks the total execution time it takes for all the threads to finish (For the above output, it would be 179 milliseconds)?

答:
If you want the execution time of the overall program, your main thread has to wait for the other threads to finish before calculating that. It is 0 milliseconds because after the threads are created and started the main thread instantly goes to the final print while your threads are still running in the background.

In this case you need to collect the threads you have and then call join() on them. This method tells the thread from where the call happens - in this case the main thread - to wait for the thread, that you called the method on, to terminate before continuing. By doing this you will be sure that all the threads finished calculation before the main thread continues to the calculation of the overall execution time.

Something like this should work:

long startTime = System.nanoTime();

List<Thread> threads = new ArrayList<>();

for(int i=0;i< args.length;i++)
{

    Thread newThread = new MyThread(args[i]);
    newThread.start();
    threads.add(newThread);
}

threads.forEach(t -> {
    try {
        t.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});

long endTime = System.nanoTime();
System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");
```

Have a look here for more information.

Body:
I have a java program that checks if numbers are prime. I tried to make it parallel by checking different numbers using separate threads.

Here is my sequential program, primeSeq.java:

import java.io.*;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

class primeSeq {

    static boolean isPrime(long n) {
        // Check base cases:
        // n < 2, n is 2 or 3, n is divisible by 2 or 3
        if(n < 2) return false;
        if(n == 2 || n == 3) return true;
        if(n%2 == 0 || n%3 == 0) return false;

        // Check if divisible by all numbers 6k +-1 up to sqrt(n)
        long sqrtN = (long)Math.sqrt(n)+1;
        for(long i = 6L; i <= sqrtN; i += 6) {
            if(n%(i-1) == 0 || n%(i+1) == 0) return false;
        }
        return true;
    }

    public static void main(String args[]) throws ParseException
    {
        if (args.length == 0){
            System.out.println("No args provided.");
        }
        else
        {
            long startTime = System.nanoTime();

            for(int i=0;i< args.length;i++)
            {
                long single_startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
                boolean isPrime = isPrime(Long.parseLong(args[i]));
                long single_endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
                System.out.println(args[i] + ": " + isPrime + "\tStart time: " + single_startTime + "\tEnd time: " + single_endTime + "\tElapsed time: " + (single_endTime - single_startTime));

            }

            long endTime = System.nanoTime();
            System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");
        }
    }
}

And here is my attempt at parallelizing it, primePar.java:

import java.io.*;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

class MyThread extends Thread
{
    boolean isPrime(long n) {
        // Check base cases:
        // n < 2, n is 2 or 3, n is divisible by 2 or 3
        if(n < 2) return false;
        if(n == 2 || n == 3) return true;
        if(n%2 == 0 || n%3 == 0) return false;

        // Check if divisible by all numbers 6k +-1 up to sqrt(n)
        long sqrtN = (long)Math.sqrt(n)+1;
        for(long i = 6L; i <= sqrtN; i += 6) {
            if(n%(i-1) == 0 || n%(i+1) == 0) return false;
        }
        return true;
    }

    String threadName;
    public MyThread(String threadName)
    {
        super(threadName);
        this.threadName = threadName;
    }

    @Override
    public void run()
    {
        long startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        boolean isPrime = isPrime(Long.parseLong(threadName));
        long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        System.out.println(threadName + ": " + isPrime + "\tStart time: " + startTime + "\tEnd time: " + endTime + "\tElapsed time: " + (endTime - startTime));
    }
}

class primePar {
    public static void main(String args[]) throws ParseException
    {
        if (args.length == 0){
            System.out.println("No args provided.");
        }
        else
        {
            long startTime = System.nanoTime();

            for(int i=0;i< args.length;i++)
            {

                Thread newThread = new MyThread(args[i]);
                newThread.start();
            }

            long endTime = System.nanoTime();
            System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");
        }
    }
}

Here is the output of these:

PrimeSeq:

$ java primeSeq 1000000000000037 1000000000000091 1000000000000159 1000000000000187
1000000000000037: true  Start time: 143773080   End time: 143773182 Elapsed time: 102
1000000000000091: true  Start time: 143773183   End time: 143773284 Elapsed time: 101
1000000000000159: true  Start time: 143773284   End time: 143773400 Elapsed time: 116
1000000000000187: true  Start time: 143773400   End time: 143773510 Elapsed time: 110
Total time: 430 milliseconds

PrimePar:

$ java primePar 1000000000000037 1000000000000091 1000000000000159 1000000000000187
Total time: 0 milliseconds
1000000000000091: true  Start time: 144449191   End time: 144449354 Elapsed time: 163
1000000000000159: true  Start time: 144449191   End time: 144449355 Elapsed time: 164
1000000000000187: true  Start time: 144449191   End time: 144449357 Elapsed time: 166
1000000000000037: true  Start time: 144449191   End time: 144449370 Elapsed time: 179

It seems that my parallel program is performing correctly since all the threads start at the same time. However, the total execution time is not what I wanted (it says 0 milliseconds). How can I change it so that it tracks the total execution time it takes for all the threads to finish (For the above output, it would be 179 milliseconds)?

Body:
If you want the execution time of the overall program, your main thread has to wait for the other threads to finish before calculating that. It is 0 milliseconds because after the threads are created and started the main thread instantly goes to the final print while your threads are still running in the background.

In this case you need to collect the threads you have and then call join() on them. This method tells the thread from where the call happens - in this case the main thread - to wait for the thread, that you called the method on, to terminate before continuing. By doing this you will be sure that all the threads finished calculation before the main thread continues to the calculation of the overall execution time.

Something like this should work:

long startTime = System.nanoTime();

List<Thread> threads = new ArrayList<>();

for(int i=0;i< args.length;i++)
{

    Thread newThread = new MyThread(args[i]);
    newThread.start();
    threads.add(newThread);
}

threads.forEach(t -> {
    try {
        t.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});

long endTime = System.nanoTime();
System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");

Have a look here for more information.


来源: stackexchange

问:
Roo hidden field in Jspx
I want to have a hidden field in a jspx file.

What I would like to do is automatically save the name of the authentificated user in the database. Here is how I do it :

Modify my bean with  :

```<code> public void Got.setUserkt(String userkt) {
        final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
        this.userkt = currentUser;
    }
</code>```

Looking around I found out that i had to use render="false" in my create.jspx page but when render is set to false, no data from my input field is saved in my database.

What am I doing wrong ?

答:
I will resume what I did, for my fellow rookies.

First step : Cut my method from my roo controler (EntityController_Roo_Controller.aj)

```<code>  @RequestMapping(method = RequestMethod.POST)

    public String create(@Valid Got got, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {

        if (bindingResult.hasErrors()) {

            uiModel.addAttribute("got", got);

            addDateTimeFormatPatterns(uiModel);

            return "gots/create";

        }

        uiModel.asMap().clear();

        got.persist();

        return "redirect:/gots/" + encodeUrlPathSegment(got.getId().toString(), httpServletRequest);

    }
</code>```

Second Step : Paste the methode into the java contoller (EntityController.java)

Third Step : Edit the method to get the usernmae and to modifiy my method with it

added Principal principal as a
parameter

update my entity :
got.setUserkt(principal.getName());

@RequestMapping(method = RequestMethod.POST)

```<code>public String create(@Valid Got got, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, Principal principal) {

    if (bindingResult.hasErrors()) {

        uiModel.addAttribute("got", got);

        addDateTimeFormatPatterns(uiModel);

        return "gots/create";

    }

    uiModel.asMap().clear();

    got.setUserkt(principal.getName());

    got.persist();

    return "redirect:/gots/" + encodeUrlPathSegment(got.getId().toString(), httpServletRequest);

}
</code>```

Thanks again !

ContentLicense: CC BY-SA 3.0

Title: Roo hidden field in Jspx

Body:
I want to have a hidden field in a jspx file.

What I would like to do is automatically save the name of the authentificated user in the database. Here is how I do it :

Modify my bean with  :

 public void Got.setUserkt(String userkt) {
        final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
        this.userkt = currentUser;
    }

Looking around I found out that i had to use render="false" in my create.jspx page but when render is set to false, no data from my input field is saved in my database.

What am I doing wrong ?

Body:
I will resume what I did, for my fellow rookies.

First step : Cut my method from my roo controler (EntityController_Roo_Controller.aj)

  @RequestMapping(method = RequestMethod.POST)

    public String create(@Valid Got got, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {

        if (bindingResult.hasErrors()) {

            uiModel.addAttribute("got", got);

            addDateTimeFormatPatterns(uiModel);

            return "gots/create";

        }

        uiModel.asMap().clear();

        got.persist();

        return "redirect:/gots/" + encodeUrlPathSegment(got.getId().toString(), httpServletRequest);

    }

Second Step : Paste the methode into the java contoller (EntityController.java)

Third Step : Edit the method to get the usernmae and to modifiy my method with it

added Principal principal as a
parameter

update my entity :
got.setUserkt(principal.getName());

@RequestMapping(method = RequestMethod.POST)

public String create(@Valid Got got, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, Principal principal) {

    if (bindingResult.hasErrors()) {

        uiModel.addAttribute("got", got);

        addDateTimeFormatPatterns(uiModel);

        return "gots/create";

    }

    uiModel.asMap().clear();

    got.setUserkt(principal.getName());

    got.persist();

    return "redirect:/gots/" + encodeUrlPathSegment(got.getId().toString(), httpServletRequest);

}

Thanks again !


问:
BlocProvider.of() called with a context that does not contain a Bloc - even that it does
First of, I do know how BLoC suppose to work, the idea behind it and I know the difference between BlocProvider() and BlocProvider.value() constructors.

For simplicity, my application has 3 pages with a widget tree like this:

App() => LoginPage() => HomePage() => UserTokensPage()

I want my LoginPage() to have access to UserBloc because i need to log in user etc. To do that, I wrap LoginPage() builder at App() widget like this:

```<code>void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: BlocProvider<UserBloc>(
        create: (context) => UserBloc(UserRepository()),
        child: LoginPage(),
      ),
    );
  }
}
</code>```

That obviously works just fine. Then, if User logs in successfully, he is navigated to HomePage. Now, I need to have access to two different blocs at my HomePage so I use MultiBlocProvider to pass existing UserBloc further and create a brand new one named DataBloc. I do it like this:

```<code>  @override
  Widget build(BuildContext context) {
    return BlocListener<UserBloc, UserState>(
      listener: (context, state) {
        if (state is UserAuthenticated) {
          Navigator.of(context).push(
            MaterialPageRoute<HomePage>(
              builder: (_) => MultiBlocProvider(
                providers: [
                  BlocProvider.value(
                    value: BlocProvider.of<UserBloc>(context),
                  ),
                  BlocProvider<DataBloc>(
                    create: (_) => DataBloc(DataRepository()),
                  ),
                ],
                child: HomePage(),
              ),
            ),
          );
        }
      },
[...]
</code>```

This also works. Problem happens when from HomePage user navigates to UserTokensPage. At UserTokensPage I need my already existing UserBloc that I want to pass with BlocProvider.value() constructor. I do it like this:

```<code>class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        title: Text('My App'),
        actions: <Widget>[
          CustomPopupButton(),
        ],
      ),

[...]

class CustomPopupButton extends StatelessWidget {
  const CustomPopupButton({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      icon: Icon(Icons.more_horiz),
      onSelected: (String choice) {
        switch (choice) {
          case PopupState.myTokens:
            {
              Navigator.of(context).push(
                MaterialPageRoute<UserTokensPage>(
                  builder: (_) => BlocProvider.value(
                    value: BlocProvider.of<UserBloc>(context),
                    child: UserTokensPage(),
                  ),
                ),
              );
            }
            break;
          case PopupState.signOut:
            {
              BlocProvider.of<UserBloc>(context).add(SignOut());
              Navigator.of(context).pop();
            }
        }
      },
[...]
</code>```

When I press button to navigate to MyTokensPage i get error with message:

```<code>════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building Builder(dirty):
        BlocProvider.of() called with a context that does not contain a Bloc of type UserBloc.

        No ancestor could be found starting from the context that was passed to BlocProvider.of<UserBloc>().

        This can happen if:
        1. The context you used comes from a widget above the BlocProvider.
        2. You used MultiBlocProvider and didn't explicity provide the BlocProvider types.

        Good: BlocProvider<UserBloc>(create: (context) => UserBloc())
        Bad: BlocProvider(create: (context) => UserBloc()).

        The context used was: CustomPopupButton
</code>```

What am I doing wrong? Is it because i have extracted PopupMenuButton widget that somehow loses blocs? I don't understand what I can be doing wrong.

答: you don't have to use BlocProvider.value() to navigate to another screen, you can just wrap MaterialApp into BlocProvider as a child of it</p>

ContentLicense: CC BY-SA 4.0

Body:
First of, I do know how BLoC suppose to work, the idea behind it and I know the difference between BlocProvider() and BlocProvider.value() constructors.

For simplicity, my application has 3 pages with a widget tree like this:

App() => LoginPage() => HomePage() => UserTokensPage()

I want my LoginPage() to have access to UserBloc because i need to log in user etc. To do that, I wrap LoginPage() builder at App() widget like this:

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: BlocProvider<UserBloc>(
        create: (context) => UserBloc(UserRepository()),
        child: LoginPage(),
      ),
    );
  }
}

That obviously works just fine. Then, if User logs in successfully, he is navigated to HomePage. Now, I need to have access to two different blocs at my HomePage so I use MultiBlocProvider to pass existing UserBloc further and create a brand new one named DataBloc. I do it like this:

  @override
  Widget build(BuildContext context) {
    return BlocListener<UserBloc, UserState>(
      listener: (context, state) {
        if (state is UserAuthenticated) {
          Navigator.of(context).push(
            MaterialPageRoute<HomePage>(
              builder: (_) => MultiBlocProvider(
                providers: [
                  BlocProvider.value(
                    value: BlocProvider.of<UserBloc>(context),
                  ),
                  BlocProvider<DataBloc>(
                    create: (_) => DataBloc(DataRepository()),
                  ),
                ],
                child: HomePage(),
              ),
            ),
          );
        }
      },
[...]

This also works. Problem happens when from HomePage user navigates to UserTokensPage. At UserTokensPage I need my already existing UserBloc that I want to pass with BlocProvider.value() constructor. I do it like this:

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        title: Text('My App'),
        actions: <Widget>[
          CustomPopupButton(),
        ],
      ),

[...]

class CustomPopupButton extends StatelessWidget {
  const CustomPopupButton({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      icon: Icon(Icons.more_horiz),
      onSelected: (String choice) {
        switch (choice) {
          case PopupState.myTokens:
            {
              Navigator.of(context).push(
                MaterialPageRoute<UserTokensPage>(
                  builder: (_) => BlocProvider.value(
                    value: BlocProvider.of<UserBloc>(context),
                    child: UserTokensPage(),
                  ),
                ),
              );
            }
            break;
          case PopupState.signOut:
            {
              BlocProvider.of<UserBloc>(context).add(SignOut());
              Navigator.of(context).pop();
            }
        }
      },
[...]

When I press button to navigate to MyTokensPage i get error with message:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building Builder(dirty):
        BlocProvider.of() called with a context that does not contain a Bloc of type UserBloc.

        No ancestor could be found starting from the context that was passed to BlocProvider.of<UserBloc>().

        This can happen if:
        1. The context you used comes from a widget above the BlocProvider.
        2. You used MultiBlocProvider and didn't explicity provide the BlocProvider types.

        Good: BlocProvider<UserBloc>(create: (context) => UserBloc())
        Bad: BlocProvider(create: (context) => UserBloc()).

        The context used was: CustomPopupButton

What am I doing wrong? Is it because i have extracted PopupMenuButton widget that somehow loses blocs? I don't understand what I can be doing wrong.


问:
Sending one more value via POST PHP
It's my first post so welcome!

I'm struggling with one problem in my project. As you can see at my screenshot, i have few names which are fetched from database, and displayed in main menu. after clicking "modal" button, modal from bootstrap is showed with php form. user can type a 4 digit pin code, next step is to match this pin with database records. But 2 users can have same pin so i need to compare not only pin with database, but name too. i don`t know how to send "name" value with post. Here is my code and screenshot:

index.php:

```<code>  <?php
 $data = $worker->select_workers();
$worker->show_workers($data);
$worker->show_modal();
</code>```

worker.php:

```<code><?php
require_once('db.php');
class Worker extends db {

protected $select_workers;
    public function select_workers(){

                return $this->select_workers = $this->query('SELECT * FROM worker')->fetchAll();
    }

    public function show_workers($data){
        foreach ($data as $users) {
    echo '<p id="p_name">'.$users['name'].'</p><a id="button_modal" href="/?name='.$users['name'].'" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Modal
</a><br>';

}
}
    public function show_modal(){
echo '<!-- Button trigger modal -->

<!-- Modal -->
<form action="test.php" id="submit_ajax" method="post">
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modal_title" name="name"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <input id="hidden_name" type="text" value="" name="name" />
Hasło:<input type="text" name="password"><br>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button  type="submit" class="btn btn-primary">Przerwa/powrót</button>
        </form>
      </div>
    </div>
  </div>
</div>';
    }
</code>```

Main menu of my application

I belive that solution is really simple but like always - i waste too many times for complicated things which are not working. Sorry for my english, it's not my native language :)
Thank you

答: Put value here <input id="hidden_name" type="text" value="<?= $name ?>" name="name" />, but if you fetch data from db, isn't it better to use ids instead of names?

Title: Sending one more value via POST PHP

Body:
It's my first post so welcome!

I'm struggling with one problem in my project. As you can see at my screenshot, i have few names which are fetched from database, and displayed in main menu. after clicking "modal" button, modal from bootstrap is showed with php form. user can type a 4 digit pin code, next step is to match this pin with database records. But 2 users can have same pin so i need to compare not only pin with database, but name too. i don`t know how to send "name" value with post. Here is my code and screenshot:

index.php:

  <?php
 $data = $worker->select_workers();
$worker->show_workers($data);
$worker->show_modal();

worker.php:

<?php
require_once('db.php');
class Worker extends db {

protected $select_workers;
    public function select_workers(){

                return $this->select_workers = $this->query('SELECT * FROM worker')->fetchAll();
    }

    public function show_workers($data){
        foreach ($data as $users) {
    echo '
'.$users['name'].'

  Modal

';

}
}
    public function show_modal(){
echo '

<form action="test.php" id="submit_ajax" method="post">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <input id="hidden_name" type="text" value="" name="name" />
Hasło:<input type="text" name="password">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button  type="submit" class="btn btn-primary">Przerwa/powrót</button>
        </form>

';
    }

Main menu of my application

I belive that solution is really simple but like always - i waste too many times for complicated things which are not working. Sorry for my english, it's not my native language :)
Thank you


问:
Custom property on UIViewController like splitViewController or tabBarController
I have written a custom simple split view controller for purposes not fulfilled by UISplitView.

Now I want its child view controllers to access this custom split view just like we can access the UISplitView or UITabBarController or even UINavigationController directly regardless of complicated hierarchy of controllers.

For example, even if we use UISplitView inside UITabBarController and UINavigationController as one of the view controller of tabBarController, we always get appropriate controllers by using properties splitViewController, tabBarController & navigationController on actual controller classes. [It somehow traverses the hierarchy to get appropriate controller].

How can I create such a property to access my custom split view controller.

答:
You can call the existing method and check the class, here is an example:

SceneSplitViewController.h

```<code>@interface SceneSplitViewController : UISplitViewController

@end

@interface UIViewController (SceneSplitViewController)

@property(strong, nonatomic, readonly) SceneSplitViewController *sceneSplitViewController;

@end
</code>```

SceneSplitViewController.m

```<code>#import "SceneSplitViewController.h"

@implementation SceneSplitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

@end

@implementation UIViewController (SceneSplitViewController)

- (SceneSplitViewController *)sceneSplitViewController{
    UISplitViewController *svc = self.splitViewController;
    if([svc isKindOfClass:SceneSplitViewController.class]){
        return (SceneSplitViewController *)svc;
    }
    return svc.sceneSplitViewController;
}

@end
</code>```

Body:
You can call the existing method and check the class, here is an example:

SceneSplitViewController.h

@interface SceneSplitViewController : UISplitViewController

@end

@interface UIViewController (SceneSplitViewController)

@property(strong, nonatomic, readonly) SceneSplitViewController *sceneSplitViewController;

@end

SceneSplitViewController.m

#import "SceneSplitViewController.h"

@implementation SceneSplitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

@end

@implementation UIViewController (SceneSplitViewController)

- (SceneSplitViewController *)sceneSplitViewController{
    UISplitViewController *svc = self.splitViewController;
    if([svc isKindOfClass:SceneSplitViewController.class]){
        return (SceneSplitViewController *)svc;
    }
    return svc.sceneSplitViewController;
}

@end


问:
What is the difference between "RTCSdpTypeAnswer" and "RTCSdpTypePrAnswer"?
He||o

I am coding using Swift and WebRTC, I do not understand what is the difference between "RTCSdpTypeAnswer" and "RTCSdpTypePrAnswer" (enum RTCSdpType in RTCSessionDescription.h file)

I do not find the answer on internet, can someone help me please ?

(I got WebRTC using the "GoogleWebRTC" pod)

答:
jib's comment:
pranswer is an early-but-not-final answer, mostly for legacy hardware. It has poor web compat. You can safely ignore it.</p>


问:
I can't get past a few do-while loops even though their conditions have not been met
I'm just doing an exercise where I'm supposed to be finding all even numbers between two certain integers. However, each time I enter any numbers I get held up on one of the first two do-while loops. I assume I'm making a simple error. Does anybody see what I'm doing wrong?
Thank you!

The input should be x and y, the output should be b. x must be smaller than y, and they both must be between 1-99 (I'll fix that, it should be 0-100.)

```<code>#include <iostream>

int main()
{
    int x, y, b;

    std::cout << "This program will show all even numbers between a certain range.\n\nEnter two integers >0 and <100. The first integer must be smaller than the second integer.\n ";
    std::cin >> x >> y;

    do
    {
        std::cout << "The first integer must be smaller than the second integer. Please enter two integers.\n ";
        std::cin >> x >> y;

    } while (x > y);

    do
    {
        std::cout << "The first smaller integer must be greater than 0, the second larger integer must be less than 100.\n ";
        std::cin >> x >> y;

    } while (((x < 0 || y > 100 || x > y)));

    b = x;

    if ((b % 2) == 0)
    {
        do
        {
            std::cout << b;
            b++;
        } while (b < y);
    }
}
</code>```

答:
This is a fairly typical "loop and a half" situation.

That is, you need to prompt the user for input, read the input, then if the input was bad, tell them it was bad, and repeat.

To be honest, most ways of handling situations like this end up at least a little bit clumsy. That said, one possibility that avoids most clumsiness is like this:

```<code>bool CheckInput(int a, int b) {
     if (b < a) {
         std::cout << "The first item must be less than the second.\n");
         return false;
     }

     // add range checks here....

     return true;
}

int main() {
    int x, y;

    do {
        std::cout << "Please enter two integers (in sorted order): ";
        std::cin >> x >> y;
    } while (!CheckInput(x, y));
}
</code>```

Body:
I'm just doing an exercise where I'm supposed to be finding all even numbers between two certain integers. However, each time I enter any numbers I get held up on one of the first two do-while loops. I assume I'm making a simple error. Does anybody see what I'm doing wrong?
Thank you!

The input should be x and y, the output should be b. x must be smaller than y, and they both must be between 1-99 (I'll fix that, it should be 0-100.)

#include <iostream>

int main()
{
    int x, y, b;

    std::cout << "This program will show all even numbers between a certain range.\n\nEnter two integers >0 and <100. The first integer must be smaller than the second integer.\n ";
    std::cin >> x >> y;

    do
    {
        std::cout << "The first integer must be smaller than the second integer. Please enter two integers.\n ";
        std::cin >> x >> y;

    } while (x > y);

    do
    {
        std::cout << "The first smaller integer must be greater than 0, the second larger integer must be less than 100.\n ";
        std::cin >> x >> y;

    } while (((x < 0 || y > 100 || x > y)));

    b = x;

    if ((b % 2) == 0)
    {
        do
        {
            std::cout << b;
            b++;
        } while (b < y);
    }
}

Body:
This is a fairly typical "loop and a half" situation.

That is, you need to prompt the user for input, read the input, then if the input was bad, tell them it was bad, and repeat.

To be honest, most ways of handling situations like this end up at least a little bit clumsy. That said, one possibility that avoids most clumsiness is like this:

bool CheckInput(int a, int b) {
     if (b < a) {
         std::cout << "The first item must be less than the second.\n");
         return false;
     }

     // add range checks here....

     return true;
}

int main() {
    int x, y;

    do {
        std::cout << "Please enter two integers (in sorted order): ";
        std::cin >> x >> y;
    } while (!CheckInput(x, y));
}


问:
Link to a course on Data Structure
I want to study data structure with python for my upcoming test in 2 days.

I have studied data structure like stack,queue,linked-list,trees,graphs in isolation without any language.
Also, I have learned python very well.

But, I have an exam on  Implementation of data structure with python.

I searched on youtube hoping to get a 6-8 hour freeCodeCamp video but I didn't get.
Neither was there any course from any other channel.

So, please if you know of any course please provide the link for it.

Any please give only the link and no review or description whatsoever.

I don't want the answer to be a chit-chat which would destroy the reputation of stack-overflow.

I would love if the course is 6-8 hours in length and its level be intermediate to advance.
Even if your course doesn't fit in upper mentioned criteria, please do mention the course.
It might prove helpful.

Course from any site will do. Only, condition is it should be free and good content.

答:
Here is what you want. However i dont know if this a good use of stackoverflow.
https://www.udemy.com/course/python-data-structures-a-to-z/</p>

Title: Link to a course on Data Structure


问:
How to assert an actual value against 2 or more expected values?
I'm testing a method to see if it returns the correct string. This string is made up of a lot of lines whose order might change, thus usually giving 2 possible combinations. That order is not important for my application.

However, because the order of the lines might change, writing just an Assert statement will not work, since sometimes it will pass the test, and sometimes it will fail the test.

So, is it possible to write a test that will assert an actual string value against 2 or more expected string values and see if it is equal to any of them?

答:
Consider writing a custom hamcrest matcher returned by a method, in this case containsOneOf, i.e.:

```<code>assertThat(myString, containsOneOf("value1", "value2"));
</code>```

In keeping with the "xUnit patterns" you should avoid conditional logic in your matcher, a loop with a break statement should suffice.

Have a look at Hamcrest and xUnit Patterns for more information.

Body:
Consider writing a custom hamcrest matcher returned by a method, in this case containsOneOf, i.e.:

assertThat(myString, containsOneOf("value1", "value2"));

In keeping with the "xUnit patterns" you should avoid conditional logic in your matcher, a loop with a break statement should suffice.

Have a look at Hamcrest and xUnit Patterns for more information.


问:
Cannot decide about condition in while loop
I am making a program about inputting 'n' number of integers from the user and calculating the even and odd sums respectively. However, I am being confused about the condition I should put in while loop. Other than that the sums of even and odd numbers are being calculated perfectly.</p>

```<code>#include <stdio.h>
int main()
{
    int i, n, number, sum = 0, summ = 0, count;
    printf("Enter Number of Integers:");
    scanf("%d", &n);
    while (i <= n)
    {
        i = number;
        printf("Enter Number:");
        scanf("%d", &number);
        i++;
        if (number % 2 == 0)
        {
            sum = sum + number;
            number++;
        }
        else if (number % 2 != 0)
        {
            summ = summ + number;
            number++;
        }
    }
    printf("Sum of Even Numbers: %d", sum);
    printf("\nSum of Odd Numbers: %d", summ);
}
</code>```

答:
just decrease n on each loop.
Simplify your odd test</p>

```<code>#include<stdio.h>
int main()
{
    int n,sum=0,summ=0;
    printf("Enter Number of Integers:");
    scanf("%d",&n);
    while(n-- > 0)
    {
        int number;
        printf("Enter Number:");
        scanf("%d", &number);
        if(number % 2) {
            summ += number;
        }
        else {
            sum += number;
        }
    }
    printf("Sum of Even Numbers: %d\n",sum);
    printf("Sum of Odd Numbers: %d\n",summ);
}
</code>```

Body:
I am making a program about inputting 'n' number of integers from the user and calculating the even and odd sums respectively. However, I am being confused about the condition I should put in while loop. Other than that the sums of even and odd numbers are being calculated perfectly.

#include <stdio.h>
int main()
{
    int i, n, number, sum = 0, summ = 0, count;
    printf("Enter Number of Integers:");
    scanf("%d", &n);
    while (i <= n)
    {
        i = number;
        printf("Enter Number:");
        scanf("%d", &number);
        i++;
        if (number % 2 == 0)
        {
            sum = sum + number;
            number++;
        }
        else if (number % 2 != 0)
        {
            summ = summ + number;
            number++;
        }
    }
    printf("Sum of Even Numbers: %d", sum);
    printf("\nSum of Odd Numbers: %d", summ);
}

Body:
just decrease n on each loop.
Simplify your odd test

#include<stdio.h>
int main()
{
    int n,sum=0,summ=0;
    printf("Enter Number of Integers:");
    scanf("%d",&n);
    while(n-- > 0)
    {
        int number;
        printf("Enter Number:");
        scanf("%d", &number);
        if(number % 2) {
            summ += number;
        }
        else {
            sum += number;
        }
    }
    printf("Sum of Even Numbers: %d\n",sum);
    printf("Sum of Odd Numbers: %d\n",summ);
}


问:
Too many open files: how many are open, what they are, and how many can the JVM open
I'm getting this exception in Java:

```<code>java.io.FileNotFoundException: (Too many open files)
</code>```

I'm looking for the ways to eliminate this problem.

This error obviously indicates that JVM has allocated too many handles and underlying OS won't let it have more. Either I've got leak somewhere with improperly closed connections/streams.

This process runs for days non-stop and eventually throws the exception. It repeatedly happens after 12-14 days of up-time.

How do you fight this? Is there a way to get a list of allocated handles in JVM or track when it hits certain amount? I'd love to have them printed and see how it grows and when. I can't use a profiler because it's a production system and have difficulties to reproduce it in development. Any suggestion?

I am monitoring free heap size and raising an "alarm" when it approaches 1% of the total specified in -Xmx. I also know that if my thread count hits above 500, then something definitely goes out of hand. Now, is there a way to know that my JVM allocates too many handles from OS and doesn't give them back, e.g. sockets, opened files, etc. If I'd knew that, I'd know where to look and when.

答:
If you are on MacOS</p>

```<code>sudo launchctl limit maxfiles <hard> <soft>
sudo launchctl limit maxfiles 1024 200000
</code>```

Body:
I'm getting this exception in Java:

java.io.FileNotFoundException: (Too many open files)

I'm looking for the ways to eliminate this problem.

This error obviously indicates that JVM has allocated too many handles and underlying OS won't let it have more. Either I've got leak somewhere with improperly closed connections/streams.

This process runs for days non-stop and eventually throws the exception. It repeatedly happens after 12-14 days of up-time.

How do you fight this? Is there a way to get a list of allocated handles in JVM or track when it hits certain amount? I'd love to have them printed and see how it grows and when. I can't use a profiler because it's a production system and have difficulties to reproduce it in development. Any suggestion?

I am monitoring free heap size and raising an "alarm" when it approaches 1% of the total specified in -Xmx. I also know that if my thread count hits above 500, then something definitely goes out of hand. Now, is there a way to know that my JVM allocates too many handles from OS and doesn't give them back, e.g. sockets, opened files, etc. If I'd knew that, I'd know where to look and when.

Body:
If you are on MacOS

sudo launchctl limit maxfiles <hard> <soft>
sudo launchctl limit maxfiles 1024 200000


问:
Rank and count elements of list of lists in django
I have a Genre and a User models. Each Genre has an id and a name, and there is a many-to-many relationship, so that each User likes 0 or more Genres.

Is there an efficient query for obtaining how many likes has each Genre, across all users, in descendant order?

My current approach works, but it is extremely inefficient since it has to read all the likes of all the users for each genre:

```<code>In [1]: genres = list(Genre.objects.values('name', 'id'))

In[2]: genres
Out[2]:
[{'id': 10, 'name': 'Rock'},
 {'id': 11, 'name': 'Pop'},
 {'id': 12, 'name': 'Hip hop'},
 {'id': 13, 'name': 'Electronic'},
 {'id': 14, 'name': 'Classical'}]

In [3]: likes_by_users = []

In [4]: users = list(User.objects.all())

In [5]: for u in users:
...:     current_user_likes = []
...:     likes_by_users.append(current_user_likes)
...:     for lg in u.liked_genres.all():
...:         current_user_likes.append(lg.pk)

In [6]: likes_by_users
Out[6]:
[[14],
 [11, 12],
 [11, 10, 13, 12],
 [],
 [13, 12, 10, 1
 [10, 11]]

In [7]: counts = {}

In [8]: for g in genres:
    ...:     counts[g['id']] = {
    ...:         'name' : g['name'],
    ...:         'likes': 0
    ...:     }
    ...:     for l in likes_by_users:
    ...:         for gid in l:
    ...:             if gid == g['id']:
    ...:                 counts[gid]['likes'] += 1

In [9]: ranking = sorted(list(counts.values()), key=lambda x : x['likes'], reverse=True)
</code>```

And this is exactly the output that I need:

```<code>In [9]: ranking
Out[9]:
[{'likes': 4, 'name': 'Pop'},
 {'likes': 3, 'name': 'Rock'},
 {'likes': 3, 'name': 'Hip hop'},
 {'likes': 2, 'name': 'Electronic'},
 {'likes': 1, 'name': 'Classical'}]
</code>```

Is there a query or another method for obtaining in an efficient way the required ranking?

答:
ManyToMany fields in Django are backed by actual models (and thus tables).

You can get at the backing model via .through:

```<code>GenreLikes = User.liked_genres.through
</code>```

For a simple many-to-many relation, the model will have two fields/columns, user and genre in in your case, one instance/row per user-like pair.

Thus, you should be able to get your ranking with just

```<code>GenreLikes.objects.values('genre').annotate(likes=Count('user')).order_by('-likes')
</code>```

or similar.

Body:
I have a Genre and a User models. Each Genre has an id and a name, and there is a many-to-many relationship, so that each User likes 0 or more Genres.

Is there an efficient query for obtaining how many likes has each Genre, across all users, in descendant order?

My current approach works, but it is extremely inefficient since it has to read all the likes of all the users for each genre:

In [1]: genres = list(Genre.objects.values('name', 'id'))

In[2]: genres
Out[2]:
[{'id': 10, 'name': 'Rock'},
 {'id': 11, 'name': 'Pop'},
 {'id': 12, 'name': 'Hip hop'},
 {'id': 13, 'name': 'Electronic'},
 {'id': 14, 'name': 'Classical'}]

In [3]: likes_by_users = []

In [4]: users = list(User.objects.all())

In [5]: for u in users:
...:     current_user_likes = []
...:     likes_by_users.append(current_user_likes)
...:     for lg in u.liked_genres.all():
...:         current_user_likes.append(lg.pk)

In [6]: likes_by_users
Out[6]:
[[14],
 [11, 12],
 [11, 10, 13, 12],
 [],
 [13, 12, 10, 1
 [10, 11]]

In [7]: counts = {}

In [8]: for g in genres:
    ...:     counts[g['id']] = {
    ...:         'name' : g['name'],
    ...:         'likes': 0
    ...:     }
    ...:     for l in likes_by_users:
    ...:         for gid in l:
    ...:             if gid == g['id']:
    ...:                 counts[gid]['likes'] += 1

In [9]: ranking = sorted(list(counts.values()), key=lambda x : x['likes'], reverse=True)

And this is exactly the output that I need:

In [9]: ranking
Out[9]:
[{'likes': 4, 'name': 'Pop'},
 {'likes': 3, 'name': 'Rock'},
 {'likes': 3, 'name': 'Hip hop'},
 {'likes': 2, 'name': 'Electronic'},
 {'likes': 1, 'name': 'Classical'}]

Is there a query or another method for obtaining in an efficient way the required ranking?

Body:
ManyToMany fields in Django are backed by actual models (and thus tables).

You can get at the backing model via .through:

GenreLikes = User.liked_genres.through

For a simple many-to-many relation, the model will have two fields/columns, user and genre in in your case, one instance/row per user-like pair.

Thus, you should be able to get your ranking with just

GenreLikes.objects.values('genre').annotate(likes=Count('user')).order_by('-likes')

or similar.


问:
Typecasting HashSets in C#
I have two classes where one derives the other. I also have a HashSet field which stores a bunch of Derived classes. The problem is that the Derived class is only used internally and I have a property which needs to return a HashSet of Base classes. I know List has the ConvertAll method, does HashSet have something similar?</p>

```<code>public class Base
{
}

public class MyClass
{
    private class Derived : Base
    {
    }

    private HashSet<Derived> mList;

    public HashSet<Base> GetList { get { /* Convert mList to HashSet<Base> */ } }
}
</code>```

答:
Just declare mList as...

```<code>private HashSet<Base> mList;
</code>```

You can do...

```<code>public HashSet<Base> GetList { get { return new HashSet<Base>(mList); } }
</code>```

Since the mList implements IEnumerable<Base>

Title: Typecasting HashSets in C#

Body:
I have two classes where one derives the other. I also have a HashSet field which stores a bunch of Derived classes. The problem is that the Derived class is only used internally and I have a property which needs to return a HashSet of Base classes. I know List has the ConvertAll method, does HashSet have something similar?

public class Base
{
}

public class MyClass
{
    private class Derived : Base
    {
    }

    private HashSet<Derived> mList;

    public HashSet<Base> GetList { get { /* Convert mList to HashSet<Base> */ } }
}

Body:
Just declare mList as...

private HashSet<Base> mList;

You can do...

public HashSet<Base> GetList { get { return new HashSet<Base>(mList); } }

Since the mList implements IEnumerable<Base>


问:
Mutex implementation within IIS async controller action?
I have written a web service that's an Asp.Net MVC application hosted in IIS.  The data from the web service isn't retrieved from a database but from another server that is accessed via TCP.  We'll call this the Data Server.  There can be multiple Data Servers that the web service connects to.

For the sake of discussion, a user authenticates by specifying a username and password then a "Session" with a Socket is created with the appropriate Data Server.  Assuming everything is good - we keep the Socket alive and pass the user a token that identifies the Session they belong to.

For each Socket I need to prevent traffic from interrupting each other.  I assume that the best way to do that is to run the network traffic on a Socket in a serialized manner.  I have achieved this by using a lock. My code to execute a query on this Data Server follows.  The problem I'm having is that once in a while it appears that I'm getting two queries that collide and one may hang. I see a query come in but it looks like it gets stuck at the lock. Is the lock mechanism safe for IIS async calls?  Is there instrumentation I can put in to make sure this is actually the bug?  I've been looking for a while but I can't find guidance for this particular scenario.

```<code> private async Task<string> query(string request, AbstractPermission context = null, bool bUpdateDateTime = true)
        {
            try
            {
                string reply = "";
                isErrorMsg = false;

                //this lock prevents the keep alive thread from coming in here while we're on the socket
                lock (socketLock)
                {
                    sendDone.Reset();
                    receiveDone.Reset();

                    // Send test data to the remote device.
                    Send(Socket, request);
                    sendDone.WaitOne();

                    // Receive the response from the remote device.
                    Receive(Socket);
                    receiveDone.WaitOne();

                    reply = QueryResponse;

                }  //done reading - let's unlock

                if (bUpdateDateTime)
                {
                    this.LastUsed = DateTime.Now;
                }

                return QueryResponse;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

  private void Send(Socket client, String data)
        {
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            client.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), client);
        }

        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);

                // Signal that all bytes have been sent.
                sendDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private void Receive(Socket client)
        {
            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;
                state.PostInitialRead = false;

                // Begin receiving the data from the remote device.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,
                    new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
                LogError(e);
            }
        }

        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;
                bool PostInitialRead = state.PostInitialRead;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                //
                //
                var thisBatch = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
                var endIdx = thisBatch.IndexOf('\x04');

                if (!PostInitialRead)
                {
                    if (bytesRead == 0)
                        throw new ApplicationException("Timeout waiting for response");

                    if (endIdx != -1)
                    {
                        thisBatch = thisBatch.Substring(0, endIdx);
                    }
                    if (state.buffer[0] != 0)
                    {
                        thisBatch = thisBatch.Substring(1, state.buffer[0]);
                        isErrorMsg = true;
                    }
                    else if (state.buffer[1] != 0)
                    {
                        thisBatch = thisBatch.Substring(2);
                        isErrorMsg = true;
                    }
                    else
                    {
                        thisBatch = thisBatch.Substring(2);
                    }
                    state.sb.Append(thisBatch);
                    state.PostInitialRead = true;
                }
                else
                {
                    state.ms.Write(state.buffer, 0, endIdx!=-1?endIdx:bytesRead);
                }

                if (endIdx != -1)
                {
                    // Got everything
                    state.sb.Append(Encoding.ASCII.GetString(state.ms.ToArray()));
                    QueryResponse = state.sb.ToString();
                    receiveDone.Set();
                    return;
                }
                else
                {
                    // Get the rest of the data.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

</code>```

答:
1: Is hosting something like this within IIS completely absurd?

No. See, dotnetcore and modern development uses SignalR based on WebSockets for stuff like that - and it is hosted in IIS, so it is NOT completely absurd.

2: We can not really answer that. The IO part is trivial - IIS can handle this. But without details on the data server - no idea. YOu generally want to avoid locks as much as possible, but that does not mean totally. MRSV (multiple Reader, Single Writer), copy on write etc. can help minimizing writes, but at the end you will need SOME locking. It is NOT fun debugging this, but that is what people doing that get paid big bucks for.

General applicatiosn avoid all that by offloading the locking to the database at the backend - which spends a LOT of time by many people optimizing locking on data. If you can not do that (remember, we do not know at all what your data server does internally) - welcome to the hard programming.

Your best chance for debugging is trying to find a repro case and then - while it is stuck - attach a debugger. Stuff like that is NOTORIOUSLY hard to debug - but again, this is like the topmost level of regular programming (leaving out certain hardware and very special tasks).

Body:
I have written a web service that's an Asp.Net MVC application hosted in IIS.  The data from the web service isn't retrieved from a database but from another server that is accessed via TCP.  We'll call this the Data Server.  There can be multiple Data Servers that the web service connects to.

For the sake of discussion, a user authenticates by specifying a username and password then a "Session" with a Socket is created with the appropriate Data Server.  Assuming everything is good - we keep the Socket alive and pass the user a token that identifies the Session they belong to.

For each Socket I need to prevent traffic from interrupting each other.  I assume that the best way to do that is to run the network traffic on a Socket in a serialized manner.  I have achieved this by using a lock. My code to execute a query on this Data Server follows.  The problem I'm having is that once in a while it appears that I'm getting two queries that collide and one may hang. I see a query come in but it looks like it gets stuck at the lock. Is the lock mechanism safe for IIS async calls?  Is there instrumentation I can put in to make sure this is actually the bug?  I've been looking for a while but I can't find guidance for this particular scenario.

 private async Task<string> query(string request, AbstractPermission context = null, bool bUpdateDateTime = true)
        {
            try
            {
                string reply = "";
                isErrorMsg = false;

                //this lock prevents the keep alive thread from coming in here while we're on the socket
                lock (socketLock)
                {
                    sendDone.Reset();
                    receiveDone.Reset();

                    // Send test data to the remote device.
                    Send(Socket, request);
                    sendDone.WaitOne();

                    // Receive the response from the remote device.
                    Receive(Socket);
                    receiveDone.WaitOne();

                    reply = QueryResponse;

                }  //done reading - let's unlock

                if (bUpdateDateTime)
                {
                    this.LastUsed = DateTime.Now;
                }

                return QueryResponse;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

  private void Send(Socket client, String data)
        {
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            client.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), client);
        }

        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);

                // Signal that all bytes have been sent.
                sendDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private void Receive(Socket client)
        {
            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;
                state.PostInitialRead = false;

                // Begin receiving the data from the remote device.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,
                    new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
                LogError(e);
            }
        }

        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;
                bool PostInitialRead = state.PostInitialRead;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                //
                //
                var thisBatch = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
                var endIdx = thisBatch.IndexOf('\x04');

                if (!PostInitialRead)
                {
                    if (bytesRead == 0)
                        throw new ApplicationException("Timeout waiting for response");

                    if (endIdx != -1)
                    {
                        thisBatch = thisBatch.Substring(0, endIdx);
                    }
                    if (state.buffer[0] != 0)
                    {
                        thisBatch = thisBatch.Substring(1, state.buffer[0]);
                        isErrorMsg = true;
                    }
                    else if (state.buffer[1] != 0)
                    {
                        thisBatch = thisBatch.Substring(2);
                        isErrorMsg = true;
                    }
                    else
                    {
                        thisBatch = thisBatch.Substring(2);
                    }
                    state.sb.Append(thisBatch);
                    state.PostInitialRead = true;
                }
                else
                {
                    state.ms.Write(state.buffer, 0, endIdx!=-1?endIdx:bytesRead);
                }

                if (endIdx != -1)
                {
                    // Got everything
                    state.sb.Append(Encoding.ASCII.GetString(state.ms.ToArray()));
                    QueryResponse = state.sb.ToString();
                    receiveDone.Set();
                    return;
                }
                else
                {
                    // Get the rest of the data.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }


问:
2D conditional calculation
I have a spreadsheet with list of Products sold over time, with each product having it's class (I'd prefer if classes would be unlimited, but I can also live with predefined classes) and status active/inactive.
I need an arrayformula for H5 to fill the yellow area (only active products). I've tried with combination of MMULT and Arrayformula, but no luck, maybe someone can help me out.</p>

答:
Here's another approach which tries to address the 'infinite columns' issue. The difficulty with the question comes from the 2D nature of the data, so one approach is to normalise or reverse-pivot the data so that there is one row per data item. There are a number of ways of doing this see earlier question, but I have chosen to use the vlookup method:

```<code>=ArrayFormula({sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A)),
vlookup(roundup(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A))/counta(Sheet10!C3:3),0),{sequence(counta(Sheet10!A5:A)),filter(Sheet10!A5:A,Sheet10!A5:A<>"")},2,false),
hlookup(mod(sequence(counta(Sheet10!C2:2)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C2:2)),{sequence(1,counta(Sheet10!C2:2),0);filter(Sheet10!C2:2,Sheet10!C2:2<>"")},2,false),
hlookup(mod(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C3:3)),{sequence(1,counta(Sheet10!C3:3),0);filter(Sheet10!C3:3,Sheet10!C3:3<>"")},2,false),
vlookup(roundup(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A))/counta(Sheet10!C3:3),0),{sequence(counta(Sheet10!A5:A)),Sheet10!C5:index(Sheet10!C5:Z1000,counta(Sheet10!A5:A),counta(Sheet10!C3:3))},mod(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C3:3))+2)
})
</code>```

This gives you:

Once you have got this, it is fairly straightforward to wrap it in a pivot query to give you the required totals:

```<code>=ArrayFormula(query({sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A)),
vlookup(roundup(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A))/counta(Sheet10!C3:3),0),{sequence(counta(Sheet10!A5:A)),filter(Sheet10!A5:A,Sheet10!A5:A<>"")},2,false),
hlookup(mod(sequence(counta(Sheet10!C2:2)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C2:2)),{sequence(1,counta(Sheet10!C2:2),0);filter(Sheet10!C2:2,Sheet10!C2:2<>"")},2,false),
hlookup(mod(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C3:3)),{sequence(1,counta(Sheet10!C3:3),0);filter(Sheet10!C3:3,Sheet10!C3:3<>"")},2,false),
vlookup(roundup(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A))/counta(Sheet10!C3:3),0),{sequence(counta(Sheet10!A5:A)),Sheet10!C5:index(Sheet10!C5:Z1000,counta(Sheet10!A5:A),counta(Sheet10!C3:3))},mod(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C3:3))+2)
},"select Col2,sum(Col5) where Col4=TRUE group by Col2 pivot Col3 label Col2 'Date' format Col2 'dd-mmm-yyyy'"))
</code>```

which gives you

Title: 2D conditional calculation

Body:
Here's another approach which tries to address the 'infinite columns' issue. The difficulty with the question comes from the 2D nature of the data, so one approach is to normalise or reverse-pivot the data so that there is one row per data item. There are a number of ways of doing this see earlier question, but I have chosen to use the vlookup method:

=ArrayFormula({sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A)),
vlookup(roundup(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A))/counta(Sheet10!C3:3),0),{sequence(counta(Sheet10!A5:A)),filter(Sheet10!A5:A,Sheet10!A5:A<>"")},2,false),
hlookup(mod(sequence(counta(Sheet10!C2:2)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C2:2)),{sequence(1,counta(Sheet10!C2:2),0);filter(Sheet10!C2:2,Sheet10!C2:2<>"")},2,false),
hlookup(mod(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C3:3)),{sequence(1,counta(Sheet10!C3:3),0);filter(Sheet10!C3:3,Sheet10!C3:3<>"")},2,false),
vlookup(roundup(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A))/counta(Sheet10!C3:3),0),{sequence(counta(Sheet10!A5:A)),Sheet10!C5:index(Sheet10!C5:Z1000,counta(Sheet10!A5:A),counta(Sheet10!C3:3))},mod(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C3:3))+2)
})

This gives you:

Once you have got this, it is fairly straightforward to wrap it in a pivot query to give you the required totals:

=ArrayFormula(query({sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A)),
vlookup(roundup(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A))/counta(Sheet10!C3:3),0),{sequence(counta(Sheet10!A5:A)),filter(Sheet10!A5:A,Sheet10!A5:A<>"")},2,false),
hlookup(mod(sequence(counta(Sheet10!C2:2)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C2:2)),{sequence(1,counta(Sheet10!C2:2),0);filter(Sheet10!C2:2,Sheet10!C2:2<>"")},2,false),
hlookup(mod(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C3:3)),{sequence(1,counta(Sheet10!C3:3),0);filter(Sheet10!C3:3,Sheet10!C3:3<>"")},2,false),
vlookup(roundup(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A))/counta(Sheet10!C3:3),0),{sequence(counta(Sheet10!A5:A)),Sheet10!C5:index(Sheet10!C5:Z1000,counta(Sheet10!A5:A),counta(Sheet10!C3:3))},mod(sequence(counta(Sheet10!C3:3)*counta(Sheet10!A5:A),1,0),counta(Sheet10!C3:3))+2)
},"select Col2,sum(Col5) where Col4=TRUE group by Col2 pivot Col3 label Col2 'Date' format Col2 'dd-mmm-yyyy'"))

which gives you


问:
How do I use DateTime.TryParse with a Nullable<DateTime>?
I want to use the DateTime.TryParse method to get the datetime value of a string into a Nullable.  But when I try this:

```<code>DateTime? d;
bool success = DateTime.TryParse("some date text", out (DateTime)d);
</code>```

the compiler tells me

'out' argument is not classified as a variable

Not sure what I need to do here.  I've also tried:

```<code>out (DateTime)d.Value
</code>```

and that doesn't work either.  Any ideas?

答:
Here's a single line solution:

DateTime? d = DateTime.TryParse("text", out DateTime parseDate) ? parseDate : (DateTime?)null;
```

OwnerDisplayName: Brian Sullivan

Body:
I want to use the DateTime.TryParse method to get the datetime value of a string into a Nullable.  But when I try this:

DateTime? d;
bool success = DateTime.TryParse("some date text", out (DateTime)d);

the compiler tells me

'out' argument is not classified as a variable

Not sure what I need to do here.  I've also tried:

out (DateTime)d.Value

and that doesn't work either.  Any ideas?


问:
Write csv file using csvhelper library
I am using the following code and getting an exception ,

```<code> Exception thrown: 'CsvHelper.WriterException' in CsvHelper.dll on this line executed:

csv.WriteRecord(item);
</code>```

This is the more of the code:

```<code>using (var memoryStream = new MemoryStream())
{
    using (var writer = new StreamWriter(memoryStream))
    {
        using (var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture))
        {
            foreach (var item in csvData)
            {
                csv.WriteRecord(item); // Exception thrown here
            }
        }
    }

    var arr = memoryStream.ToArray();
    //js.SaveAs("people.csv", arr);  what type object is js? copied from the stackoverflow answer linked here
}
</code>```

This is the csvData code:

```<code>IEnumerable<DateLowHigh> csvData = stocks.candles
    .Select(c => new DateLowHigh
    {
        Time = c.datetime,
        Close = c.close,
        Low = c.low,
        High = c.high
    })
    .ToList();
</code>```

I do get the csvData.

This stackoverflow answer helped me get started.

答:
To answer your question as to what type of object js is in js.SaveAs("people.csv", arr); it is likely Microsoft.JSInterop.IJSRuntime as seen in this Blazer HowTo. The StackOverflow question you referenced was likely using it to get access to JavaScript they could use in C# code. If you just want to save a CSV file using CsvHelper, it could be as simple as:

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(csvData);
}
```

If you are still getting errors, you would need to post the full exception with StackTrace  in order to help further.

Title: Write csv file using csvhelper library

Body:
I am using the following code and getting an exception ,

 Exception thrown: 'CsvHelper.WriterException' in CsvHelper.dll on this line executed:

csv.WriteRecord(item);

This is the more of the code:

using (var memoryStream = new MemoryStream())
{
    using (var writer = new StreamWriter(memoryStream))
    {
        using (var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture))
        {
            foreach (var item in csvData)
            {
                csv.WriteRecord(item); // Exception thrown here
            }
        }
    }

    var arr = memoryStream.ToArray();
    //js.SaveAs("people.csv", arr);  what type object is js? copied from the stackoverflow answer linked here
}

This is the csvData code:

IEnumerable<DateLowHigh> csvData = stocks.candles
    .Select(c => new DateLowHigh
    {
        Time = c.datetime,
        Close = c.close,
        Low = c.low,
        High = c.high
    })
    .ToList();

I do get the csvData.

This stackoverflow answer helped me get started.

Body:
To answer your question as to what type of object js is in js.SaveAs("people.csv", arr); it is likely Microsoft.JSInterop.IJSRuntime as seen in this Blazer HowTo. The StackOverflow question you referenced was likely using it to get access to JavaScript they could use in C# code. If you just want to save a CSV file using CsvHelper, it could be as simple as:

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(csvData);
}

If you are still getting errors, you would need to post the full exception with StackTrace  in order to help further.


问:
Moving files using wildcard in Windows
In Windows cmd, I'm trying to move some .avi files from child directories to parent directories. For example, I have a parent directory that contains 5 child directories. And each child directory has one .avi file in it. Let's say the full path of the parent directory is C:\Grand\Parent.

Parent

Child1

Child2

Child3

Child4

Child5

With C:\Grand as my working directory, I tried this, but it didn't work:

```<code>move "Parent\*\*.avi" "Parent"
</code>```

答:
From the command line use one of these:

This one might complain if files named "*.avi" already exist in "C:\Grand\Parent":

```<code>for /f "usebackq delims=" %f in (`dir /s /b /a-d "C:\Grand\Parent\*.avi"`) do move "%~f" "C:\Grand\Parent"
</code>```

This one doesn't process files already in "C:\Grand\Parent":

```<code>for /f "usebackq delims=" %f in (`dir /b /ad "C:\Grand\Parent\*"`) do move "%~f\*.avi" "C:\Grand\Parent"
</code>```

Title: Moving files using wildcard in Windows

Body:
In Windows cmd, I'm trying to move some .avi files from child directories to parent directories. For example, I have a parent directory that contains 5 child directories. And each child directory has one .avi file in it. Let's say the full path of the parent directory is C:\Grand\Parent.

Parent

Child1

Child2

Child3

Child4

Child5

With C:\Grand as my working directory, I tried this, but it didn't work:

move "Parent\*\*.avi" "Parent"

Body:
From the command line use one of these:

This one might complain if files named "*.avi" already exist in "C:\Grand\Parent":

for /f "usebackq delims=" %f in (`dir /s /b /a-d "C:\Grand\Parent\*.avi"`) do move "%~f" "C:\Grand\Parent"

This one doesn't process files already in "C:\Grand\Parent":

for /f "usebackq delims=" %f in (`dir /b /ad "C:\Grand\Parent\*"`) do move "%~f\*.avi" "C:\Grand\Parent"


问:
Find substring in string from the end
I need to find position of string in substring. Scan has to begin from the end. For example:

```<code>findch(L"asdhuifdsahdfasasd", L"asd");
</code>```

return 16 instead of 1

Here is my function:

```<code>int findchr(LPCWSTR T, LPCWSTR P)
{
    int n = lstrlenW(T);
    int m = lstrlenW(P);

    for (int i = 0; i <= n - m; ++i) {
        int j = 0;
        while (j < m && T[i + j] == P[j]) {
            ++j;
        }
        if (j == m) {
            return i;
        }
    }
    return -1;
}
</code>```

答:
You can try using std::string::rfind which does exactly what you want:

Finds the last substring equal to the given character sequence.

Then you can have something like this:

#include <string>
#include <iostream>

std::string::size_type reverse_find(std::string const& str, std::string const& substr) {
    return str.rfind(substr);
}

int main() {
    auto first = reverse_find("asdhuifdsahdfasasd", "asd");
    if (std::string::npos != first) {
        std::cout << first << std::endl;  // 15
    }

    auto second = reverse_find("asdhuifdsahdfasasd", "z");
    if (std::string::npos != second) {
        std::cout << second << std::endl; // won't be outputted
    }
    return 0;
}
```

Demo

Above reverse_find function returns 15 because indices start at 0.

Title: Find substring in string from the end

Body:
I need to find position of string in substring. Scan has to begin from the end. For example:

findch(L"asdhuifdsahdfasasd", L"asd");

return 16 instead of 1

Here is my function:

int findchr(LPCWSTR T, LPCWSTR P)
{
    int n = lstrlenW(T);
    int m = lstrlenW(P);

    for (int i = 0; i <= n - m; ++i) {
        int j = 0;
        while (j < m && T[i + j] == P[j]) {
            ++j;
        }
        if (j == m) {
            return i;
        }
    }
    return -1;
}

Body:
You can try using std::string::rfind which does exactly what you want:

Finds the last substring equal to the given character sequence.

Then you can have something like this:

#include <string>
#include <iostream>

std::string::size_type reverse_find(std::string const& str, std::string const& substr) {
    return str.rfind(substr);
}

int main() {
    auto first = reverse_find("asdhuifdsahdfasasd", "asd");
    if (std::string::npos != first) {
        std::cout << first << std::endl;  // 15
    }

    auto second = reverse_find("asdhuifdsahdfasasd", "z");
    if (std::string::npos != second) {
        std::cout << second << std::endl; // won't be outputted
    }
    return 0;
}

<a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:2,endLineNumber:19,positionColumn:1,positionLineNumber:1,selectionStartColumn:2,selectionStartLineNumber:19,startColumn:1,startLineNumber:1),source:'%23include+%3Cstring%3E%0A%23include+%3Ciostream%3E%0A%0Astd::string::size_type+reverse_find(std::string+const%26+str,+std::string+const%26+substr)+%7B%0A++++return+str.rfind(substr)%3B%0A%7D%0A%0Aint+main()+%7B%0A++++auto+first+%3D+reverse_find(%22asdhuifdsahdfasasd%22,+%22asd%22)%3B%0A++++if+(std::string::npos+!!%3D+first)+%7B%0A++++++++std::cout+%3C%3C+first+%3C%3C+std::endl%3B%0A++++%7D%0A%0A++++auto+second+%3D+reverse_find(%22asdhuifdsahdfasasd%22,+%22z%22)%3B%0A++++if+(std::string::npos+!!%3D+second)+%7B%0A++++++++std::cout+%3C%3C+second+%3C%3C+std::endl%3B%0A++++%7D%0A++++return+0%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:52.637075718015666,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:g91,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:1,lang:c%2B%2B,libs:!(),options:'-std%3Dc%2B%2B11',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+gcc+9.1+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0')),k:37.5,l:'4',m:50,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:1,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%231+with+x86-64+gcc+9.1',t:'0')),header:(),l:'4',m:50,n:'0',o:'',s:0,t:'0')),k:47.362924281984334,l:'3',n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">Demo

Above reverse_find function returns 15 because indices start at 0.


问:
How do I get the next day's date in JS in YYYY-MM-DD format?
Seems like a simple question, but all the timezone ins and outs in JS are causing me a bunch of headaches.

Basically, if I have a date like the following:

```<code>2018-04-06
</code>```

I want to be able to get the next day's date as such:

```<code>2018-04-07
</code>```

I found the following snippet on SO for doing this (kind of):

```<code>var date = new Date('2018-04-06');
date.setDate(date + 1);
</code>```

The problem is that I'm getting the date back with the adjusted timezone, and because I'm in the US ET timezone, it's giving me that date minus five hours, which is actually the same day as where I started.

I've been through countless SO posts trying to find an answer to this seemingly simple question, but for any given date, regardless of the timezone the user is in, how do I get the next day's date in YYYY-MM-DD format? Thank you.

答:
Did you try with the UTC date?

var date = new Date('2018-04-06');
console.log(date.toUTCString());

date.setDate(date.getDate() + 1);
console.log(date.toUTCString());```

Body:
Seems like a simple question, but all the timezone ins and outs in JS are causing me a bunch of headaches.

Basically, if I have a date like the following:

2018-04-06

I want to be able to get the next day's date as such:

2018-04-07

I found the following snippet on SO for doing this (kind of):

var date = new Date('2018-04-06');
date.setDate(date + 1);

The problem is that I'm getting the date back with the adjusted timezone, and because I'm in the US ET timezone, it's giving me that date minus five hours, which is actually the same day as where I started.

I've been through countless SO posts trying to find an answer to this seemingly simple question, but for any given date, regardless of the timezone the user is in, how do I get the next day's date in YYYY-MM-DD format? Thank you.


问:
JQuery inside js function
I am using the jquery autocomplete ui,trying to make it automatically open the menu when the user clicks in the text box.
When i use $("#selector").autocomplete( "search" , "" ); outside a function it works as intended (of course this works only one time per refresh) but when i try it inside a function it does nothing and i dont know why.

EDIT: I am also working with flask-admin who uses jinja.

```<code>{% extends 'admin/model/list.html' %}
{% import 'admin/model/layout.html' as model_layout with context %}

{% if search_supported %}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input type="text" id="selector" onfocus="func()" />

<script>
$("#selector").autocomplete({
  source: ['test',"test2"],
  minLength: 0,
  autoFocus: true,
});

$("#selector").autocomplete( "search" , "" ); //this works

function func(){
 $("#selector").autocomplete( "search" , "" ); //this doesnt
}
</script>
{% endif %}
</code>```

答:
I added an event listener to click event you could also change it to focus event, that will register the required action to your input...
here is a working snippet handles also the css, tested in chrome, edge, and firefox...</p>

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <title>Document</title>
</head>
<body>
    <input type="text" id="selector" onfocus="func()" />
    <script>
$(document).ready(()=>{
    document.getElementById('selector').addEventListener('click', func)//hook the function the click event.
    $('#selector').val('')//to make sure the input is empty on page reload...
})
$("#selector").autocomplete({
  source: ['test', "test2"],
  minLength: 0,
  autoFocus: true,
});

function func() {
    $("#selector").autocomplete("search", "")

}

    </script>
</body>
</html>
</code>```

Title: JQuery inside js function

Body:
I am using the jquery autocomplete ui,trying to make it automatically open the menu when the user clicks in the text box.
When i use $("#selector").autocomplete( "search" , "" ); outside a function it works as intended (of course this works only one time per refresh) but when i try it inside a function it does nothing and i dont know why.

EDIT: I am also working with flask-admin who uses jinja.

{% extends 'admin/model/list.html' %}
{% import 'admin/model/layout.html' as model_layout with context %}

{% if search_supported %}

<input type="text" id="selector" onfocus="func()" />

{% endif %}

Body:
I added an event listener to click event you could also change it to focus event, that will register the required action to your input...
here is a working snippet handles also the css, tested in chrome, edge, and firefox...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <title>Document</title>
</head>
<body>
    <input type="text" id="selector" onfocus="func()" />
    <script>
$(document).ready(()=>{
    document.getElementById('selector').addEventListener('click', func)//hook the function the click event.
    $('#selector').val('')//to make sure the input is empty on page reload...
})
$("#selector").autocomplete({
  source: ['test', "test2"],
  minLength: 0,
  autoFocus: true,
});

function func() {
    $("#selector").autocomplete("search", "")

}

    </script>
</body>
</html>


问:
How do I bind to the X position of a MouseDragElementBehavior?
My goal is to display the X position of my control in a TextBlock as I drag it around.

```<code>xmlns:mb="http://schemas.microsoft.com/xaml/behaviors"

<cc:CardControl Name="SevenOfSpades" Canvas.Left="350" Canvas.Top="124" Width="60" Height="80" Face="S7">
    <mb:Interaction.Behaviors>
        <mb:MouseDragElementBehavior ConstrainToParentBounds="True"/>
    </mb:Interaction.Behaviors>
</cc:CardControl>
<TextBlock Text="{Binding ElementName=SevenOfSpades, Path=(mb:Interaction.Behaviors)[0].X}"/>
</code>```

I'm struggling with the syntax of the Binding Path. At runtime I get an exception:

InvalidOperationException: Property path is not valid. 'Interaction' does not have a public property named 'Behaviors'.

The property is there because the drag works when the TextBlock is removed. I've tried various combinations of parentheses, I even tried x:static. Any help?

Edit

Having reread WPF Attached Property Data Binding, it does not solve my problem. Path= is in the Xaml and parentheses are included. The error is not a binding error it's a runtime error that occurs inside InitializeComponent.

MouseDragElementBehavior is part of the Microsoft.Xaml.Behaviors.Wpf Nuget package installed into my project.

答:
Ah, ok. In that case, the code for MouseDragElementBehavior is most certainly available, and even if it wasn't you could just open up the assembly with JustDecompile or something and browse it that way.

If you check the documentation for MouseDragElementBehavior you'll see this:

XProperty Dependency property for the X position of the dragged
  element, relative to the left of the root element.

So basically you're trying to bind one dependency property (TextBlock.Text) to another (MouseDragElementBehavior.X), but in order for this to work they have to be part of the same visual or logical tree (which they aren't, MouseDragElementBehavior is a behavior). If one of them was an attached property then you could bind them directly, but in your case you have to link them together with either a property in your DataContext that supports INPC, or some kind of proxy object.

However, even if you do this, you're going to run into problems. If you click the "Go to Live Visual Tree" button while your application is running and look at the properties for your SevenOfSpades control you'll see this:

So far, so good. Now drag the control around a bit and repeat this process. Suddenly a RenderTransform field has appeared:

Looking back at the code for MouseDragElementBehavior reveals that sure enough, that behaviour does the drag by changing the render transform.

So basically you're trying to set the position with Canvas.Top/Canvas.Left, but the behaviour is setting it by applying a render transform offset. Pick one. I personally use MVVM where everything is implemented in the view model layer, so it's easy to bind Canvas.Top/Canvas.Left to properties there. If you want to continue using MouseDragElementBehavior then you'll need to bind both the position of your cards, as well as your TextBlock text, to the render transform instead:

```<code><Canvas>

    <Rectangle Name="SevenOfSpades" Width="60" Height="80" Fill="Blue">
        <Rectangle.RenderTransform>
            <TranslateTransform X="350" Y="124" />
        </Rectangle.RenderTransform>
        <mb:Interaction.Behaviors>
            <mb:MouseDragElementBehavior ConstrainToParentBounds="True" />
        </mb:Interaction.Behaviors>
    </Rectangle>

    <TextBlock Text="{Binding ElementName=SevenOfSpades, Path=RenderTransform.Value.OffsetX}" />

</Canvas>
</code>```

Body:
My goal is to display the X position of my control in a TextBlock as I drag it around.

xmlns:mb="http://schemas.microsoft.com/xaml/behaviors"

<cc:CardControl Name="SevenOfSpades" Canvas.Left="350" Canvas.Top="124" Width="60" Height="80" Face="S7">
    <mb:Interaction.Behaviors>
        <mb:MouseDragElementBehavior ConstrainToParentBounds="True"/>
    </mb:Interaction.Behaviors>
</cc:CardControl>
<TextBlock Text="{Binding ElementName=SevenOfSpades, Path=(mb:Interaction.Behaviors)[0].X}"/>

I'm struggling with the syntax of the Binding Path. At runtime I get an exception:

InvalidOperationException: Property path is not valid. 'Interaction' does not have a public property named 'Behaviors'.

The property is there because the drag works when the TextBlock is removed. I've tried various combinations of parentheses, I even tried x:static. Any help?

Edit

Having reread WPF Attached Property Data Binding, it does not solve my problem. Path= is in the Xaml and parentheses are included. The error is not a binding error it's a runtime error that occurs inside InitializeComponent.

MouseDragElementBehavior is part of the Microsoft.Xaml.Behaviors.Wpf Nuget package installed into my project.

Body:
Ah, ok. In that case, the code for MouseDragElementBehavior is most certainly available, and even if it wasn't you could just open up the assembly with JustDecompile or something and browse it that way.

If you check the documentation for MouseDragElementBehavior you'll see this:

XProperty Dependency property for the X position of the dragged
  element, relative to the left of the root element.

So basically you're trying to bind one dependency property (TextBlock.Text) to another (MouseDragElementBehavior.X), but in order for this to work they have to be part of the same visual or logical tree (which they aren't, MouseDragElementBehavior is a behavior). If one of them was an attached property then you could bind them directly, but in your case you have to link them together with either a property in your DataContext that supports INPC, or some kind of proxy object.

However, even if you do this, you're going to run into problems. If you click the "Go to Live Visual Tree" button while your application is running and look at the properties for your SevenOfSpades control you'll see this:

So far, so good. Now drag the control around a bit and repeat this process. Suddenly a RenderTransform field has appeared:

Looking back at the code for MouseDragElementBehavior reveals that sure enough, that behaviour does the drag by changing the render transform.

So basically you're trying to set the position with Canvas.Top/Canvas.Left, but the behaviour is setting it by applying a render transform offset. Pick one. I personally use MVVM where everything is implemented in the view model layer, so it's easy to bind Canvas.Top/Canvas.Left to properties there. If you want to continue using MouseDragElementBehavior then you'll need to bind both the position of your cards, as well as your TextBlock text, to the render transform instead:

<Canvas>

    <Rectangle Name="SevenOfSpades" Width="60" Height="80" Fill="Blue">
        <Rectangle.RenderTransform>
            <TranslateTransform X="350" Y="124" />
        </Rectangle.RenderTransform>
        <mb:Interaction.Behaviors>
            <mb:MouseDragElementBehavior ConstrainToParentBounds="True" />
        </mb:Interaction.Behaviors>
    </Rectangle>

    <TextBlock Text="{Binding ElementName=SevenOfSpades, Path=RenderTransform.Value.OffsetX}" />

</Canvas>