答:
You shouldn't call notifyDataSetChanged it will refresh the entire list, which will affect the performance

```<code>cardView.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        db.deleteTitle(position+1);
        yourArrayList.remove(position);
        Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
        notifyItemRemoved(position);
        return true;
    }
});
</code>```

Title: i want to delete item from listview without restarting actitvity

Body:
i want to delete a listview item on long press on that item . after deleting item i need to restart activity to see changes  but i want to  see changes instantly

i already tried notifyDataSetChanged(); but it didn't work i am taking data from sqlite database and put it in hashmaps and sending it to custom adapter
on long press one row is deleted from database but no changes take place in listview.

@Override
public View getView( final  int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    ImageView imageView = view.findViewById(R.id.detailsimage);
    CardView cardView = view.findViewById(R.id.detailcardView);
    TextView textmo =view.findViewById(R.id.detailsmo);
    TextView texttu =view.findViewById(R.id.detailstu);
    TextView textwe =view.findViewById(R.id.detailswe);
    TextView textth =view.findViewById(R.id.detailsthu);
    TextView  textfr =view.findViewById(R.id.detailsfri);
    TextView textsa =view.findViewById(R.id.detailssat);
    TextView textsu =view.findViewById(R.id.detailssun);

    final databasehandler db = new databasehandler(context);
    cardView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            db.deleteTitle(position+1);
            Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
            notifyDataSetChanged();

            return true;
        }
    });

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            HashMap<String, String> hashmap= arrayList.get(position);
            String string= hashmap.get("repeat");
            string = Objects.requireNonNull(string).trim();

            Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
        }
    });

    HashMap<String, String> hashmap= arrayList.get(position);
    String string= Objects.requireNonNull(hashmap.get("repeat")).trim();
   String[] separated = Objects.requireNonNull(string).split("");

                        }
            }}
 return view;
 }
}

Body:
You shouldn't call notifyDataSetChanged it will refresh the entire list, which will affect the performance

cardView.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        db.deleteTitle(position+1);
        yourArrayList.remove(position);
        Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
        notifyItemRemoved(position);
        return true;
    }
});


来源: stackexchange

问:
getting a header with two alignments in apache fop
In xsl:fo i'm trying to create a header that contains the company name and the print date. The company name should be aligned to the left and the print date should be aligned to the right. Somhow i can not get this to work.

```<code><fo:static-content flow-name="xsl-region-before">
  <fo:block text-align="start" position="absolute" top="0">
    initech
  </fo:block>
  <fo:block text-align="end" position="absolute" top="0">
    Printdate 11-04-2011
  </fo:block>
</fo:static-content>
</code>```

Could anyone give me some tips on this one.

答:
Here is one way to do it:    </p>

```<code><fo:static-content flow-name="xsl-region-before">
  <fo:block text-align-last="justify">
initech<fo:leader/>Printdate 11-04-2011
  </fo:block>
</fo:static-content>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In xsl:fo i'm trying to create a header that contains the company name and the print date. The company name should be aligned to the left and the print date should be aligned to the right. Somhow i can not get this to work.

<fo:static-content flow-name="xsl-region-before">
  <fo:block text-align="start" position="absolute" top="0">
    initech
  </fo:block>
  <fo:block text-align="end" position="absolute" top="0">
    Printdate 11-04-2011
  </fo:block>
</fo:static-content>

Could anyone give me some tips on this one.

Body:
Here is one way to do it:

<fo:static-content flow-name="xsl-region-before">
  <fo:block text-align-last="justify">
initech<fo:leader/>Printdate 11-04-2011
  </fo:block>
</fo:static-content>


问:
Symfony 4 Form not being sent to the DB, probable datetimepicker issue
i have this form that was working until i added a datetimepicker. Now the submit button doesn't even work, nothing gets sent to the DB. Would anyone have an idea as to why? Thank you!

I don't get the infamous red bar, no errors are being reported by symfony...

controller

```<code> public function newReservation(request $request)
    {

        $reservation = new Contact();
        $em = $this->getDoctrine()->getRepository(Contact::class);

        $form = $this->createForm(ReservationType::class, $reservation,array());

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $reservation->setName($form['name']->getData());
            $reservation->setContent($form['content']->getData());

            $reservation->setParticipant($form['kidNumber']->getData()+$form['adultNumber']->getData());

            $reservation->setReservationStart($form['reservationStart']->getData());

            $reservation->setReservationEnd($form['reservationEnd']->getData());

            $reservation->setReservationStart2($form['reservation_start2']->getData());

            $reservation->setReservationEnd2($form['reservation_end2']->getData());

            $reservation->setContactName($form['contactName']->getData());

            $reservation->setEmail($form['email']->getData());

            $reservation->setPhone($form['phone']->getData());

            $reservation->setSubject($form['subject']->getData());

            $reservation->setDateSubmit(new \DateTime());
            $reservation->setKidNumber($form['kidNumber']->getData());

            $reservation->setAdultNumber($form['adultNumber']->getData());

            $reservation->setAddress($form['address']->getData());
            $reservation->setStatus('En attente');

            $em = $this->getDoctrine()->getManager();
            $em->persist($reservation);
            $em->flush();

            $this->addFlash(
                'notice',
                'Demande envoyée'
            );

            return $this->redirectToRoute('admin');
        }

        return $this->render('reservation/reservation.html.twig', array(
            'form' => $form->createView(),
            'reservation' => $reservation
        )
    );

    }
</code>```

form

```<code>
class ReservationType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('subject', EntityType::class, [
            'class' => Subject::class,
            'choice_label' => 'name',
            'label' => 'Choisir un type de réservation',
            'placeholder' => ' ',
        ])

        ->add('name', TextType::class, array('label'=>'Organisme', 'attr' => array(
              'class' => 'form-control',
              'title' => 'Organisme',
        )))

       ->add('contactName', TextType::class, array('label'=>'Nom de la personne à contacter', 'attr' => array(
            'class' => 'form-control',
            'title' => 'Organisme',
      )))

        ->add('reservationStart', DateTimeType::class, array(
        'label'=>'Date de début - Premier choix',
        'time_widget'=> 'single_text',
        'date_widget'=>'single_text',
        'attr' => array(
            'class' => 'datetimepicker',
            'data-format' => 'dd-mm-yyyy HH:ii',
            'title' => 'Save',
        )))

        ->add('reservationEnd', DateTimeType::class, array(
            'label'=>'Date de fin - Premier choix',
            'time_widget' => 'single_text',
            'date_widget' => 'single_text',
            'attr' => array(
                'class' => 'datetimepicker',
                'title' => 'Save',
        )))

        ->add('reservation_start2', DateTimeType::class, array(
            'label'=>'Date de début - Second choix',
            'time_widget'=> 'single_text',
            'date_widget'=>'single_text',
            'attr' => array(
                'class' => 'datetimepicker',
                'title' => 'Save',
        )))

        ->add('reservation_end2', DateTimeType::class, array(
            'label'=>'Date de fin - Second choix',
            'time_widget' => 'single_text',
            'date_widget' => 'single_text',
            'attr' => array(
                'class' => 'datetimepicker',
                'title' => 'Save',
        )))

        ->add('email', EmailType::class, array('label'=>'Email', 'attr' => array(
        'class' => 'form-control',
        'title' => 'Email',
        )))

        ->add('kidNumber', IntegerType::class, array('label'=>'Nombre d\'enfants', 'attr' => array(
        'class' => 'form-control',
        'title' => 'Nombre d\'enfant',
        )))

        ->add('adultNumber', IntegerType::class, array('label'=>'Nombre d\'adultes', 'attr' => array(
            'class' => 'form-control',
            'title' => 'Nombre d\'adulte',
            )))

        ->add('phone', TelType::class, array('label'=>'Téléphone', 'attr' => array(
            'class' => 'form-control',
            'title' => 'Telephone',
            )))

        ->add('address', TextType::class, array('label'=>'Adresse', 'attr' => array(
            'class' => 'form-control',
            'title' => 'Adresse',
            )))

        ->add('content', TextareaType::class, array('label'=>'Donnez nous plus d\'informations', 'attr' => array(
              'class' => 'form-control',
              'title' => 'Content',
            )));

        $builder
        ->add('save', SubmitType::class, array(
                'label' => 'Envoyer la demande!',
                'attr' => array(
                    'class' => 'btn btn-primary btn-margin',
                    'title' => 'Faire une demande'
                )
            ));

    }
}
</code>```

I can't see where the problem is.

答:
Well, you have a lot to improve in your code. You are using Symfony 4.x, but you are still using old practices.

Use Dependency Injection. Inject what you need. In your case:

public function newReservation(Request $request, EntityManagerInterface $em){...}

If you pass class to form, you don't need to set each value to your object. Use configureOptions() method and set data_class as Contact::class (see more details https://symfony.com/doc/current/components/options_resolver.html)

This is not how you get EntityManager:

$em = $this->getDoctrine()->getRepository(Contact::class);

If you use previous listed item, you don't need to pass second and third argument:

$form = $this->createForm(ReservationType::class, $reservation,array());

Where's your validation? Have you installed profiler (web dev bar)?

ContentLicense: CC BY-SA 4.0

Body:
i have this form that was working until i added a datetimepicker. Now the submit button doesn't even work, nothing gets sent to the DB. Would anyone have an idea as to why? Thank you!

I don't get the infamous red bar, no errors are being reported by symfony...

controller

 public function newReservation(request $request)
    {

        $reservation = new Contact();
        $em = $this->getDoctrine()->getRepository(Contact::class);

        $form = $this->createForm(ReservationType::class, $reservation,array());

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $reservation->setName($form['name']->getData());
            $reservation->setContent($form['content']->getData());

            $reservation->setParticipant($form['kidNumber']->getData()+$form['adultNumber']->getData());

            $reservation->setReservationStart($form['reservationStart']->getData());

            $reservation->setReservationEnd($form['reservationEnd']->getData());

            $reservation->setReservationStart2($form['reservation_start2']->getData());

            $reservation->setReservationEnd2($form['reservation_end2']->getData());

            $reservation->setContactName($form['contactName']->getData());

            $reservation->setEmail($form['email']->getData());

            $reservation->setPhone($form['phone']->getData());

            $reservation->setSubject($form['subject']->getData());

            $reservation->setDateSubmit(new \DateTime());
            $reservation->setKidNumber($form['kidNumber']->getData());

            $reservation->setAdultNumber($form['adultNumber']->getData());

            $reservation->setAddress($form['address']->getData());
            $reservation->setStatus('En attente');

            $em = $this->getDoctrine()->getManager();
            $em->persist($reservation);
            $em->flush();

            $this->addFlash(
                'notice',
                'Demande envoyée'
            );

            return $this->redirectToRoute('admin');
        }

        return $this->render('reservation/reservation.html.twig', array(
            'form' => $form->createView(),
            'reservation' => $reservation
        )
    );

    }

form

class ReservationType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('subject', EntityType::class, [
            'class' => Subject::class,
            'choice_label' => 'name',
            'label' => 'Choisir un type de réservation',
            'placeholder' => ' ',
        ])

        ->add('name', TextType::class, array('label'=>'Organisme', 'attr' => array(
              'class' => 'form-control',
              'title' => 'Organisme',
        )))

       ->add('contactName', TextType::class, array('label'=>'Nom de la personne à contacter', 'attr' => array(
            'class' => 'form-control',
            'title' => 'Organisme',
      )))

        ->add('reservationStart', DateTimeType::class, array(
        'label'=>'Date de début - Premier choix',
        'time_widget'=> 'single_text',
        'date_widget'=>'single_text',
        'attr' => array(
            'class' => 'datetimepicker',
            'data-format' => 'dd-mm-yyyy HH:ii',
            'title' => 'Save',
        )))

        ->add('reservationEnd', DateTimeType::class, array(
            'label'=>'Date de fin - Premier choix',
            'time_widget' => 'single_text',
            'date_widget' => 'single_text',
            'attr' => array(
                'class' => 'datetimepicker',
                'title' => 'Save',
        )))

        ->add('reservation_start2', DateTimeType::class, array(
            'label'=>'Date de début - Second choix',
            'time_widget'=> 'single_text',
            'date_widget'=>'single_text',
            'attr' => array(
                'class' => 'datetimepicker',
                'title' => 'Save',
        )))

        ->add('reservation_end2', DateTimeType::class, array(
            'label'=>'Date de fin - Second choix',
            'time_widget' => 'single_text',
            'date_widget' => 'single_text',
            'attr' => array(
                'class' => 'datetimepicker',
                'title' => 'Save',
        )))

        ->add('email', EmailType::class, array('label'=>'Email', 'attr' => array(
        'class' => 'form-control',
        'title' => 'Email',
        )))

        ->add('kidNumber', IntegerType::class, array('label'=>'Nombre d\'enfants', 'attr' => array(
        'class' => 'form-control',
        'title' => 'Nombre d\'enfant',
        )))

        ->add('adultNumber', IntegerType::class, array('label'=>'Nombre d\'adultes', 'attr' => array(
            'class' => 'form-control',
            'title' => 'Nombre d\'adulte',
            )))

        ->add('phone', TelType::class, array('label'=>'Téléphone', 'attr' => array(
            'class' => 'form-control',
            'title' => 'Telephone',
            )))

        ->add('address', TextType::class, array('label'=>'Adresse', 'attr' => array(
            'class' => 'form-control',
            'title' => 'Adresse',
            )))

        ->add('content', TextareaType::class, array('label'=>'Donnez nous plus d\'informations', 'attr' => array(
              'class' => 'form-control',
              'title' => 'Content',
            )));

        $builder
        ->add('save', SubmitType::class, array(
                'label' => 'Envoyer la demande!',
                'attr' => array(
                    'class' => 'btn btn-primary btn-margin',
                    'title' => 'Faire une demande'
                )
            ));

    }
}

I can't see where the problem is.


问:
Facing error with JMeter in Non-GUI mode. Error: "Malformed option -"
I am using Jmeter(5.1.1) in Non-GUI mode and unable to execute it. It still runs fine in GUI mode but fails in Non-GUI with "Error: Malformed option -". I removed the listeners from the JMX file but it still has some HTTP Request which are disabled will that be the problem here.?
I am currently using this command in my Windows 7 machine with Java 8.

Commands:

```<code>jmeter -n -t (location: C:\Users\File.jmx) -l (location: C:\Users\Results.csv)
</code>```

Its not showing results neither updating the results.csv file, after each run its just showing "

Error: Malformed option -

" in command window. Can someone tell me what i am missing or what should i follow.?

答:
Ok, so here what i was doing wrong. Dont know if this is stupid but might help others.

Since we use JMeter at work locations, my drive was linked with the cloud folder where none of the commands get execute i believe, so when i copy the installed JMeter folder and my JMX file to a Local location, say

before:

```<code>> C:\UsersABC\OneDrive-UserABC\JMETER\apache-jmeter-5.1.1\bin
</code>```

Now:

```<code>> C:\JMET\apache-jmeter-5.1.1\bin
</code>```

That OneDrive causing all the trouble. But thanks to all of you guys, you helped me figured this out. Thanks alot again :)

Body:
I am using Jmeter(5.1.1) in Non-GUI mode and unable to execute it. It still runs fine in GUI mode but fails in Non-GUI with "Error: Malformed option -". I removed the listeners from the JMX file but it still has some HTTP Request which are disabled will that be the problem here.?
I am currently using this command in my Windows 7 machine with Java 8.

Commands:

jmeter -n -t (location: C:\Users\File.jmx) -l (location: C:\Users\Results.csv)

Its not showing results neither updating the results.csv file, after each run its just showing "

Error: Malformed option -

" in command window. Can someone tell me what i am missing or what should i follow.?

Body:
Ok, so here what i was doing wrong. Dont know if this is stupid but might help others.

Since we use JMeter at work locations, my drive was linked with the cloud folder where none of the commands get execute i believe, so when i copy the installed JMeter folder and my JMX file to a Local location, say

before:

> C:\UsersABC\OneDrive-UserABC\JMETER\apache-jmeter-5.1.1\bin

Now:

> C:\JMET\apache-jmeter-5.1.1\bin

That OneDrive causing all the trouble. But thanks to all of you guys, you helped me figured this out. Thanks alot again :)


问:
expected substitution value for custom inline macro to be of type Inline; got String
I am trying to update my macro to use AsciidoctorJ 2.0.0. I have a macro extending InlineMacroProcessor that creates a link or a text depending on the configuration.

To create a link, I can do:

String linkUrl, linkText;
//TODO init the variables

// Define options for an 'anchor' element:
Map<String, Object> options = new HashMap<String, Object>();
options.put("type", ":link");
options.put("target", linkUrl);

// Create the 'anchor' node:
PhraseNode inline = createPhraseNode(parent, "anchor", linkText, attributes, options);
return inline;
```

<p>I would like to just insert some text to the document.</p>

<p><strong>Option 1.</strong> return just a String (as with the previous version of AsciidoctorJ):</p>

<pre class="lang-java prettyprint-override"><code>String linkText;
//TODO init the linkText variable.

return linkText;
</code>```

It works but I get this log entry:

```<code>INFO: expected substitution value for custom inline macro to be of type Inline; got String
</code>```

Which is implying that I am doing something wrong with the new API.

Option 2: I have tried to create a PhraseNode of type "text" (I invented this)

String linkText;
//TODO init the linkText variable.

PhraseNode inline = createPhraseNode(parent, "text", linkText, attributes, options);
return inline;
```

<p>But then I get:</p>

```org.asciidoctor.jruby.internal.AsciidoctorCoreException: org.jruby.exceptions.NoMethodError: (NoMethodError) undefined method `convert_inline_text' for #<Asciidoctor::Converter::Html5Converter:0x10b4e7f8>
Did you mean?  convert_inline_button
               convert_inline_quoted
               convert_inline_menu
               convert_inline_image
               convert_inline_break
               convert_inline_kbd
```

So what is the correct way to create an Inline that contains just a string?

答:
If you want to return a String, you can use:

PhraseNode inline = createPhraseNode(parent, "quoted", linkText, attributes, options);
return inline;
```

Body:
I am trying to update my macro to use AsciidoctorJ 2.0.0. I have a macro extending InlineMacroProcessor that creates a link or a text depending on the configuration.

To create a link, I can do:

String linkUrl, linkText;
//TODO init the variables

// Define options for an 'anchor' element:
Map<String, Object> options = new HashMap<String, Object>();
options.put("type", ":link");
options.put("target", linkUrl);

// Create the 'anchor' node:
PhraseNode inline = createPhraseNode(parent, "anchor", linkText, attributes, options);
return inline;

I would like to just insert some text to the document.

Option 1. return just a String (as with the previous version of AsciidoctorJ):

String linkText;
//TODO init the linkText variable.

return linkText;

It works but I get this log entry:

INFO: expected substitution value for custom inline macro to be of type Inline; got String

Which is implying that I am doing something wrong with the new API.

Option 2: I have tried to create a PhraseNode of type "text" (I invented this)

String linkText;
//TODO init the linkText variable.

PhraseNode inline = createPhraseNode(parent, "text", linkText, attributes, options);
return inline;

But then I get:

org.asciidoctor.jruby.internal.AsciidoctorCoreException: org.jruby.exceptions.NoMethodError: (NoMethodError) undefined method `convert_inline_text' for #<Asciidoctor::Converter::Html5Converter:0x10b4e7f8>
Did you mean?  convert_inline_button
               convert_inline_quoted
               convert_inline_menu
               convert_inline_image
               convert_inline_break
               convert_inline_kbd

So what is the correct way to create an Inline that contains just a string?


问:
Get UITextView dynamic height with auto layout after setting text
I have a UITextView not scrollable with auto layout set by interface builder, and the text increase or decrease dynamically with no problem, but i want know what is the new UITextView height after setting text, i'm trying to do this:

```<code>NSLog(@"text before: %.2f",self.myText.frame.size.height);
[self.myText setText:self.string];
NSLog(@"text after: %.2f",self.myText.frame.size.height);
</code>```

this is the result:

```<code>text before: 47.50
text after: 47.50
</code>```

the text is increased in the view when i run it, but the size is the same, how i can get the real height after setting text?

答:
Well, I haven't converted this code into swift4 syntax, but the logic will remain the same. This is an extension method for Xamarin.ios(C#).

```<code>public static nfloat GetEstimateHeight(this UITextView textView, UIView View)
{
    var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
    var estimatedSize = textView.SizeThatFits(size);
    return estimatedSize.Height;
}
</code>```

The logic here that will work for swift is

```<code>var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
    var estimatedSize = textView.SizeThatFits(size);
    var textViewFinalHeight = estimatedSize.Height;
</code>```

Body:
I have a UITextView not scrollable with auto layout set by interface builder, and the text increase or decrease dynamically with no problem, but i want know what is the new UITextView height after setting text, i'm trying to do this:

NSLog(@"text before: %.2f",self.myText.frame.size.height);
[self.myText setText:self.string];
NSLog(@"text after: %.2f",self.myText.frame.size.height);

this is the result:

text before: 47.50
text after: 47.50

the text is increased in the view when i run it, but the size is the same, how i can get the real height after setting text?

Body:
Well, I haven't converted this code into swift4 syntax, but the logic will remain the same. This is an extension method for Xamarin.ios(C#).

public static nfloat GetEstimateHeight(this UITextView textView, UIView View)
{
    var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
    var estimatedSize = textView.SizeThatFits(size);
    return estimatedSize.Height;
}

The logic here that will work for swift is

var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
    var estimatedSize = textView.SizeThatFits(size);
    var textViewFinalHeight = estimatedSize.Height;


问:
View - ViewModel with different data
I have a view, called a selector, which is essentially two pieces of text, a heading and a link to another page or view. During one of my iterations I noticed that this view could be made into a "view part" and mimicked all around my app for a better overall UI experience.

I now wonder, what would be the best way to change the two values in the View Model to reflect the different parts of the app I want to install this "view part" in. Should it reach into the model, should they be values on the view?

I use MVVM Light in my application and its WP7 if that helps.

答: Ok I think I found a nice clean way to do this. Have my views models ID property bound to my model as the "active view id". This property will contain the ID of the View that is open (the view parts reside inside a view at all times), the view part simply reads this value and then pulls up the appropriate data from the model based on it.</p>

Title: View - ViewModel with different data


问:
Selectively copy and paste rows with given criteria
I am trying to select rows in a table based on the word "Yes" being present in column J.

I have a table going from column A to J, and I want to select the rows where there is a "Yes" in column J and paste only those rows into a new sheet.

Once selected, I need to copy these rows to a new sheet or word document.

I have tried a range of forumulas, this is for Windows MS Excel software, using a VBA Macro.

I am using the following VBA, but having issues:

```<code>Sub Macro1()
 Dim rngJ As Range
    Dim cell As Range

    Set rngJ = Range("J1", Range("J65536").End(xlUp))
    Set wsNew = ThisWorkbook.Worksheets.Add

    For Each cell In rngJ
        If cell.Value = "Yes" Then
            cell.EntireRow.Copy

            wsNew.Sheets("Sheet1").Range("J65536").End(xlUp).Offset(1, 0).Select

            ActiveSheet.Paste
        End If
    Next cell

End Sub
</code>```

Any help would be very much appreciated!

答:
Rather than finding, copying and pasting for each cell, why not find all, then copy and paste once like this:

```<code>Sub Macro1()
Dim rngJ As Range
Dim MySel As Range

Set rngJ = Range("J1", Range("J" & Rows.Count).End(xlUp))
Set wsNew = ThisWorkbook.Worksheets.Add

For Each cell In rngJ
    If cell.Value = "Yes" Then
        If MySel Is Nothing Then
            Set MySel = cell.EntireRow
        Else
            Set MySel = Union(MySel, cell.EntireRow)
        End If
    End If
Next cell

If Not MySel Is Nothing Then MySel.Copy Destination:= wsNew.Range("A1")
End Sub
</code>```

It's better to avoid using Select as much as possible; see this link.

Body:
I am trying to select rows in a table based on the word "Yes" being present in column J.

I have a table going from column A to J, and I want to select the rows where there is a "Yes" in column J and paste only those rows into a new sheet.

Once selected, I need to copy these rows to a new sheet or word document.

I have tried a range of forumulas, this is for Windows MS Excel software, using a VBA Macro.

I am using the following VBA, but having issues:

Sub Macro1()
 Dim rngJ As Range
    Dim cell As Range

    Set rngJ = Range("J1", Range("J65536").End(xlUp))
    Set wsNew = ThisWorkbook.Worksheets.Add

    For Each cell In rngJ
        If cell.Value = "Yes" Then
            cell.EntireRow.Copy

            wsNew.Sheets("Sheet1").Range("J65536").End(xlUp).Offset(1, 0).Select

            ActiveSheet.Paste
        End If
    Next cell

End Sub

Any help would be very much appreciated!

Body:
Rather than finding, copying and pasting for each cell, why not find all, then copy and paste once like this:

Sub Macro1()
Dim rngJ As Range
Dim MySel As Range

Set rngJ = Range("J1", Range("J" & Rows.Count).End(xlUp))
Set wsNew = ThisWorkbook.Worksheets.Add

For Each cell In rngJ
    If cell.Value = "Yes" Then
        If MySel Is Nothing Then
            Set MySel = cell.EntireRow
        Else
            Set MySel = Union(MySel, cell.EntireRow)
        End If
    End If
Next cell

If Not MySel Is Nothing Then MySel.Copy Destination:= wsNew.Range("A1")
End Sub

It's better to avoid using Select as much as possible; see this link.


问:
Can a SQL database support "insert only" mode?
In the latest years the "Insert Only" methodology came more and more popular.
For those who use SQL DB you probably know that in high volume with a lot of update queries the DB is locking the rows and you starting to get a "bottleneck". the Insert Only mode is to use only insert (without updates) and always retrieve the latest item in the DB.

The issue I'm facing is with the SELECT queries since there is a field that can be common for multiple records in the DB and if I will want to query by it I will never know when I got all of the latest records for the field above (unless I'm using GROUP and this will not be efficient)

Scheme Example:

let say I have the following scheme:

```<code>CREATE TABLE users
(
  id         SERIAL    NOT NULL
    CONSTRAINT users_pkey
    PRIMARY KEY,

  first_name VARCHAR(255),
  last_name  VARCHAR(255),
  username   VARCHAR(255),
  email      VARCHAR(255),
  password   VARCHAR(255),
  account_id INTEGER,
  created_at TIMESTAMP NOT NULL
);
</code>```

Now let say I have the following users that's related to account number 1 (using account_id):
1. John Doe
2. Jain Doe

If I will want to edit John Doe last name in the Insert Only mode I will insert a new record and when I will want to retrieve it I will run the following query:

```<code>SELECT * from users WHERE email='jhon.doe@test.com' ORDER BY created_at Desc limit 1;
</code>```

The issue is what I need to to if I want to retrieve all account 1 users ? how can I prevent from executing poor query with group by

The following query will return 3 records although I have only 2 users

```<code>SELECT * from users WHERE account_id=1;
</code>```

答:
The answer to your question is distinct on (in Postgres).  However, it is unclear how you define a user.  I would expect a user_id, but perhaps email is supposed to serve this purpose.

The query looks like:

```<code>select distinct on (email) u.*
from users u
where account_id = 1
order by email, created_at desc;
</code>```

For performance, you want an index on users(account_id, email, created_at desc).

Body:
In the latest years the "Insert Only" methodology came more and more popular.
For those who use SQL DB you probably know that in high volume with a lot of update queries the DB is locking the rows and you starting to get a "bottleneck". the Insert Only mode is to use only insert (without updates) and always retrieve the latest item in the DB.

The issue I'm facing is with the SELECT queries since there is a field that can be common for multiple records in the DB and if I will want to query by it I will never know when I got all of the latest records for the field above (unless I'm using GROUP and this will not be efficient)

Scheme Example:

let say I have the following scheme:

CREATE TABLE users
(
  id         SERIAL    NOT NULL
    CONSTRAINT users_pkey
    PRIMARY KEY,

  first_name VARCHAR(255),
  last_name  VARCHAR(255),
  username   VARCHAR(255),
  email      VARCHAR(255),
  password   VARCHAR(255),
  account_id INTEGER,
  created_at TIMESTAMP NOT NULL
);

Now let say I have the following users that's related to account number 1 (using account_id):
1. John Doe
2. Jain Doe

If I will want to edit John Doe last name in the Insert Only mode I will insert a new record and when I will want to retrieve it I will run the following query:

SELECT * from users WHERE email='jhon.doe@test.com' ORDER BY created_at Desc limit 1;

The issue is what I need to to if I want to retrieve all account 1 users ? how can I prevent from executing poor query with group by

The following query will return 3 records although I have only 2 users

SELECT * from users WHERE account_id=1;

Body:
The answer to your question is distinct on (in Postgres).  However, it is unclear how you define a user.  I would expect a user_id, but perhaps email is supposed to serve this purpose.

The query looks like:

select distinct on (email) u.*
from users u
where account_id = 1
order by email, created_at desc;

For performance, you want an index on users(account_id, email, created_at desc).


问:
PHP ECHO to JSON result = JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data
I have echo from php = echo "{success: true, redirect: '/home', auth_key:'$auth_key'}";

and tried to parse it but encountering error =

JSON.parse: expected property name or '}' at line 1 column 2 of the
  JSON data

I tried jquery parse and normal json.parse method

```<code>$.ajax({

    type: "POST",
    url: "/login/process",
    data: user,
    success: function (response) {
            var resp = $.parseJSON(response);
    }
});
</code>```

I would like to get the value of auth from the echo

答:
Your JSON is invalid. Try it on jsonlint. If you scroll down the page you will see Common errors and a rule:

Enclosing your collection keys in quotes. Proper format for a collection is { "key": "value" }

It should be:

```<code>echo '{"success": true, "redirect": "/home", "auth_key":"$auth_key"}';
</code>```

Javascript test:

let invalidJson = "{success: true, redirect: '/home', auth_key:'$auth_key'}",
    validJson = '{"success": true, "redirect": "/home", "auth_key":"$auth_key"}';

try {
  console.log("invalid json", JSON.parse(invalidJson));
}
catch (e)
{
  console.error(e);
}

try {
  console.log("valid json", JSON.parse(validJson));
}
catch (e)
{
  console.error(e);
}```

If you are creating a hard code json, I would advise to create an Array and echo it with json_encode(). The function will produce a valid json with your data and you won't need to worry about formatting it.

Body:
I have echo from php = echo "{success: true, redirect: '/home', auth_key:'$auth_key'}";

and tried to parse it but encountering error =

JSON.parse: expected property name or '}' at line 1 column 2 of the
  JSON data

I tried jquery parse and normal json.parse method

$.ajax({

    type: "POST",
    url: "/login/process",
    data: user,
    success: function (response) {
            var resp = $.parseJSON(response);
    }
});

I would like to get the value of auth from the echo

Body:
Your JSON is invalid. Try it on jsonlint. If you scroll down the page you will see Common errors and a rule:

Enclosing your collection keys in quotes. Proper format for a collection is { "key": "value" }

It should be:

echo '{"success": true, "redirect": "/home", "auth_key":"$auth_key"}';

Javascript test:

let invalidJson = "{success: true, redirect: '/home', auth_key:'$auth_key'}",
    validJson = '{"success": true, "redirect": "/home", "auth_key":"$auth_key"}';

try {
  console.log("invalid json", JSON.parse(invalidJson));
}
catch (e)
{
  console.error(e);
}

try {
  console.log("valid json", JSON.parse(validJson));
}
catch (e)
{
  console.error(e);
}

If you are creating a hard code json, I would advise to create an Array and echo it with json_encode(). The function will produce a valid json with your data and you won't need to worry about formatting it.


问:
Iterating over separate lists in R
I have lots of variables in R, all of type list

```<code>a100 = list()
a200 = list()
# ...
p700 = list()
</code>```

Each variable is a complicated data structure:

```<code>a200$time$data # returns 1000 x 1000 matrix
</code>```

Now, I want to apply code to each variable in turn. However, since R doesn't support pass-by-reference, I'm not sure what to do.

One idea I had was to create a big list of all these lists, i.e.,

```<code>biglist = list()
biglist[[1]] = a100
...
</code>```

And then I could iterate over biglist:

```<code>for (i in 1:length(biglist)){
    biglist[[i]]$newstuff = "profit"
    # more code here
}
</code>```

And finally, after the loop, go backwards so that existing code (that uses variable names) still works:

```<code>a100 = biglist[[1]]
# ...
</code>```

The question is: is there a better way to iterate over a set of named lists? I have a feeling that I'm doing things horribly wrong. Is there something easier, like:

```<code># FAKE, Idealized code:
foreach x in (a100, a200, ....){
    x$newstuff = "profit"
}

a100$newstuff # "profit"
</code>```

答:
jimmyb is quite right. lapply and sapply are specifically designed to work on lists. So they would work with your biglist as well. You shouldn't forget to return the object in the nested function though : An example :

```<code>X <- list(A=list(A1=1:2,A2=3:4),B=list(B1=5:6,B2=7:8))

lapply(X,function(i){
    i$newstuff = "profit"
    return(i)
})
</code>```

Now as you said, R passes by value so you have multiple copies of the data roaming around. If you work with really big lists, you might want to try toning the memory usage down by working on each variable seperately, using assign and get. The following is considered bad coding, but can sometimes be necessary to avoid memory trouble :

```<code>A <- X[[1]] ; B <- X[[2]] #make the data
list.names <- c("A","B")

for (i in list.names){
    tmp <- get(i)
    tmp$newstuff <- "profit"
    assign(i,tmp)
    rm(tmp)
}
</code>```

Make sure you are well aware of the implication this code has, as you're working within the global environment. If you need to do this more often, you might want to work with environments instead :

```<code>my.env <- new.env() # make the environment
my.env$A <- X[[1]];my.env$B <- X[[2]] # put vars in environment

for (i in list.names){
    tmp <- get(i,envir=my.env)
    tmp$newstuff <- "profit"
    assign(i,tmp,envir=my.env)
    rm(tmp)
}
my.env$A
my.env$B
</code>```

Title: Iterating over separate lists in R

Body:
I have lots of variables in R, all of type list

a100 = list()
a200 = list()
# ...
p700 = list()

Each variable is a complicated data structure:

a200$time$data # returns 1000 x 1000 matrix

Now, I want to apply code to each variable in turn. However, since R doesn't support pass-by-reference, I'm not sure what to do.

One idea I had was to create a big list of all these lists, i.e.,

biglist = list()
biglist[[1]] = a100
...

And then I could iterate over biglist:

for (i in 1:length(biglist)){
    biglist[[i]]$newstuff = "profit"
    # more code here
}

And finally, after the loop, go backwards so that existing code (that uses variable names) still works:

a100 = biglist[[1]]
# ...

The question is: is there a better way to iterate over a set of named lists? I have a feeling that I'm doing things horribly wrong. Is there something easier, like:

# FAKE, Idealized code:
foreach x in (a100, a200, ....){
    x$newstuff = "profit"
}

a100$newstuff # "profit"

Body:
jimmyb is quite right. lapply and sapply are specifically designed to work on lists. So they would work with your biglist as well. You shouldn't forget to return the object in the nested function though : An example :

X <- list(A=list(A1=1:2,A2=3:4),B=list(B1=5:6,B2=7:8))

lapply(X,function(i){
    i$newstuff = "profit"
    return(i)
})

Now as you said, R passes by value so you have multiple copies of the data roaming around. If you work with really big lists, you might want to try toning the memory usage down by working on each variable seperately, using assign and get. The following is considered bad coding, but can sometimes be necessary to avoid memory trouble :

A <- X[[1]] ; B <- X[[2]] #make the data
list.names <- c("A","B")

for (i in list.names){
    tmp <- get(i)
    tmp$newstuff <- "profit"
    assign(i,tmp)
    rm(tmp)
}

Make sure you are well aware of the implication this code has, as you're working within the global environment. If you need to do this more often, you might want to work with environments instead :

my.env <- new.env() # make the environment
my.env$A <- X[[1]];my.env$B <- X[[2]] # put vars in environment

for (i in list.names){
    tmp <- get(i,envir=my.env)
    tmp$newstuff <- "profit"
    assign(i,tmp,envir=my.env)
    rm(tmp)
}
my.env$A
my.env$B


问:
How to order an array of objects according to different properties?
I need to order an array where the elements are objects. I want to fill up a dropdown in a specific order

```<code>[{ id: 1, name: "Country", parent: null, level: 0 },
{ id: 48, name: "Village1", parent: 16, level: 2 },
{ id: 17, name: "City1", parent: 1, level: 1 },
{ id: 15, name: "Village4", parent: 16, level: 2 },
{ id: 61, name: "City2", parent: 1, level: 1 },
{ id: 16, name: "City3", parent: 1, level: 1 },
{ id: 85, name: "City6", parent: 1, level: 1 },
{ id: 31, name: "Village2", parent: 77, level: 2 },
{ id: 76, name: "City4", parent: 1, level: 1 },
{ id: 77, name: "City5", parent: 1, level: 1 },
{ id: 79, name: "Village3", parent: 77, level: 2 }]
</code>```

What I am trying to achieve is to to get a dropdown where first appear the Country (parent null), then its children, but immediately, if those children have also children, they should appear down below, kind of:

- Country

- City1

- City2

- City3

- Village1

- Village2

- City4

. . .
And so on..

Anyone can give me a hand? I am really struggling here...

答:
You could first add all the children into a property of their parent.

```<code>[
  {
    id: 1,
    name: "Country",
    children:[{id: 17, name: "Village1", parent: 1, level: 1}]
  },
  {
    id: 2,
    name: "Country2",
    children:[{id: 19, name: "Village2", parent: 2, level: 1}]
  },
]
</code>```

Then loop through the parents, output them & nest a loop going through each parent's children and outputting them

```<code>parents.forEach((parent) => {
  //output parent
  parent.children.forEach((child) => {
  //output child
  });
});
</code>```

Body:
I need to order an array where the elements are objects. I want to fill up a dropdown in a specific order

[{ id: 1, name: "Country", parent: null, level: 0 },
{ id: 48, name: "Village1", parent: 16, level: 2 },
{ id: 17, name: "City1", parent: 1, level: 1 },
{ id: 15, name: "Village4", parent: 16, level: 2 },
{ id: 61, name: "City2", parent: 1, level: 1 },
{ id: 16, name: "City3", parent: 1, level: 1 },
{ id: 85, name: "City6", parent: 1, level: 1 },
{ id: 31, name: "Village2", parent: 77, level: 2 },
{ id: 76, name: "City4", parent: 1, level: 1 },
{ id: 77, name: "City5", parent: 1, level: 1 },
{ id: 79, name: "Village3", parent: 77, level: 2 }]

What I am trying to achieve is to to get a dropdown where first appear the Country (parent null), then its children, but immediately, if those children have also children, they should appear down below, kind of:

- Country

- City1

- City2

- City3

- Village1

- Village2

- City4

. . .
And so on..

Anyone can give me a hand? I am really struggling here...

Body:
You could first add all the children into a property of their parent.

[
  {
    id: 1,
    name: "Country",
    children:[{id: 17, name: "Village1", parent: 1, level: 1}]
  },
  {
    id: 2,
    name: "Country2",
    children:[{id: 19, name: "Village2", parent: 2, level: 1}]
  },
]

Then loop through the parents, output them & nest a loop going through each parent's children and outputting them

parents.forEach((parent) => {
  //output parent
  parent.children.forEach((child) => {
  //output child
  });
});


问:
Detecting time change in DateTimePicker
I have WPF application that holds some buttons. One button is named ChangeTime so when clicked, dialog opens and there is hh/mm/ss what you can change. I want to store picked time in variable.

My problem is that I only want store that new time if user really changed time. Currently when user presses button, event triggers and new value is stored. Also it shouldn't store new value when dialog is closed without touching Time field.

Essentially I want to change BtnWasClicked to true when time is actually changed. Poor choice of variable name indeed.

Any way to prevent it?

```<code>private DateTimePicker _timePortionDateTimePicker;
private DateTime _pickedTime;
private bool btnWasClicked = false;
private bool timeChanged = false;

private void TimeIsChanged(object sender, EventArgs e)
{
  timeChanged = true;
  if (timeChanged)
  {
    btnWasClicked = true;
  }
}

private void BtnChangeTime_OnClick(object sender, EventArgs e)
{
  Form timeDialog = new Form();

  _timePortionDateTimePicker = new DateTimePicker();
  _timePortionDateTimePicker.Format = DateTimePickerFormat.Time;
  _timePortionDateTimePicker.ShowUpDown = true;
  _timePortionDateTimePicker.ValueChanged += new
                                             EventHandler(TimeIsChanged);

  timeDialog.Controls.Add(_timePortionDateTimePicker);
  timeDialog.ShowDialog();

  _pickedTime = _timePortionDateTimePicker.Value;
}
</code>```

答:
You don't actually need TimeIsChanged. You can just check whether _timePortionDateTimePicker.Value is different from _pickedTime in BtnChangeTime_OnClick.

```<code>  Form timeDialog = new Form();

  _timePortionDateTimePicker = new DateTimePicker();
  _timePortionDateTimePicker.Format = DateTimePickerFormat.Time;
  _timePortionDateTimePicker.ShowUpDown = true;
  // start with the previous chosen time
  _timePortionDateTimePicker.Value = _pickedTime;

  timeDialog.Controls.Add(_timePortionDateTimePicker);
  timeDialog.ShowDialog();

  if (_pickedTime != _timePortionDateTimePicker.Value) {
      // time has changed, assign to _pickedTime and other variables
      _pickedTime != _timePortionDateTimePicker.Value;
      timeChanged = true;
      btnWasClicked = true;
  } // otherwise do nothing
</code>```

Title: Detecting time change in DateTimePicker

Body:
I have WPF application that holds some buttons. One button is named ChangeTime so when clicked, dialog opens and there is hh/mm/ss what you can change. I want to store picked time in variable.

My problem is that I only want store that new time if user really changed time. Currently when user presses button, event triggers and new value is stored. Also it shouldn't store new value when dialog is closed without touching Time field.

Essentially I want to change BtnWasClicked to true when time is actually changed. Poor choice of variable name indeed.

Any way to prevent it?

private DateTimePicker _timePortionDateTimePicker;
private DateTime _pickedTime;
private bool btnWasClicked = false;
private bool timeChanged = false;

private void TimeIsChanged(object sender, EventArgs e)
{
  timeChanged = true;
  if (timeChanged)
  {
    btnWasClicked = true;
  }
}

private void BtnChangeTime_OnClick(object sender, EventArgs e)
{
  Form timeDialog = new Form();

  _timePortionDateTimePicker = new DateTimePicker();
  _timePortionDateTimePicker.Format = DateTimePickerFormat.Time;
  _timePortionDateTimePicker.ShowUpDown = true;
  _timePortionDateTimePicker.ValueChanged += new
                                             EventHandler(TimeIsChanged);

  timeDialog.Controls.Add(_timePortionDateTimePicker);
  timeDialog.ShowDialog();

  _pickedTime = _timePortionDateTimePicker.Value;
}

Body:
You don't actually need TimeIsChanged. You can just check whether _timePortionDateTimePicker.Value is different from _pickedTime in BtnChangeTime_OnClick.

  Form timeDialog = new Form();

  _timePortionDateTimePicker = new DateTimePicker();
  _timePortionDateTimePicker.Format = DateTimePickerFormat.Time;
  _timePortionDateTimePicker.ShowUpDown = true;
  // start with the previous chosen time
  _timePortionDateTimePicker.Value = _pickedTime;

  timeDialog.Controls.Add(_timePortionDateTimePicker);
  timeDialog.ShowDialog();

  if (_pickedTime != _timePortionDateTimePicker.Value) {
      // time has changed, assign to _pickedTime and other variables
      _pickedTime != _timePortionDateTimePicker.Value;
      timeChanged = true;
      btnWasClicked = true;
  } // otherwise do nothing


问:
NGINX auth_request is ignored
I have the following in my nginx.conf:

```<code>location / {
    auth_request /auth;
    add_header Content-Type text/plain;
    return 200 'You are in!';
}

location = /auth {
    proxy_pass http://localhost:5021/auth;
    proxy_pass_request_body off;
    proxy_set_header Host $http_host;
    proxy_set_header X-Original-URI $request_uri;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Authorization $http_authorization;
    proxy_pass_header Authorization;
}
</code>```

Thus I would expect http://localhost:5021/auth (a Flask app) to be accessed upon trying to reach /. This does not happen, and using the nginx-debug binary and error_log  /var/log/nginx/error.log debug; I never see any of the debug output that I expect to see (log for the request is available here). There are no errors, neither printed to the console nor any of nginx's log files. It seems like the auth_request line is just silently ignored.

Output of nginx-debug -V (it does contain --with-http_auth_request_module):

```<code>nginx version: nginx/1.15.8
built by gcc 6.4.0 (Alpine 6.4.0)
built with OpenSSL 1.0.2q  20 Nov 2018
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-threads --with-stream --with-stream_ssl_module --with-stream_ssl_preread_module --with-stream_realip_module --with-stream_geoip_module=dynamic --with-http_slice_module --with-mail --with-mail_ssl_module --with-compat --with-file-aio --with-http_v2_module --with-debug
</code>```

答:
Instead

```<code>return 200 'You are in!';
</code>```

you can use the following code

```<code>echo -n "You are in!";
</code>```

Title: NGINX auth_request is ignored

Body:
I have the following in my nginx.conf:

location / {
    auth_request /auth;
    add_header Content-Type text/plain;
    return 200 'You are in!';
}

location = /auth {
    proxy_pass http://localhost:5021/auth;
    proxy_pass_request_body off;
    proxy_set_header Host $http_host;
    proxy_set_header X-Original-URI $request_uri;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Authorization $http_authorization;
    proxy_pass_header Authorization;
}

Thus I would expect http://localhost:5021/auth (a Flask app) to be accessed upon trying to reach /. This does not happen, and using the nginx-debug binary and error_log  /var/log/nginx/error.log debug; I never see any of the debug output that I expect to see (log for the request is available here). There are no errors, neither printed to the console nor any of nginx's log files. It seems like the auth_request line is just silently ignored.

Output of nginx-debug -V (it does contain --with-http_auth_request_module):

nginx version: nginx/1.15.8
built by gcc 6.4.0 (Alpine 6.4.0)
built with OpenSSL 1.0.2q  20 Nov 2018
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-threads --with-stream --with-stream_ssl_module --with-stream_ssl_preread_module --with-stream_realip_module --with-stream_geoip_module=dynamic --with-http_slice_module --with-mail --with-mail_ssl_module --with-compat --with-file-aio --with-http_v2_module --with-debug

Body:
Instead

return 200 'You are in!';

you can use the following code

echo -n "You are in!";


问:
PHP - How to sort multidimensional array by Key?
I have to sort multidimensional array by key and I need some recomendation how to do it.

I tried using ksort() and other php built-in functions, but none of them helped me.

This is my array, which I want to sort by key:

```<code>Array
(
[0] => Array
    (
        [20190529] => Array
            (
                [30] => Array
                    (
                        [17] => Array
                            (
                                [3846] => 0
                            )

                    )

            )

    )

[1] => Array
    (
        [20190516] => Array
            (
                [31] => Array
                    (
                        [17] => Array
                            (
                                [512] => 0
                            )

                    )

            )

    )
</code>```

)

In that case, keys are 20190529 and 20190516

答:
I modified my array like that:

```<code>Array
(
[0] => Array
    (
        [DATE] => 20190503
        [DEAL] => 30
        [IBLOCK] => 18
        [AMOUNT] => 2500
        [PAYED] => 0
    )

[1] => Array
    (
        [DATE] => 20190516
        [DEAL] => 31
        [IBLOCK] => 17
        [AMOUNT] => 512
        [PAYED] => 0
    )
)
</code>```

then I used usort():

```<code>function cmp($a, $b) {
    return $a['DATE'] - $b['DATE'];
}

usort($mydata, "cmp");
</code>```

And it did job for me :) but Now I have to modify my array again to return first look.

Body:
I have to sort multidimensional array by key and I need some recomendation how to do it.

I tried using ksort() and other php built-in functions, but none of them helped me.

This is my array, which I want to sort by key:

Array
(
[0] => Array
    (
        [20190529] => Array
            (
                [30] => Array
                    (
                        [17] => Array
                            (
                                [3846] => 0
                            )

                    )

            )

    )

[1] => Array
    (
        [20190516] => Array
            (
                [31] => Array
                    (
                        [17] => Array
                            (
                                [512] => 0
                            )

                    )

            )

    )

)

In that case, keys are 20190529 and 20190516

Body:
I modified my array like that:

Array
(
[0] => Array
    (
        [DATE] => 20190503
        [DEAL] => 30
        [IBLOCK] => 18
        [AMOUNT] => 2500
        [PAYED] => 0
    )

[1] => Array
    (
        [DATE] => 20190516
        [DEAL] => 31
        [IBLOCK] => 17
        [AMOUNT] => 512
        [PAYED] => 0
    )
)

then I used usort():

function cmp($a, $b) {
    return $a['DATE'] - $b['DATE'];
}

usort($mydata, "cmp");

And it did job for me :) but Now I have to modify my array again to return first look.


问:
TextView display wrong with escape character
I have a random message that contains escape characters. I found that TextView displays wrong spaces for escape characters "\t".

My sample project has an Activity that has a layout with only one TextView.

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_hello"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:text="@string/text_hello"
        android:maxLines="5"
        />
</FrameLayout>
</code>```

I define text in file strings.xml

```<code><string name="text_hello">Click Change: 13894\t18258\nClick Change: 1604\t2190\nClick Change: 9250\t11962</string>
</code>```

The corresponding result is

I change the text like below

```<code><string name="text_hello">ABC: 13894\t18258\nDEF: 1604\t2190\nXYZ: 9250\t11962</string>
</code>```

The corresponding result will changes

As sample, TextView displays wrongly space. Can anyone has a solution to fix this issue?

答:
You can use

```<code>\u0020
</code>```

or

```<code>
</code>```

instead of \t in string.xml file.

Body:
I have a random message that contains escape characters. I found that TextView displays wrong spaces for escape characters "\t".

My sample project has an Activity that has a layout with only one TextView.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_hello"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:text="@string/text_hello"
        android:maxLines="5"
        />
</FrameLayout>

I define text in file strings.xml

<string name="text_hello">Click Change: 13894\t18258\nClick Change: 1604\t2190\nClick Change: 9250\t11962</string>

The corresponding result is

I change the text like below

<string name="text_hello">ABC: 13894\t18258\nDEF: 1604\t2190\nXYZ: 9250\t11962</string>

The corresponding result will changes

As sample, TextView displays wrongly space. Can anyone has a solution to fix this issue?

Body:
You can use

\u0020

or

&#032;

instead of \t in string.xml file.


问:
Is it possible to update a For End argument while inside it?
I wanted to change my For "End" argument while inside the For.

For instance:

```<code>ForEnd = 3
for i = 1 To ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
Next i
</code>```

This doesn't work because the "End" or "Upper Limit" argument is defined once the code goes through the first line. Even if I change it inside the code it will consider the original value.

Any thoughts?

Thank you.

答:
You can not control the upper limit of a For cycle when you use a const or a variable in the heading. However, using a function will do this:

```<code>for i = 1 To ForEnd(i)
      ' commands
Next i

Function ForEnd(k as Long) As Long

     If Something = "TRUE" Then
        ForEnd = 0
     Else
        ForEnd = k + 1
     End If

End Function
</code>```

though I'd rather use Do While as above. If you need For loop then you can use Exit For to break the loop in case:

```<code>for i = 1 To 111111
    If Something = "False" Then Exit For
Next i
</code>```

Body:
I wanted to change my For "End" argument while inside the For.

For instance:

ForEnd = 3
for i = 1 To ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
Next i

This doesn't work because the "End" or "Upper Limit" argument is defined once the code goes through the first line. Even if I change it inside the code it will consider the original value.

Any thoughts?

Thank you.

Body:
You can not control the upper limit of a For cycle when you use a const or a variable in the heading. However, using a function will do this:

for i = 1 To ForEnd(i)
      ' commands
Next i

Function ForEnd(k as Long) As Long

     If Something = "TRUE" Then
        ForEnd = 0
     Else
        ForEnd = k + 1
     End If

End Function

though I'd rather use Do While as above. If you need For loop then you can use Exit For to break the loop in case:

for i = 1 To 111111
    If Something = "False" Then Exit For
Next i


问:
ASP.net page without a code behind
I have an ASP.Net page with a C# code behind.

However, I've been asked to not use a code behind - so that it will be easier to deploy in SharePoint.

Is there a way to include the C# code in the ASP.Net page, without using a separate code behind file?

答:
yes on your aspx page include a script tag with runat=server

```<code><script language="c#" runat="server">

public void Page_Load(object sender, EventArgs e)
{
  // some load code
}
</script>
</code>```

You can also use classic ASP Syntax

```<code><% if (this.MyTextBox.Visible) { %>
<span>Only show when myTextBox is visible</span>
<% } %>
</code>```

OwnerDisplayName: Sophia

ContentLicense: CC BY-SA 2.5

Title: ASP.net page without a code behind

Body:
yes on your aspx page include a script tag with runat=server

<script language="c#" runat="server">

public void Page_Load(object sender, EventArgs e)
{
  // some load code
}
</script>

You can also use classic ASP Syntax

<% if (this.MyTextBox.Visible) { %>
<span>Only show when myTextBox is visible</span>
<% } %>

OwnerDisplayName: bendewey


问:
UIButton state selected
I've seen a lot of info on changing the button image for selected but being a new I'm having a bit of trouble implementing a simpler version of it.

When the button is pressed it goes dark and I would like it to stay that way once it's been selected. So there are a few questions.

Do I create IBOutlet for the button and then and IBAction to change the state with something like button.state = SELECTED.

Sorry for the complete lack of any code to look at.

Edit: (id)sender is the button object right?

```<code>-(IBAction)journalEntryViewControllerClick: (id)sender
{
    UIButton *button = (id)sender;

    [button setSelected:YES];

}
</code>```

答: You probably want a UISegmentedControl instead. UIButton's are meant to be momentary.

Title: UIButton state selected

Body:
I've seen a lot of info on changing the button image for selected but being a new I'm having a bit of trouble implementing a simpler version of it.

When the button is pressed it goes dark and I would like it to stay that way once it's been selected. So there are a few questions.

Do I create IBOutlet for the button and then and IBAction to change the state with something like button.state = SELECTED.

Sorry for the complete lack of any code to look at.

Edit: (id)sender is the button object right?

-(IBAction)journalEntryViewControllerClick: (id)sender
{
    UIButton *button = (id)sender;

    [button setSelected:YES];

}


问:
Asynchronously copy from one realm to another
From my understanding, Realm can/should only be accessed from the main thread.

I use two realms, one for storing "dirty" data that, upon validation, will be moved to the real realm.

So far so good, but I cannot find a way to do so outside of the mainthread.
If I write to the real realm using realm.executeTransactionAsync(), I will not be able to access the dirty realm or its RealmResults inside the transactions thread.

The only workaround is to use dirtyRealm.copyFromRealm() on the main thread - which could potentially block the thread for a longer time, right?

Is this the right approach or are there better solutions?

答:
I used RxJava Completable to complete this operation in background thread

```<code> public class RealmCopier {

    private String errorLog = "";

    public Completable copyTo(Realm realm) {//in my case remote realm on ROS

        return Completable.create(emitter -> {

            boolean isCopied = copy(realm);

            if (!emitter.isDisposed()){

                if (isCopied)
                    emitter.onComplete();
                else
                    emitter.onError(new Throwable(errorLog));

            }
        });

    }

    private boolean copy(Realm realm) {

        try {
            realm.beginTransaction();

            realm.insertOrUpdate(getItems(SomeClassA.class));
            realm.insertOrUpdate(getItems(SomeClassB.class));

            realm.commitTransaction();

        }catch(Exception e){
            realm.cancelTransaction();
            errorLog = e.getMessage();
            return false;

        } finally {
            realm.close();
        }

        return true;
    }

    private List<? extends RealmObject> getItems(Class<? extends RealmObject> classType) {

        RealmConfiguration localConfiguration = ConfigurationManager.createLocalConfiguration();

        Realm realm = Realm.getInstance(localConfiguration);//local realm

        return realm.where(classType).findAll();
    }

}
</code>```

Body:
I used RxJava Completable to complete this operation in background thread

 public class RealmCopier {

    private String errorLog = "";

    public Completable copyTo(Realm realm) {//in my case remote realm on ROS

        return Completable.create(emitter -> {

            boolean isCopied = copy(realm);

            if (!emitter.isDisposed()){

                if (isCopied)
                    emitter.onComplete();
                else
                    emitter.onError(new Throwable(errorLog));

            }
        });

    }

    private boolean copy(Realm realm) {

        try {
            realm.beginTransaction();

            realm.insertOrUpdate(getItems(SomeClassA.class));
            realm.insertOrUpdate(getItems(SomeClassB.class));

            realm.commitTransaction();

        }catch(Exception e){
            realm.cancelTransaction();
            errorLog = e.getMessage();
            return false;

        } finally {
            realm.close();
        }

        return true;
    }

    private List<? extends RealmObject> getItems(Class<? extends RealmObject> classType) {

        RealmConfiguration localConfiguration = ConfigurationManager.createLocalConfiguration();

        Realm realm = Realm.getInstance(localConfiguration);//local realm

        return realm.where(classType).findAll();
    }

}


问:
How to apply "to_f" to a column for all results in an active record query inside rails console
I have this query:
p = Payment.where(:client_id => 1)

Then only some fields, so I execute this:
p.select(:id, :created_at, :amount)

The issue is that every amount in the result comes as BigDecimal, and it's not readable. I need to apply to_f function inside rails console to have a readable set of results.

I tried map,like this:
p.map {|p| p.amount.to_f}
But it returns to me an array only with the amounts, and I need it to be along with the other attributes.

答:
You can try like this,</p>

```<code>p.map { |item| { id: item.id, created_at: item.created_at, amount: item.amount.to_f}}
</code>```

Body:
You can try like this,

p.map { |item| { id: item.id, created_at: item.created_at, amount: item.amount.to_f}}


答:
Instead you create array and save it as json and check,

```<code>$a =  ["success" =>  true, "redirect" =>  '/home', "auth_key" => $auth_key];
echo json_encode($a, JSON_UNESCAPED_SLASHES);die; //
</code>```

JSON_UNESCAPED_SLASHES - Don't escape /.

Output

```<code>{"success":true,"redirect":"/home","auth_key":"123213123123"}
</code>```

This will give sure short json output.

Title: PHP ECHO to JSON result = JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data

Body:
I have echo from php = echo "{success: true, redirect: '/home', auth_key:'$auth_key'}";

and tried to parse it but encountering error =

JSON.parse: expected property name or '}' at line 1 column 2 of the
  JSON data

I tried jquery parse and normal json.parse method

$.ajax({

    type: "POST",
    url: "/login/process",
    data: user,
    success: function (response) {
            var resp = $.parseJSON(response);
    }
});

I would like to get the value of auth from the echo

Body:
Instead you create array and save it as json and check,

$a =  ["success" =>  true, "redirect" =>  '/home', "auth_key" => $auth_key];
echo json_encode($a, JSON_UNESCAPED_SLASHES);die; //

JSON_UNESCAPED_SLASHES - Don't escape /.

Output

{"success":true,"redirect":"/home","auth_key":"123213123123"}

This will give sure short json output.


问:
Truncate and rename subdirectories within a directory
I have several folders named:

```<code>001TRIAL1
002TRIAL2
003TRIAL3
...etc.
</code>```

I'm trying to rename all folders using a batch-file and truncate them in order to get:

```<code>TRIAL1
TRIAL2
TRIAL3
...etc.
</code>```

I have tried this code:

```<code>for /D %%X in (C:\FOLDER1\FOLDER2\*) do (
    move %%X %%X:~3,10%
)
Pause
</code>```

But I'm unable to get the result I want.

This script does not work and I don't know how I can do that. The rename allows to rename folders but I'm not able to truncate the folders that I want.

答:
You cannot expand a metavariable like that, you need to set the value to a proper variable, then perform the expansion. Additionally, as the variable would be set within a code block, you'd need to enable delayed expansion. Finally, you'd use Rename not Move, which would require that the directory already existed, and you'd need to delete the original directory post rename.

Try this:

@Echo Off
SetLocal DisableDelayedExpansion
For /D %%A In ("C:\FOLDER1\FOLDER2\*") Do (
    Set "_d=%%~nxA"
    SetLocal EnableDelayedExpansion
    If Not Exist "%%~dpA!_d:~3!" Ren "%%A" "!_d:~3!"
    EndLocal
)
```

Body:
I have several folders named:

001TRIAL1
002TRIAL2
003TRIAL3
...etc.

I'm trying to rename all folders using a batch-file and truncate them in order to get:

TRIAL1
TRIAL2
TRIAL3
...etc.

I have tried this code:

for /D %%X in (C:\FOLDER1\FOLDER2\*) do (
    move %%X %%X:~3,10%
)
Pause

But I'm unable to get the result I want.

This script does not work and I don't know how I can do that. The rename allows to rename folders but I'm not able to truncate the folders that I want.


问:
Encoding a string in 128c barcode symbology
I am having some trouble with encoding this string into barcode symbology - Code 128.

Text to encode:
1021448642241082212700794828592311

I am using the universal encoder from idautomation.com:
https://www.bcgen.com/fontencoder/

I get the following output for the encoded text for Code 128:
Í*5LvJ8*r5;ÂoP<[7+.Î

However, in ";Âo"  the character between the semi-colon and o (let us call it special A) - is not part of the extended character set used in Code128. (See the Latin Supplements at https://www.fonts2u.com/code-128.font)

Yet the same string shows a valid barcode at
https://www.bcgen.com/linear-barcode-creator.html

How?

If I use the output with the Special A on a webpage with a font face for barcodes, the special A character does not show up as the barcode (and that seems correct since the special A is not part of the character set).

What gives? Please help.

I am using the IDAutomation utility to encode the string to 128c symbology. If you can share code to do the encoding (in Java/Python/C/Perl) that would help too.

答:
Sorry, this is very late.

When you are dealing with the encoding of code 128, in any subset, it's a good idea to think of that coding in terms of numbers, not characters. At this level, when you have shifts, code-changes, checksums and stuff, intermixed with the data, the whole concept of "character" is lost.

However, this is what is happening:

The semicolon in the output corresponds to "27"
The lowercase o corresponds to "48" and the P to "79"

The "A with Macron" corresponds to your "00" sequence. This is why you should be dealing with numbers, not characters, at this level of encoding.

How would you expect it to show a character with a code of 00 ? That would be a space of NULL, neither of which is particularly visible.

Your software has simply rendered it the best way it can, which is to make the character 'visible' by adding 0x80 to it. If you look at charmap, you will see that code 0x80 is indeed A with macron.

The rest (indeed all) of your encoded string looks correct for a setc-encodation.


问:
Is there an c++ function from Armadillo for selecting a column from a matrix?”
I'm looking for selecting a column from a matrix H for example, knowingly that a have the index off this column

I searched in Armadillio

答:
Try the .col(col_number) function, or the .cols(first_col, last_col) function.

See here.


问:
Returning header as array using Curl
I'm trying to get the response & the response headers from CURL using PHP, specifically for Content-Disposition: attachment; so I can return the filename passed within the header. This doesn't seem to get returned within curl_getinfo.

I've tried using the HeaderFunction to call a function to read the additional headers, however, I am unable to add the contents to an array.

Does anyone have any ideas please?

Below is part of my code which is a Curl wrapper class:

```<code> ...
 curl_setopt($this->_ch, CURLOPT_URL, $this->_url);
 curl_setopt($this->_ch, CURLOPT_HEADER, false);
 curl_setopt($this->_ch, CURLOPT_POST, 1);
 curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $this->_postData);
 curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($this->_ch, CURLOPT_USERAGENT, $this->_userAgent);
 curl_setopt($this->_ch, CURLOPT_HEADERFUNCTION, 'readHeader');

 $this->_response = curl_exec($this->_ch);
 $info = curl_getinfo($this->_ch);
 ...

 function readHeader($ch, $header)
 {
      array_push($this->_headers, $header);
 }
</code>```

答:
Fixing issues:

Error when content of the header contained ': '(split string)

Multiline-headers were not supported

Duplicate headers (Set-Cookie) were not supported

This is my take on the topic ;-)

```<code>list($head, $body)=explode("\r\n\r\n", $content, 2);
$headers=parseHeaders($head);

function parseHeaders($text) {
    $headers=array();

    foreach (explode("\r\n", $text) as $i => $line) {
        // Special HTTP first line
        if (!$i && preg_match('@^HTTP/(?<protocol>[0-9.]+)\s+(?<code>\d+)(?:\s+(?<message>.*))?$@', $line, $match)) {
            $headers['@status']=$line;
            $headers['@code']=$match['code'];
            $headers['@protocol']=$match['protocol'];
            $headers['@message']=$match['message'];
            continue;
        }

        // Multiline header - join with previous
        if ($key && preg_match('/^\s/', $line)) {
            $headers[$key].=' '.trim($line);
            continue;
        }

        list ($key, $value) = explode(': ', $line, 2);
        $key=strtolower($key);
        // Append duplicate headers - namely Set-Cookie header
        $headers[$key]=isset($headers[$key]) ? $headers[$key].' ' : $value;
    }

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

Title: Returning header as array using Curl

Body:
I'm trying to get the response & the response headers from CURL using PHP, specifically for Content-Disposition: attachment; so I can return the filename passed within the header. This doesn't seem to get returned within curl_getinfo.

I've tried using the HeaderFunction to call a function to read the additional headers, however, I am unable to add the contents to an array.

Does anyone have any ideas please?

Below is part of my code which is a Curl wrapper class:

 ...
 curl_setopt($this->_ch, CURLOPT_URL, $this->_url);
 curl_setopt($this->_ch, CURLOPT_HEADER, false);
 curl_setopt($this->_ch, CURLOPT_POST, 1);
 curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $this->_postData);
 curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($this->_ch, CURLOPT_USERAGENT, $this->_userAgent);
 curl_setopt($this->_ch, CURLOPT_HEADERFUNCTION, 'readHeader');

 $this->_response = curl_exec($this->_ch);
 $info = curl_getinfo($this->_ch);
 ...

 function readHeader($ch, $header)
 {
      array_push($this->_headers, $header);
 }

Body:
Fixing issues:

Error when content of the header contained ': '(split string)

Multiline-headers were not supported

Duplicate headers (Set-Cookie) were not supported

This is my take on the topic ;-)

list($head, $body)=explode("\r\n\r\n", $content, 2);
$headers=parseHeaders($head);

function parseHeaders($text) {
    $headers=array();

    foreach (explode("\r\n", $text) as $i => $line) {
        // Special HTTP first line
        if (!$i && preg_match('@^HTTP/(?<protocol>[0-9.]+)\s+(?<code>\d+)(?:\s+(?<message>.*))?$@', $line, $match)) {
            $headers['@status']=$line;
            $headers['@code']=$match['code'];
            $headers['@protocol']=$match['protocol'];
            $headers['@message']=$match['message'];
            continue;
        }

        // Multiline header - join with previous
        if ($key && preg_match('/^\s/', $line)) {
            $headers[$key].=' '.trim($line);
            continue;
        }

        list ($key, $value) = explode(': ', $line, 2);
        $key=strtolower($key);
        // Append duplicate headers - namely Set-Cookie header
        $headers[$key]=isset($headers[$key]) ? $headers[$key].' ' : $value;
    }

    return $headers;
}


问:
How does line spacing work in Core Text? (and why is it different from NSLayoutManager?)
I'm trying to draw text using Core Text functions, with a line spacing that's as close as possible to what it would be if I used NSTextView.

Take this font as an example:

```<code>NSFont *font = [NSFont fontWithName:@"Times New Roman" size:96.0];
</code>```

The line height of this font, if I would use it in an NSTextView is 111.0.

```<code>NSLayoutManager *lm = [[NSLayoutManager alloc] init];
NSLog(@"%f", [lm defaultLineHeightForFont:font]); // this is 111.0
</code>```

Now, if I do the same thing with Core Text, the result is 110.4 (assuming you can calculate the line height by adding the ascent, descent and leading).

```<code>CTFontRef cFont = CTFontCreateWithName(CFSTR("Times New Roman"), 96.0, NULL);
NSLog(@"%f", CTFontGetDescent(cFont) + CTFontGetAscent(cFont) +
             CTFontGetLeading(cFont)); // this is 110.390625
</code>```

This is very close to 111.0, but for some fonts the difference is much bigger.
E.g. for Helvetica, NSLayoutManager gives 115.0 whereas CTFont ascent + descent + leading = 96.0. Clearly, for Helvetica, I wouldn't be able to use ascent + descent + leading to calculate the spacing between lines.

So I thought I'd use CTFrame and CTFramesetter to layout a few lines and get the linespacing from that. But that also gives different values.

```<code>CTFontRef cFont = CTFontCreateWithName(CFSTR("Times New Roman"), 96.0, NULL);
NSDictionary *attrs = [NSDictionary dictionaryWithObject:(id)cFont forKey:(id)kCTFontAttributeName];
NSAttributedString *threeLines = [[NSAttributedString alloc] initWithString:@"abcdefg\nabcdefg\nabcdefg" attributes:attrs];

CTFramesetterRef threeLineFramesetter =  CTFramesetterCreateWithAttributedString((CFAttributedStringRef)threeLines);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0.0, 0.0, 600.0, 600.0));
CTFrameRef threeLineFrame = CTFramesetterCreateFrame(threeLineFramesetter, CFRangeMake(0, 0), path, NULL);

CGPoint lineOrigins[3];
CTFrameGetLineOrigins(threeLineFrame, CFRangeMake(0, 0), lineOrigins);
NSLog(@"space between line 1 and 2: %f", lineOrigins[0].y - lineOrigins[1].y); // result: 119.278125
NSLog(@"space between line 2 and 3: %f", lineOrigins[1].y - lineOrigins[2].y); // result: 113.625000
</code>```

So the line spacing is now even more different from the 111.0 that was used in my NSTextView, and not every line is equal. It seems that the line breaks add some extra space (even though the default value for paragraphSpacingBefore is 0.0).

I'm working around this problem now by getting the line height via NSLayoutManager and then individually drawing each CTLine, but I wonder if there's a better way to do this.

答:
OK, so I took a good look at what goes on in the guts of NSLayoutManager, and it appears, based on my reading of the disassembly, that the code it uses boils down to something like this:

```<code>CGFloat ascent = CTFontGetAscent(theFont);
CGFloat descent = CTFontGetDescent(theFont);
CGFloat leading = CTFontGetLeading(theFont);

if (leading < 0)
  leading = 0;

leading = floor (leading + 0.5);

lineHeight = floor (ascent + 0.5) + floor (descent + 0.5) + leading;

if (leading > 0)
  ascenderDelta = 0;
else
  ascenderDelta = floor (0.2 * lineHeight + 0.5);

defaultLineHeight = lineHeight + ascenderDelta;
</code>```

This will get you the 111.0 and 115.0 values for the two fonts you mention above.

I should add that the correct way, according to the OpenType specification, is just to add the three values (being careful, if you’re using an API that doesn’t make them all positive, to get the sign of the descent value correct).

Body:
I'm trying to draw text using Core Text functions, with a line spacing that's as close as possible to what it would be if I used NSTextView.

Take this font as an example:

NSFont *font = [NSFont fontWithName:@"Times New Roman" size:96.0];

The line height of this font, if I would use it in an NSTextView is 111.0.

NSLayoutManager *lm = [[NSLayoutManager alloc] init];
NSLog(@"%f", [lm defaultLineHeightForFont:font]); // this is 111.0

Now, if I do the same thing with Core Text, the result is 110.4 (assuming you can calculate the line height by adding the ascent, descent and leading).

CTFontRef cFont = CTFontCreateWithName(CFSTR("Times New Roman"), 96.0, NULL);
NSLog(@"%f", CTFontGetDescent(cFont) + CTFontGetAscent(cFont) +
             CTFontGetLeading(cFont)); // this is 110.390625

This is very close to 111.0, but for some fonts the difference is much bigger.
E.g. for Helvetica, NSLayoutManager gives 115.0 whereas CTFont ascent + descent + leading = 96.0. Clearly, for Helvetica, I wouldn't be able to use ascent + descent + leading to calculate the spacing between lines.

So I thought I'd use CTFrame and CTFramesetter to layout a few lines and get the linespacing from that. But that also gives different values.

CTFontRef cFont = CTFontCreateWithName(CFSTR("Times New Roman"), 96.0, NULL);
NSDictionary *attrs = [NSDictionary dictionaryWithObject:(id)cFont forKey:(id)kCTFontAttributeName];
NSAttributedString *threeLines = [[NSAttributedString alloc] initWithString:@"abcdefg\nabcdefg\nabcdefg" attributes:attrs];

CTFramesetterRef threeLineFramesetter =  CTFramesetterCreateWithAttributedString((CFAttributedStringRef)threeLines);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0.0, 0.0, 600.0, 600.0));
CTFrameRef threeLineFrame = CTFramesetterCreateFrame(threeLineFramesetter, CFRangeMake(0, 0), path, NULL);

CGPoint lineOrigins[3];
CTFrameGetLineOrigins(threeLineFrame, CFRangeMake(0, 0), lineOrigins);
NSLog(@"space between line 1 and 2: %f", lineOrigins[0].y - lineOrigins[1].y); // result: 119.278125
NSLog(@"space between line 2 and 3: %f", lineOrigins[1].y - lineOrigins[2].y); // result: 113.625000

So the line spacing is now even more different from the 111.0 that was used in my NSTextView, and not every line is equal. It seems that the line breaks add some extra space (even though the default value for paragraphSpacingBefore is 0.0).

I'm working around this problem now by getting the line height via NSLayoutManager and then individually drawing each CTLine, but I wonder if there's a better way to do this.

Body:
OK, so I took a good look at what goes on in the guts of NSLayoutManager, and it appears, based on my reading of the disassembly, that the code it uses boils down to something like this:

CGFloat ascent = CTFontGetAscent(theFont);
CGFloat descent = CTFontGetDescent(theFont);
CGFloat leading = CTFontGetLeading(theFont);

if (leading < 0)
  leading = 0;

leading = floor (leading + 0.5);

lineHeight = floor (ascent + 0.5) + floor (descent + 0.5) + leading;

if (leading > 0)
  ascenderDelta = 0;
else
  ascenderDelta = floor (0.2 * lineHeight + 0.5);

defaultLineHeight = lineHeight + ascenderDelta;

This will get you the 111.0 and 115.0 values for the two fonts you mention above.

I should add that the correct way, according to the OpenType specification, is just to add the three values (being careful, if you’re using an API that doesn’t make them all positive, to get the sign of the descent value correct).


问:
Using HttpContextAccessor inside of injected class
Using ASP.NET Core 3.0 Preview 5, I'm trying to access HttpContextAccessor from inside an AppState class that I'm injecting into my application.

Unfortunately I keep getting a System.AggregateException with a message of

''Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: [MyNameSpace].AppState
  Lifetime: Singleton ImplementationType: [MyNameSpace].AppState':
  Unable to resolve service for type
  'Microsoft.AspNetCore.Http.HttpContextAccessor' while attempting to
  activate '[MyNameSpace].AppState'.)'

My Startup.cs file is as follows:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();

    services.AddHttpContextAccessor();
    services.AddSingleton<AppState>();

    // More services
}
</code>```

and my AppState.cs file is as follows:

```<code>private HttpContextAccessor _httpContextAccessor;

public AppState(HttpContextAccessor httpContextAccessor)
{
     _httpContextAccessor = httpContextAccessor;
}
</code>```

I've checked online and it seems that just adding the AddHttpContextAccessor and AddSingleton<T> to my ConfigureServices method should do the trick but for some reason it isn't working.

As I'm pretty new to ASP.NET Core and Dependency Injection, I just wanted to see if someone who knows what they are doing has any idea what I'm doing wrong!

答:
The AddHttpContextAccessor() method registers the service as a IHttpContextAccessor (note the I prefix to denote it is an interface) and that is what your class needs to explicitly accept in it's constructor:

```<code>private IHttpContextAccessor _httpContextAccessor;

public AppState(IHttpContextAccessor httpContextAccessor)
{
     _httpContextAccessor = httpContextAccessor;
}
</code>```

However, you should not be using this from a singleton class. HTTP requests are, unsurprisingly different per request.

Body:
Using ASP.NET Core 3.0 Preview 5, I'm trying to access HttpContextAccessor from inside an AppState class that I'm injecting into my application.

Unfortunately I keep getting a System.AggregateException with a message of

''Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: [MyNameSpace].AppState
  Lifetime: Singleton ImplementationType: [MyNameSpace].AppState':
  Unable to resolve service for type
  'Microsoft.AspNetCore.Http.HttpContextAccessor' while attempting to
  activate '[MyNameSpace].AppState'.)'

My Startup.cs file is as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();

    services.AddHttpContextAccessor();
    services.AddSingleton<AppState>();

    // More services
}

and my AppState.cs file is as follows:

private HttpContextAccessor _httpContextAccessor;

public AppState(HttpContextAccessor httpContextAccessor)
{
     _httpContextAccessor = httpContextAccessor;
}

I've checked online and it seems that just adding the AddHttpContextAccessor and AddSingleton<T> to my ConfigureServices method should do the trick but for some reason it isn't working.

As I'm pretty new to ASP.NET Core and Dependency Injection, I just wanted to see if someone who knows what they are doing has any idea what I'm doing wrong!

Body:
The AddHttpContextAccessor() method registers the service as a IHttpContextAccessor (note the I prefix to denote it is an interface) and that is what your class needs to explicitly accept in it's constructor:

private IHttpContextAccessor _httpContextAccessor;

public AppState(IHttpContextAccessor httpContextAccessor)
{
     _httpContextAccessor = httpContextAccessor;
}

However, you should not be using this from a singleton class. HTTP requests are, unsurprisingly different per request.


问:
Get the cell address when a form button in it is clicked
I've multiple buttons in multiple cells and when any one of them is clicked, I've to perform a function.

I need to know which cell has this clicked button.

答:
My suggestion is to try this:

```<code>Dim r As Range
Set r = ActiveSheet.Shapes(Application.Caller).TopLeftCell
MsgBox r.Address
</code>```

Here you can get the address where the button is placed

Body:
My suggestion is to try this:

Dim r As Range
Set r = ActiveSheet.Shapes(Application.Caller).TopLeftCell
MsgBox r.Address

Here you can get the address where the button is placed


问:
Question about Self Joins. Seeing if two users interacted
I was given a SQL assignment that is the following table simulating a dating app: Table name = dating

```<code>user_id | viewing_profile_id | date | liked
   1              2             x       yes
   1              3             x       yes
   2              1             x       yes
   2              3             x       no
   3              1             x       no
   3              2             x       no
</code>```

essentially I want to see the % of profiles that match each other. a match is when both profiles like each other.

I think I know what I have to do. Perform a Self join onto the table itself and use a case when for when the profiles like each other.

```<code>select t.date, sum(t.match) / count(t.match) as p_match
from (
select s1.user_id, s1.viewing_profile_id,
date_trunc('day',s1.date) as date, case when s1.liked = 'yes'
and s2.liked = 'yes' then 1 else 0 end as match
from dating s1
left join dating s2 on s2.ser_id = s1.viewing_profile_id
group by 1,2) t
group by 1
</code>```

Since this is just a made up table, and I do not have any data execute this on, I was wondering if I can get some insight into whether or not this would work.

I am expecting the subquery to produce something like the following:

```<code>user_id | viewing_profile_id | date | match
   1              2             x       1
   1              3             x       0
   2              1             x       1
   2              3             x       0
   3              1             x       0
   3              2             x       0
</code>```

答:
You need to left self join the table on the conditions you have:

```<code>select
  d1.*,
  case when d2.user_id is null then 0 else 1 end `match`
from dating d1 left join dating d2
on
  d1.user_id = d2.viewing_profile_id
  and d1.viewing_profile_id = d2.user_id
  and d1.liked = 'yes' and d2.liked = 'yes'
order by d1.user_id, d1.viewing_profile_id
</code>```

See the demo.

Results:

```<code>| user_id | viewing_profile_id | date | liked | match |
| ------- | ------------------ | ---- | ----- | ----- |
| 1       | 2                  |      | yes   | 1     |
| 1       | 3                  |      | yes   | 0     |
| 2       | 1                  |      | yes   | 1     |
| 2       | 3                  |      | no    | 0     |
| 3       | 1                  |      | no    | 0     |
| 3       | 2                  |      | no    | 0     |
</code>```

Body:
I was given a SQL assignment that is the following table simulating a dating app: Table name = dating

user_id | viewing_profile_id | date | liked
   1              2             x       yes
   1              3             x       yes
   2              1             x       yes
   2              3             x       no
   3              1             x       no
   3              2             x       no

essentially I want to see the % of profiles that match each other. a match is when both profiles like each other.

I think I know what I have to do. Perform a Self join onto the table itself and use a case when for when the profiles like each other.

select t.date, sum(t.match) / count(t.match) as p_match
from (
select s1.user_id, s1.viewing_profile_id,
date_trunc('day',s1.date) as date, case when s1.liked = 'yes'
and s2.liked = 'yes' then 1 else 0 end as match
from dating s1
left join dating s2 on s2.ser_id = s1.viewing_profile_id
group by 1,2) t
group by 1

Since this is just a made up table, and I do not have any data execute this on, I was wondering if I can get some insight into whether or not this would work.

I am expecting the subquery to produce something like the following:

user_id | viewing_profile_id | date | match
   1              2             x       1
   1              3             x       0
   2              1             x       1
   2              3             x       0
   3              1             x       0
   3              2             x       0

Body:
You need to left self join the table on the conditions you have:

select
  d1.*,
  case when d2.user_id is null then 0 else 1 end `match`
from dating d1 left join dating d2
on
  d1.user_id = d2.viewing_profile_id
  and d1.viewing_profile_id = d2.user_id
  and d1.liked = 'yes' and d2.liked = 'yes'
order by d1.user_id, d1.viewing_profile_id

See the demo.

Results:

| user_id | viewing_profile_id | date | liked | match |
| ------- | ------------------ | ---- | ----- | ----- |
| 1       | 2                  |      | yes   | 1     |
| 1       | 3                  |      | yes   | 0     |
| 2       | 1                  |      | yes   | 1     |
| 2       | 3                  |      | no    | 0     |
| 3       | 1                  |      | no    | 0     |
| 3       | 2                  |      | no    | 0     |


问:
How can I hide section headers in iOS 11?
In iOS 11, my section headers always appear, regardless of whether the items are 0 or more.

On iOS 10 devices, my code works and sections disappear when item count is 0. But on iOS 11, the same code has no affect.

```<code>func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if sections[section].items.count > 0{
        return sections[section].title
    }else{
        return nil
    }
}
</code>```

答:
swift 3, 4 and 4.2

To hide your tableView header

```<code>tableView.tableHeaderView?.frame = CGRect.zero
</code>```

and to show it back

```<code>tableView.tableHeaderView?.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 66)
</code>```

Body:
In iOS 11, my section headers always appear, regardless of whether the items are 0 or more.

On iOS 10 devices, my code works and sections disappear when item count is 0. But on iOS 11, the same code has no affect.

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if sections[section].items.count > 0{
        return sections[section].title
    }else{
        return nil
    }
}

Body:
swift 3, 4 and 4.2

To hide your tableView header

tableView.tableHeaderView?.frame = CGRect.zero

and to show it back

tableView.tableHeaderView?.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 66)


问:
How to write a sum loop with a criteria in excel sheet?
I need to run a loop that checks if cells in column A is not empty then it will take the integer in column B in the same row and sum it to the previous integer, when the cell in column A is empty then it will print the sum in the next row in column B.

X = 0

For myCounter = myRow To 1 Step -1
Do While Not IsEmpty(Cells(myCounter + 1, 1).Value)
    X = Cells (myCounter,10).Value + X
Loop
```

enter image description here

答:
You could try:</p>

```<code>Option Explicit

Sub test()

    Dim LastRow As Long, i As Long

    'Set you sheet
    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        'Start from row 2
        For i = 2 To LastRow

            If Not IsEmpty(.Range("A" & i).Value) Then

                .Range("B" & i - 1).Value = .Range("B" & i).Value + .Range("B" & i - 1).Value

            Else

                .Range("B" & i + 1).Value = .Range("B" & i).Value

            End If

        Next i

    End With

End Sub
</code>```

Body:
I need to run a loop that checks if cells in column A is not empty then it will take the integer in column B in the same row and sum it to the previous integer, when the cell in column A is empty then it will print the sum in the next row in column B.

X = 0

For myCounter = myRow To 1 Step -1
Do While Not IsEmpty(Cells(myCounter + 1, 1).Value)
    X = Cells (myCounter,10).Value + X
Loop

enter image description here

Body:
You could try:

Option Explicit

Sub test()

    Dim LastRow As Long, i As Long

    'Set you sheet
    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        'Start from row 2
        For i = 2 To LastRow

            If Not IsEmpty(.Range("A" & i).Value) Then

                .Range("B" & i - 1).Value = .Range("B" & i).Value + .Range("B" & i - 1).Value

            Else

                .Range("B" & i + 1).Value = .Range("B" & i).Value

            End If

        Next i

    End With

End Sub