问:
My SwiftUI List won't update when my @Published array of NSManagedObjects changes
I'm building a basic notes app where the main page of my app should display a list of the user's notes. A note is represented with the Note class, a Core Data-generated class. (My ultimate goal is a notes app that syncs with CloudKit via NSPersistentCloudKitContainer.)

So far, when a user loads the app, the List displays the correct notes data. However, when I attempt to create a new note by tapping my newNoteButton, the array of Notes changes, but my UI doesn't change. I have to reload the app to see the new note. What could I be doing wrong? Sorry for the messy code below:

NoteList.swift

struct NoteList: View {

  @EnvironmentObject var userNotes: UserNotes

  var newNoteButton: some View {
    Button(action: {
      self.userNotes.createNewNote()
      self.userNotes.objectWillChange.send()
    }) {
      Image(systemName: "plus")
        .imageScale(.large)
        .accessibility(label: Text("New Note"))
    }
  }

  var body: some View {
    NavigationView {
      List {
        ForEach(self.userNotes.notes) { note in
          NavigationLink(destination: NoteDetail(note: self.$userNotes.notes[self.userNotes.notes.firstIndex(of: note)!])) {
            Text(note.unsecuredContent!)
          }
        }
      }
      .navigationBarTitle(Text("Notes"), displayMode: .inline)
      .navigationBarItems(trailing: newNoteButton)
    }
  }

}
```

<p><strong>UserNotes.swift</strong></p>

<pre class="lang-swift prettyprint-override"><code>class UserNotes: NSObject, ObservableObject {

  @Published var notes: [Note] = []

  var managedObjectContext: NSManagedObjectContext? = nil

  var fetchedResultsController: NSFetchedResultsController<Note> {
    if _fetchedResultsController != nil {
      return _fetchedResultsController!
    }

    let fetchRequest: NSFetchRequest<Note> = Note.fetchRequest()

    // Set the batch size to a suitable number.
    fetchRequest.fetchBatchSize = 20

    // Edit the sort key as appropriate.
    let sortDescriptor = NSSortDescriptor(key: "unsecuredContent", ascending: false)

    fetchRequest.sortDescriptors = [sortDescriptor]

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
                                                               managedObjectContext: self.managedObjectContext!,
                                                               sectionNameKeyPath: nil, cacheName: "Master")
    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController

    do {
      try _fetchedResultsController!.performFetch()
    } catch {
      // Replace this implementation with code to handle the error appropriately.
      // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
      let nserror = error as NSError
      fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }

    return _fetchedResultsController!
  }
  var _fetchedResultsController: NSFetchedResultsController<Note>? = nil

  override init() {
    super.init()
    managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    notes = fetchedResultsController.sections![0].objects as! [Note]
  }

  func createNewNote() {
    let newNote = Note(context: managedObjectContext!)

    // If appropriate, configure the new managed object.
    newNote.unsecuredContent = "New CloudKit note"

    // Save the context.
    do {
      try managedObjectContext!.save()
    } catch {
      // Replace this implementation with code to handle the error appropriately.
      // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
      let nserror = error as NSError
      fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }
  }

}

extension UserNotes: NSFetchedResultsControllerDelegate {

  func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    notes = controller.sections![0].objects as! [Note]
  }

}
</code>```

Note.swift (generated by Core Data)

//  This file was automatically generated and should not be edited.
//

import Foundation
import CoreData

@objc(Note)
public class Note: NSManagedObject {

}
```

<p><strong>Note.swift (extension)</strong></p>

<pre class="lang-swift prettyprint-override"><code>extension Note: Identifiable {}
</code>```

答:
With SwiftUI the fetched results controller goes in the View like this:

```<code>@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Note.entity(), sortDescriptors: []) var notes: FetchedResults<Note>

var body: some View {
    VStack{
        List{
            ForEach(notes, id: \.self) { note in
            ...
            }
        }
    }
}
</code>```

You can also do Note(self.moc) to create your new notes right in the View e.g. in a button handler, without the need of that helper class.

Body:
I'm building a basic notes app where the main page of my app should display a list of the user's notes. A note is represented with the Note class, a Core Data-generated class. (My ultimate goal is a notes app that syncs with CloudKit via NSPersistentCloudKitContainer.)

So far, when a user loads the app, the List displays the correct notes data. However, when I attempt to create a new note by tapping my newNoteButton, the array of Notes changes, but my UI doesn't change. I have to reload the app to see the new note. What could I be doing wrong? Sorry for the messy code below:

NoteList.swift

struct NoteList: View {

  @EnvironmentObject var userNotes: UserNotes

  var newNoteButton: some View {
    Button(action: {
      self.userNotes.createNewNote()
      self.userNotes.objectWillChange.send()
    }) {
      Image(systemName: "plus")
        .imageScale(.large)
        .accessibility(label: Text("New Note"))
    }
  }

  var body: some View {
    NavigationView {
      List {
        ForEach(self.userNotes.notes) { note in
          NavigationLink(destination: NoteDetail(note: self.$userNotes.notes[self.userNotes.notes.firstIndex(of: note)!])) {
            Text(note.unsecuredContent!)
          }
        }
      }
      .navigationBarTitle(Text("Notes"), displayMode: .inline)
      .navigationBarItems(trailing: newNoteButton)
    }
  }

}

UserNotes.swift

class UserNotes: NSObject, ObservableObject {

  @Published var notes: [Note] = []

  var managedObjectContext: NSManagedObjectContext? = nil

  var fetchedResultsController: NSFetchedResultsController<Note> {
    if _fetchedResultsController != nil {
      return _fetchedResultsController!
    }

    let fetchRequest: NSFetchRequest<Note> = Note.fetchRequest()

    // Set the batch size to a suitable number.
    fetchRequest.fetchBatchSize = 20

    // Edit the sort key as appropriate.
    let sortDescriptor = NSSortDescriptor(key: "unsecuredContent", ascending: false)

    fetchRequest.sortDescriptors = [sortDescriptor]

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
                                                               managedObjectContext: self.managedObjectContext!,
                                                               sectionNameKeyPath: nil, cacheName: "Master")
    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController

    do {
      try _fetchedResultsController!.performFetch()
    } catch {
      // Replace this implementation with code to handle the error appropriately.
      // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
      let nserror = error as NSError
      fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }

    return _fetchedResultsController!
  }
  var _fetchedResultsController: NSFetchedResultsController<Note>? = nil

  override init() {
    super.init()
    managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    notes = fetchedResultsController.sections![0].objects as! [Note]
  }

  func createNewNote() {
    let newNote = Note(context: managedObjectContext!)

    // If appropriate, configure the new managed object.
    newNote.unsecuredContent = "New CloudKit note"

    // Save the context.
    do {
      try managedObjectContext!.save()
    } catch {
      // Replace this implementation with code to handle the error appropriately.
      // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
      let nserror = error as NSError
      fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }
  }

}

extension UserNotes: NSFetchedResultsControllerDelegate {

  func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    notes = controller.sections![0].objects as! [Note]
  }

}

Note.swift (generated by Core Data)

//  This file was automatically generated and should not be edited.
//

import Foundation
import CoreData

@objc(Note)
public class Note: NSManagedObject {

}

Note.swift (extension)

extension Note: Identifiable {}

Body:
With SwiftUI the fetched results controller goes in the View like this:

@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Note.entity(), sortDescriptors: []) var notes: FetchedResults<Note>

var body: some View {
    VStack{
        List{
            ForEach(notes, id: \.self) { note in
            ...
            }
        }
    }
}

You can also do Note(self.moc) to create your new notes right in the View e.g. in a button handler, without the need of that helper class.


来源: stackexchange

问:
put value of different keys to a single array
I have the following array of objects:

```<code>[
  {
    "name": "product1",
    "Jan": 3,
    "Feb": 2,
    "Mar": 0,
    "Apr": 1,
    "May": 3,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  },
  {
    "name": "product2",
    "Jan": 4,
    "Feb": 0,
    "Mar": 0,
    "Apr": 1,
    "May": 1,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  }
]
</code>```

I would like to pass the value of all the months to a single array respecting the order of the months as follows:

```<code>[
  {
    "name": "product1",
    "data": [3, 2, 0, 1, 3, 0, 0, 0, 5, 0, 0, 0],
  },
  {
    "name": "product2",
    "data": [4, 0, 0, 1, 1, 0, 0, 0, 5, 0, 0, 0],
  }
]
</code>```

so how can i do this?

答:
let data = [{
    "name": "product1",
    "Jan": 3,
    "Feb": 2,
    "Mar": 0,
    "Apr": 1,
    "May": 3,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  },
  {
    "name": "product2",
    "Jan": 4,
    "Feb": 0,
    "Mar": 0,
    "Apr": 1,
    "May": 1,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  }
];

function GetData(data) {
  let res = [];
  for (let i = 0; i < data.length; i++) {
    res[i] = {};
    res[i].name = data[i].name;
    res[i].data = [];
    for (let item in data[i]) {
      if (item != "name") {
        res[i].data.push(data[i][item]);
      }
    }
  }
  return res;
}

console.log(GetData(data));```

ContentLicense: CC BY-SA 4.0

Body:
I have the following array of objects:

[
  {
    "name": "product1",
    "Jan": 3,
    "Feb": 2,
    "Mar": 0,
    "Apr": 1,
    "May": 3,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  },
  {
    "name": "product2",
    "Jan": 4,
    "Feb": 0,
    "Mar": 0,
    "Apr": 1,
    "May": 1,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  }
]

I would like to pass the value of all the months to a single array respecting the order of the months as follows:

[
  {
    "name": "product1",
    "data": [3, 2, 0, 1, 3, 0, 0, 0, 5, 0, 0, 0],
  },
  {
    "name": "product2",
    "data": [4, 0, 0, 1, 1, 0, 0, 0, 5, 0, 0, 0],
  }
]

so how can i do this?


问:
What's the point of providing input and output operands if they are not specified in ASM template?
I found the following piece of code in u-boot/arch/arm/lib/semihosting.c that uses bkpt and other instructions and provides input and output operands even though they are not specified in the ASM template:

```<code>static noinline long smh_trap(unsigned int sysnum, void *addr)
{
    register long result asm("r0");
#if defined(CONFIG_ARM64)
    asm volatile ("hlt #0xf000" : "=r" (result) : "0"(sysnum), "r"(addr));
#elif defined(CONFIG_CPU_V7M)
    asm volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));
#else
    /* Note - untested placeholder */
    asm volatile ("svc #0x123456" : "=r" (result) : "0"(sysnum), "r"(addr));
#endif
    return result;
}
</code>```

Minimal, verifiable example:

```<code>#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  register long result asm("r0");
  void *addr = 0;
  unsigned int sysnum = 0;
  __asm__ volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));

  return EXIT_SUCCESS;
}
</code>```

According to ARM Architecture Reference Manual bkpt instruction
takes a single imm parameter and according to my reading of GCC manual
section on inline assembly GCC does not allow providing operands if they
are not specified in the template.  Output assembly generated with -S:

```<code>    .arch armv6
    .eabi_attribute 28, 1
    .eabi_attribute 20, 1
    .eabi_attribute 21, 1
    .eabi_attribute 23, 3
    .eabi_attribute 24, 1
    .eabi_attribute 25, 1
    .eabi_attribute 26, 2
    .eabi_attribute 30, 6
    .eabi_attribute 34, 1
    .eabi_attribute 18, 4
    .file   "bkpt-so.c"
    .text
    .align  2
    .global main
    .arch armv6
    .syntax unified
    .arm
    .fpu vfp
    .type   main, %function
main:
    @ args = 0, pretend = 0, frame = 8
    @ frame_needed = 1, uses_anonymous_args = 0
    @ link register save eliminated.
    str fp, [sp, #-4]!
    add fp, sp, #0
    sub sp, sp, #12
    mov r3, #0
    str r3, [fp, #-8]
    mov r3, #0
    str r3, [fp, #-12]
    ldr r2, [fp, #-12]
    ldr r3, [fp, #-8]
    mov r0, r2
    .syntax divided
@ 10 "bkpt-so.c" 1
    bkpt #0xAB
@ 0 "" 2
    .arm
    .syntax unified
    mov r3, #0
    mov r0, r3
    add sp, fp, #0
    @ sp needed
    ldr fp, [sp], #4
    bx  lr
    .size   main, .-main
    .ident  "GCC: (Raspbian 8.3.0-6+rpi1) 8.3.0"
    .section    .note.GNU-stack,"",%progbits
</code>```

So what's the point of "=r" (result) : "0"(sysnum), "r"(addr) in this line:

```<code>__asm__ volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));
</code>```

?

答: These instructions are used to invoke kernel (or hypervisor) from userspace code (i.e. perform a syscall). They cause CPU to emit a trap which is intercepted and handled by the kernel. Additional data passed in predefined registers (r0 and r1 in this case) holds "parameters" for kernel's trap handler.

Body:
I found the following piece of code in u-boot/arch/arm/lib/semihosting.c that uses bkpt and other instructions and provides input and output operands even though they are not specified in the ASM template:

static noinline long smh_trap(unsigned int sysnum, void *addr)
{
    register long result asm("r0");
#if defined(CONFIG_ARM64)
    asm volatile ("hlt #0xf000" : "=r" (result) : "0"(sysnum), "r"(addr));
#elif defined(CONFIG_CPU_V7M)
    asm volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));
#else
    /* Note - untested placeholder */
    asm volatile ("svc #0x123456" : "=r" (result) : "0"(sysnum), "r"(addr));
#endif
    return result;
}

Minimal, verifiable example:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  register long result asm("r0");
  void *addr = 0;
  unsigned int sysnum = 0;
  __asm__ volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));

  return EXIT_SUCCESS;
}

According to ARM Architecture Reference Manual bkpt instruction
takes a single imm parameter and according to my reading of GCC manual
section on inline assembly GCC does not allow providing operands if they
are not specified in the template.  Output assembly generated with -S:

    .arch armv6
    .eabi_attribute 28, 1
    .eabi_attribute 20, 1
    .eabi_attribute 21, 1
    .eabi_attribute 23, 3
    .eabi_attribute 24, 1
    .eabi_attribute 25, 1
    .eabi_attribute 26, 2
    .eabi_attribute 30, 6
    .eabi_attribute 34, 1
    .eabi_attribute 18, 4
    .file   "bkpt-so.c"
    .text
    .align  2
    .global main
    .arch armv6
    .syntax unified
    .arm
    .fpu vfp
    .type   main, %function
main:
    @ args = 0, pretend = 0, frame = 8
    @ frame_needed = 1, uses_anonymous_args = 0
    @ link register save eliminated.
    str fp, [sp, #-4]!
    add fp, sp, #0
    sub sp, sp, #12
    mov r3, #0
    str r3, [fp, #-8]
    mov r3, #0
    str r3, [fp, #-12]
    ldr r2, [fp, #-12]
    ldr r3, [fp, #-8]
    mov r0, r2
    .syntax divided
@ 10 "bkpt-so.c" 1
    bkpt #0xAB
@ 0 "" 2
    .arm
    .syntax unified
    mov r3, #0
    mov r0, r3
    add sp, fp, #0
    @ sp needed
    ldr fp, [sp], #4
    bx  lr
    .size   main, .-main
    .ident  "GCC: (Raspbian 8.3.0-6+rpi1) 8.3.0"
    .section    .note.GNU-stack,"",%progbits

So what's the point of "=r" (result) : "0"(sysnum), "r"(addr) in this line:

__asm__ volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));

?


问:
List of installable Homebrew casks
Is there a way to obtain a list (possibly with descriptions) of all the casks installable with Homebrew Cask?</p>

答:
Multiple ways to do, collating different answers:

1.

```<code>for cask in $(brew search ''); do
brew info $cask; done
</code>```

brew search --casks

brew search

You could one-line it to put results into file for later (because its really slow querying packages one by one):

```<code>for cask in $(brew search ''); do brew info $cask; echo "==="; done > list_of_casks.txt
</code>```

Title: List of installable Homebrew casks

Body:
Multiple ways to do, collating different answers:

1.

for cask in $(brew search ''); do
brew info $cask; done

brew search --casks

brew search

You could one-line it to put results into file for later (because its really slow querying packages one by one):

for cask in $(brew search ''); do brew info $cask; echo "==="; done > list_of_casks.txt


问:
Calling the variable property directly vs getter/setters - OOP Design
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

```<code>class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();
</code>```

Suggested Optimization:

```<code>$rover = new dog();
$rover->name = 'rover';
echo $rover->name;
</code>```

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?

答:
You could also use the __get and __set magic methods:</p>

```<code>class Example
{
    private $allowedProps = array('prop1', 'prop2', 'prop3');
    private $data = array();

    public function __set($propName, $propValue)
    {
        if (in_array($propName, $this->allowedProps))
        {
            $this->data[$propName] = $propValue;
        }
        else
        {
            // error
        }
    }

    public function __get($propName)
    {
        if (array_key_exists($propName, $this->data))
        {
            return $this->data[$propName];
        }
        else
        {
            // error
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();

Suggested Optimization:

$rover = new dog();
$rover->name = 'rover';
echo $rover->name;

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?

Body:
You could also use the __get and __set magic methods:

class Example
{
    private $allowedProps = array('prop1', 'prop2', 'prop3');
    private $data = array();

    public function __set($propName, $propValue)
    {
        if (in_array($propName, $this->allowedProps))
        {
            $this->data[$propName] = $propValue;
        }
        else
        {
            // error
        }
    }

    public function __get($propName)
    {
        if (array_key_exists($propName, $this->data))
        {
            return $this->data[$propName];
        }
        else
        {
            // error
        }
    }
}


问:
Do a search on more than one table in laravel method request
In my project I managed to do a search via request and I wanted to do a search filtered by name (in this case already) and also by reference.
I looked on the internet and nothing that helps me up so far.
I appreciate your help:\</p>

```<code>else {
            $valida=2;
            $produtc = Produtos::where('nome' & 'refencia', 'like', "%{$tpesquisa}%")->paginate();
            $nrr = count($produtos);
            $msgm = 'Pesquisa concluida com sucesso, foram econtrados ' .$nrr. ' resultados';

            return view('pesquisa', compact('produtc', 'msgm', 'nrr', 'valida'));
</code>```

答:
You are doing it wrong please try with the following way.

```<code>else {
        $valida=2;
        $produtc = Produtos::where('nome', 'like', "%".$tpesquisa."%")->orWhere('refencia','like', "%".$tpesquisa."%")->paginate();
        $nrr = count($produtos);
        $msgm = 'Pesquisa concluida com sucesso, foram econtrados ' .$nrr. ' resultados';

        return view('pesquisa', compact('produtc', 'msgm', 'nrr', 'valida'));
</code>```

If you want to do it using AND operator then use following code.

```<code>else {
        $valida=2;
        $produtc = Produtos::where('nome', 'like', "%".$tpesquisa."%")->where('refencia','like', "%".$tpesquisa."%")->paginate();
        $nrr = count($produtos);
        $msgm = 'Pesquisa concluida com sucesso, foram econtrados ' .$nrr. ' resultados';

        return view('pesquisa', compact('produtc', 'msgm', 'nrr', 'valida'));
</code>```

Body:
In my project I managed to do a search via request and I wanted to do a search filtered by name (in this case already) and also by reference.
I looked on the internet and nothing that helps me up so far.
I appreciate your help:\

else {
            $valida=2;
            $produtc = Produtos::where('nome' & 'refencia', 'like', "%{$tpesquisa}%")->paginate();
            $nrr = count($produtos);
            $msgm = 'Pesquisa concluida com sucesso, foram econtrados ' .$nrr. ' resultados';

            return view('pesquisa', compact('produtc', 'msgm', 'nrr', 'valida'));

Body:
You are doing it wrong please try with the following way.

else {
        $valida=2;
        $produtc = Produtos::where('nome', 'like', "%".$tpesquisa."%")->orWhere('refencia','like', "%".$tpesquisa."%")->paginate();
        $nrr = count($produtos);
        $msgm = 'Pesquisa concluida com sucesso, foram econtrados ' .$nrr. ' resultados';

        return view('pesquisa', compact('produtc', 'msgm', 'nrr', 'valida'));

If you want to do it using AND operator then use following code.

else {
        $valida=2;
        $produtc = Produtos::where('nome', 'like', "%".$tpesquisa."%")->where('refencia','like', "%".$tpesquisa."%")->paginate();
        $nrr = count($produtos);
        $msgm = 'Pesquisa concluida com sucesso, foram econtrados ' .$nrr. ' resultados';

        return view('pesquisa', compact('produtc', 'msgm', 'nrr', 'valida'));


问:
How to connect with different tables depending on parameter
I have model Board and BoardController where i can find all boards of my project.
All records have filled "board_layout" column with enum.

Now i have show method in BoardController and i want to load there different data from different table depending on board_layout column value.

I could do it like this:

```<code>def show
  @board = Board.find(params[:id])
  if @board.board_layout == 1
    @tasks = Car.where(board_id: @board.id)
  elsif @board.board_layout == 2
    @tasks = Truck.where(board_id: @board.id)
  end
end
</code>```

But it's not elegant + it is not DRY (i need to use some sort of if statement anytime when i want to do something with those 2 tables).

So i have tried to create Concern and create case statement inside, now it looks like:

```<code>def show
  @board = Board.find(params[:id])
  @tasks = get_class_name(@board.board_layout).where(board_id: @board.id)
end

# inside my concern
def get_class_name(scope)
  case scope
  when 1
    Car
  when 2
    Truck
  end
end
</code>```

My Question:
Is there better way to do it? Is my solution safe and clear?
What is the best solution to resolve problem like this?

I would appreciate any help.

答:
maybe you can abstract that out into a class, so you can define multiple layout and their correspondent classes, like:

```<code>class LayoutClassGetter
  CLASS_BY_LAYOUT = { '1' => Car, '2' => Truck }.freeze

  def initialize(layout_number)
    @layout_number = layout_number
  end

  def layout_class
   CLASS_BY_LAYOUT[@layout_number]
  end

  def self.layout_class(layout_number)
    new(layout_number).layout
  end
end
</code>```

And then use it:

```<code>def show
  @board = Board.find(params[:id])
  @tasks = layout_class(@board.board_layout).where(board_id: @board.id)
end

def layout_class(scope)
  LayoutClassGetter.layout_class(scope)
end
</code>```

Body:
I have model Board and BoardController where i can find all boards of my project.
All records have filled "board_layout" column with enum.

Now i have show method in BoardController and i want to load there different data from different table depending on board_layout column value.

I could do it like this:

def show
  @board = Board.find(params[:id])
  if @board.board_layout == 1
    @tasks = Car.where(board_id: @board.id)
  elsif @board.board_layout == 2
    @tasks = Truck.where(board_id: @board.id)
  end
end

But it's not elegant + it is not DRY (i need to use some sort of if statement anytime when i want to do something with those 2 tables).

So i have tried to create Concern and create case statement inside, now it looks like:

def show
  @board = Board.find(params[:id])
  @tasks = get_class_name(@board.board_layout).where(board_id: @board.id)
end

# inside my concern
def get_class_name(scope)
  case scope
  when 1
    Car
  when 2
    Truck
  end
end

My Question:
Is there better way to do it? Is my solution safe and clear?
What is the best solution to resolve problem like this?

I would appreciate any help.

Body:
maybe you can abstract that out into a class, so you can define multiple layout and their correspondent classes, like:

class LayoutClassGetter
  CLASS_BY_LAYOUT = { '1' => Car, '2' => Truck }.freeze

  def initialize(layout_number)
    @layout_number = layout_number
  end

  def layout_class
   CLASS_BY_LAYOUT[@layout_number]
  end

  def self.layout_class(layout_number)
    new(layout_number).layout
  end
end

And then use it:

def show
  @board = Board.find(params[:id])
  @tasks = layout_class(@board.board_layout).where(board_id: @board.id)
end

def layout_class(scope)
  LayoutClassGetter.layout_class(scope)
end


问:
Laravel 7 make relation to found out who invited me
in my web application each can be have unlimited user like with networking system. i can found which user registered with user ref code, but i want to know who is my parent and invited me to register

for example this code can be return how many user registered with my ref code:

```<code>$users = User::whereNull('user_id')->with('child')->get();
</code>```

model:

```<code>public function child()
{
    return $this->hasMany(User::class)->with('child');
}
</code>```

how can i found out who is parent of child? like with from tree branch to root

User migration file:

```<code>Schema::create('users', function (Blueprint $table) {
    $table->id();

    $table->string('name')->nullable();
    $table->string('family')->nullable();
    $table->string('username')->unique();

    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->index()->nullable();

    $table->unsignedBigInteger('user_id')->index()->nullable();
    $table->foreign('user_id')->references('id')->on('users');

    $table->string('password');

    $table->rememberToken();
    $table->softDeletes();
    $table->timestamp('created_at')->useCurrent();
    $table->timestamp('updated_at')->useCurrent();
});
</code>```

User model:

```<code>class User extends Authenticatable
{
    use Notifiable, SoftDeletes;

    protected $guarded = [
        'id',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime'
    ];

    public function users()
    {
        return $this->hasMany(User::class)->with('users');
    }
}
</code>```

答:
To get the parents

```<code>{
    return $this->belongsTo(User::class, 'user_id');
}
</code>```

To get the childs

```<code>{
    return $this->hasMany(User::class, 'user_id', 'id');
}
</code>```

Body:
in my web application each can be have unlimited user like with networking system. i can found which user registered with user ref code, but i want to know who is my parent and invited me to register

for example this code can be return how many user registered with my ref code:

$users = User::whereNull('user_id')->with('child')->get();

model:

public function child()
{
    return $this->hasMany(User::class)->with('child');
}

how can i found out who is parent of child? like with from tree branch to root

User migration file:

Schema::create('users', function (Blueprint $table) {
    $table->id();

    $table->string('name')->nullable();
    $table->string('family')->nullable();
    $table->string('username')->unique();

    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->index()->nullable();

    $table->unsignedBigInteger('user_id')->index()->nullable();
    $table->foreign('user_id')->references('id')->on('users');

    $table->string('password');

    $table->rememberToken();
    $table->softDeletes();
    $table->timestamp('created_at')->useCurrent();
    $table->timestamp('updated_at')->useCurrent();
});

User model:

class User extends Authenticatable
{
    use Notifiable, SoftDeletes;

    protected $guarded = [
        'id',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime'
    ];

    public function users()
    {
        return $this->hasMany(User::class)->with('users');
    }
}

Body:
To get the parents

{
    return $this->belongsTo(User::class, 'user_id');
}

To get the childs

{
    return $this->hasMany(User::class, 'user_id', 'id');
}


问:
Javascript prevent question mark input
I have a input box where I am allowing users to use alphabets, arrow, home, del etc keys. I want to prevent users to enter "?" question mark.

Here is my code:

```<code>$(document).on('keydown', "#element", function(e) {
    var key = e.which || e.keyCode;
     if (!e.altKey && !e.ctrlKey &&
     // Alphabets
        key >= 65 && key <= 120 ||
     // Backspace and Tab and Enter
        key == 8 || key == 9 || key == 13 ||
     // Home and End
        key == 35 || key == 36 ||
     // left and right arrows
        key == 37 || key == 39 || key == 50 || key == 191 ||
     // Del and Ins
        key == 46 || key == 45)
         return true;
     return false;
});
</code>```

I know that "/" key code is 191. I am unable to prevent the question mark input. How can I do that? Any help please.

答:
Since you know the key code is 191, you just need to check if the shift key was being pressed at the same time.

```<code>if (e.shiftKey && key === 191)
</code>```

So, in your code, you can just add (e.shiftKey && key === 191).

Title: Javascript prevent question mark input

Body:
I have a input box where I am allowing users to use alphabets, arrow, home, del etc keys. I want to prevent users to enter "?" question mark.

Here is my code:

$(document).on('keydown', "#element", function(e) {
    var key = e.which || e.keyCode;
     if (!e.altKey && !e.ctrlKey &&
     // Alphabets
        key >= 65 && key <= 120 ||
     // Backspace and Tab and Enter
        key == 8 || key == 9 || key == 13 ||
     // Home and End
        key == 35 || key == 36 ||
     // left and right arrows
        key == 37 || key == 39 || key == 50 || key == 191 ||
     // Del and Ins
        key == 46 || key == 45)
         return true;
     return false;
});

I know that "/" key code is 191. I am unable to prevent the question mark input. How can I do that? Any help please.

Body:
Since you know the key code is 191, you just need to check if the shift key was being pressed at the same time.

if (e.shiftKey && key === 191)

So, in your code, you can just add (e.shiftKey && key === 191).


问:
Proper structure of AJAX handler
My .NET project handles AJAX requests.  There are no UI controls at all, it simply responds with text to every AJAX post.

This is my current structure:

```<code><%
SynchLock DBNull.Value
  Main
End SynchLock
%>

<script language="VB" runat="Server">

Sub Main
  Dim a() As String = Request.Form("a").Split(" "c)
  ' a: (0) version, (1) config, (2) userid, (3) sessionid, (4) activity

  ' Initializations

  Using conn As DbConnection = sess.Connection
    Select Case a(4)
    Case 0
      ActivityOne
    Case 1
      ActivityTwo
    Case 2
      ActivityThree
    ...
    Case 28
      ActivityTwentyEight
    End Select
  End Using
End Sub

'All the activity functions and lots of other Functions

</script>
</code>```

This works but I think it can be improved; I'm not sure how to proceed.

Some of the activities call subfunctions and I'm looking at breaking some of the activities out even further.  In order to encapsulate all the functionality of an activity, I'm considering changing the activities from functions to classes, like so:

```<code>Select Case a(4)
Case 0
  Dim a1 As New ActivityOne
  a1.Execute
...
End Select
</code>```

Is this the right approach?  If I proceed with the classes, I have related questions:

(1) Do I code the "New" Sub of the classes or an "Execute" (or some other name) Sub?  If I code the "New" Sub, then I can reduce the above code to:

```<code>Select Case a(4)
Case 0
  New ActivityOne
...
End Select
</code>```

This seems easier, but are there disadvantages?

(2) The activities all rely on other Request.Form inputs.  Do I (a) pass access the HttpContext.Current object from within the classes or (b) pass the Request object to the activity or (c) pass the specific Request.Form variables needed by the activity?

e.g.

(a) New ActivityOne ' the class accesses HttpContext.Current.Form("b"), etc.

```<code>Class ActivityOne
  Sub New
    Dim p1 As String = HttpContext.Current.Form("b")
    ...
  End Sub
End Class
</code>```

(b) New ActivityOne(Request)

```<code>Class ActivityOne
  Sub New(req As HttpRequest)
    Dim p1 As String = req.Form("b")
    ...
  End Sub
End Class
</code>```

(c) New ActivityOne(Request.Form("b"))

```<code>Class ActivityOne
  Sub New(p1 As String)
    ...
  End Sub
End Class
</code>```

答:
You shouldn't use ASPX pages for AJAX requests. Just use an HTTPHandler.

http://msdn.microsoft.com/en-us/library/system.web.ihttphandler(v=VS.90).aspx

Title: Proper structure of AJAX handler

Body:
My .NET project handles AJAX requests.  There are no UI controls at all, it simply responds with text to every AJAX post.

This is my current structure:

<%
SynchLock DBNull.Value
  Main
End SynchLock
%>

This works but I think it can be improved; I'm not sure how to proceed.

Some of the activities call subfunctions and I'm looking at breaking some of the activities out even further.  In order to encapsulate all the functionality of an activity, I'm considering changing the activities from functions to classes, like so:

Select Case a(4)
Case 0
  Dim a1 As New ActivityOne
  a1.Execute
...
End Select

Is this the right approach?  If I proceed with the classes, I have related questions:

(1) Do I code the "New" Sub of the classes or an "Execute" (or some other name) Sub?  If I code the "New" Sub, then I can reduce the above code to:

Select Case a(4)
Case 0
  New ActivityOne
...
End Select

This seems easier, but are there disadvantages?

(2) The activities all rely on other Request.Form inputs.  Do I (a) pass access the HttpContext.Current object from within the classes or (b) pass the Request object to the activity or (c) pass the specific Request.Form variables needed by the activity?

e.g.

(a) New ActivityOne ' the class accesses HttpContext.Current.Form("b"), etc.

Class ActivityOne
  Sub New
    Dim p1 As String = HttpContext.Current.Form("b")
    ...
  End Sub
End Class

(b) New ActivityOne(Request)

Class ActivityOne
  Sub New(req As HttpRequest)
    Dim p1 As String = req.Form("b")
    ...
  End Sub
End Class

(c) New ActivityOne(Request.Form("b"))

Class ActivityOne
  Sub New(p1 As String)
    ...
  End Sub
End Class


问:
Can I put all the information for a DocuSign envelope into a Word document without using the DocuSign API?
I would like to mark up an MS Word document with all of the information necessary to upload to DocuSign. Specifically, I want to include all the information required for the DocuSign envelope, and also the places where the signatures need to go. I then want to upload that document, either via the API, or the DocuSign web site, and not have any further need to specify the envelope or the signature locations - I would like my markup to be recognised by DocuSign and acted on without any further interaction. It would, of course, mean that there needs to be some way of conveying to DocuSign what this markup is, or else to conform to some pre-defined DocuSign markup.

I have spoken to DocuSign support and they don't really understand the question, but maybe someone here has tried it, or can give a definitive answer as to whether I am asking for a feature that does or does not exist.

If that feature is not there, then we will build it using the DocuSign API, but if there is a wheel, we don't want to reinvent it.

答:
Two solutions I can offer you: (1) You could make use of the DocuSign template feature. In my opinion, this is the path of least resistance. (2) You could also provide your document in html markup by leveraging our responsive signing feature.

Creating and sending a DocuSign Template:

First, you can create your template in the DocuSign UI. I suggest this over the API because it very clearly illustrates the variety of features and functions you can enable. You'll also get a good sense of what your end-user will see. Once you have your template created, we will reference it repeatedly later using the API.

To build your first template:

Log into your docusign demo account.

Navigate to "Templates" and create a new template

Upload your word document and populate the other information

Add Recipient roles to your envelope (Ex. Legal, Hiring Manager, etc)

Click Next

In the tagger, drag and drop the tabs that correspond to your document fields

Click Finish

Before leaving the UI, return to your "Template" view and click on
your template

Select the "i" icon, and save your templateId for later use.

Now that you have your template created, let's go ahead and quickly create an envelope that uses our new template.

```<code>POST /envelopes
{
    "status": "sent",
    "templateId": "00df08bf-xxx-xxx-xxx-ecaa2360c121",
    "templateRoles": [
        {
            "email": "test@test.com",
            "name": "Test User",
            "roleName": "signer",
            "routingOrder": "1",
        },
        {
            "email": "test2@test.com",
            "name": "EFG",
            "roleName": "cc",
            "routingOrder": "2"
        }
    ]
}
</code>```

Notice that the only required information is templateID, status, and the recipient's information.

Body:
Two solutions I can offer you: (1) You could make use of the DocuSign template feature. In my opinion, this is the path of least resistance. (2) You could also provide your document in html markup by leveraging our responsive signing feature.

Creating and sending a DocuSign Template:

First, you can create your template in the DocuSign UI. I suggest this over the API because it very clearly illustrates the variety of features and functions you can enable. You'll also get a good sense of what your end-user will see. Once you have your template created, we will reference it repeatedly later using the API.

To build your first template:

Log into your docusign demo account.

Navigate to "Templates" and create a new template

Upload your word document and populate the other information

Add Recipient roles to your envelope (Ex. Legal, Hiring Manager, etc)

Click Next

In the tagger, drag and drop the tabs that correspond to your document fields

Click Finish

Before leaving the UI, return to your "Template" view and click on
your template

Select the "i" icon, and save your templateId for later use.

Now that you have your template created, let's go ahead and quickly create an envelope that uses our new template.

POST /envelopes
{
    "status": "sent",
    "templateId": "00df08bf-xxx-xxx-xxx-ecaa2360c121",
    "templateRoles": [
        {
            "email": "test@test.com",
            "name": "Test User",
            "roleName": "signer",
            "routingOrder": "1",
        },
        {
            "email": "test2@test.com",
            "name": "EFG",
            "roleName": "cc",
            "routingOrder": "2"
        }
    ]
}

Notice that the only required information is templateID, status, and the recipient's information.


问:
How to zip folders & subfolders with files in it in Kotlin using ZipOutputStream?
I have list of files arranges in different directories, some directories will have sub-directories and files in it. I am not able to successfully put same directory structure within a zip file. Here is my code: </p>

```<code>fun zipAll(directory: String, zipFile: String) {
val sourceFile = File(directory)

 ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))).use {
       zipFiles(it, sourceFile)
   }
}

private fun zipFiles(zipOut: ZipOutputStream, directory: File) {

val data = ByteArray(1024)

zipOut.use {

    if (directory.isDirectory) {
        //Adding directory
        it.putNextEntry(ZipEntry(directory.name))
    } else {
        zipFiles(zipOut, directory)
    }

    for (f in directory.listFiles()) {

        if (!f.name.contains(".zip") && f.exists()) {

            //Adding file

            FileInputStream(f).use { fi ->
                BufferedInputStream(fi).use { origin ->
                    val entry = ZipEntry(f.name)
                    it.putNextEntry(entry)
                    while (true) {
                        val readBytes = origin.read(data)
                        if (readBytes == -1) {
                            break
                        }
                        it.write(data, 0, readBytes)
                    }
                }
            }
        }
    }
}
}
</code>```

答:
This is my complete solution. It don't ignore zip unlike Umair Adil version and also respect folder hierarchy like Jeyhey patch</p>
```<code>fun zipAll(directory: String, zipFile: String) {
    val sourceFile = File(directory)

    ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))).use {
        zipFiles(it, sourceFile, "")
    }
}

private fun zipFiles(zipOut: ZipOutputStream, sourceFile: File, parentDirPath: String) {
    val data = ByteArray(2048)
    sourceFile.listFiles()?.forEach { f ->
        if (f.isDirectory) {
            val path = if (parentDirPath == "") {
                f.name
            } else {
                parentDirPath + File.separator + f.name
            }
            val entry = ZipEntry(path + File.separator)
            entry.time = f.lastModified()
            entry.isDirectory
            entry.size = f.length()
            zipOut.putNextEntry(entry)
            //Call recursively to add files within this directory
            zipFiles(zipOut, f, path)
        } else {
            FileInputStream(f).use { fi ->
                BufferedInputStream(fi).use { origin ->
                    val path = parentDirPath + File.separator + f.name
                    val entry = ZipEntry(path)
                    entry.time = f.lastModified()
                    entry.isDirectory
                    entry.size = f.length()
                    zipOut.putNextEntry(entry)
                    while (true) {
                        val readBytes = origin.read(data)
                        if (readBytes == -1) {
                            break
                        }
                        zipOut.write(data, 0, readBytes)
                    }
                }
            }
        }
    }
}
</code>```

Body:
I have list of files arranges in different directories, some directories will have sub-directories and files in it. I am not able to successfully put same directory structure within a zip file. Here is my code:

fun zipAll(directory: String, zipFile: String) {
val sourceFile = File(directory)

 ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))).use {
       zipFiles(it, sourceFile)
   }
}

private fun zipFiles(zipOut: ZipOutputStream, directory: File) {

val data = ByteArray(1024)

zipOut.use {

    if (directory.isDirectory) {
        //Adding directory
        it.putNextEntry(ZipEntry(directory.name))
    } else {
        zipFiles(zipOut, directory)
    }

    for (f in directory.listFiles()) {

        if (!f.name.contains(".zip") && f.exists()) {

            //Adding file

            FileInputStream(f).use { fi ->
                BufferedInputStream(fi).use { origin ->
                    val entry = ZipEntry(f.name)
                    it.putNextEntry(entry)
                    while (true) {
                        val readBytes = origin.read(data)
                        if (readBytes == -1) {
                            break
                        }
                        it.write(data, 0, readBytes)
                    }
                }
            }
        }
    }
}
}

Body:
This is my complete solution. It don't ignore zip unlike Umair Adil version and also respect folder hierarchy like Jeyhey patch

fun zipAll(directory: String, zipFile: String) {
    val sourceFile = File(directory)

    ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))).use {
        zipFiles(it, sourceFile, "")
    }
}

private fun zipFiles(zipOut: ZipOutputStream, sourceFile: File, parentDirPath: String) {
    val data = ByteArray(2048)
    sourceFile.listFiles()?.forEach { f ->
        if (f.isDirectory) {
            val path = if (parentDirPath == "") {
                f.name
            } else {
                parentDirPath + File.separator + f.name
            }
            val entry = ZipEntry(path + File.separator)
            entry.time = f.lastModified()
            entry.isDirectory
            entry.size = f.length()
            zipOut.putNextEntry(entry)
            //Call recursively to add files within this directory
            zipFiles(zipOut, f, path)
        } else {
            FileInputStream(f).use { fi ->
                BufferedInputStream(fi).use { origin ->
                    val path = parentDirPath + File.separator + f.name
                    val entry = ZipEntry(path)
                    entry.time = f.lastModified()
                    entry.isDirectory
                    entry.size = f.length()
                    zipOut.putNextEntry(entry)
                    while (true) {
                        val readBytes = origin.read(data)
                        if (readBytes == -1) {
                            break
                        }
                        zipOut.write(data, 0, readBytes)
                    }
                }
            }
        }
    }
}


问:
interact.js for vue component
up until now I had two boards between which someone could drag 'n drop cards.
Now I want to try out interact.js as it sounds like a nice and well maintained library.
As I am using vue for my project I am now a bit confused about how to tackle this.

I found this blog post here which uses interact.js with swipable cards and tried to fit it to my purpose.
My card component right now looks like this:

```<code><template>
  <v-card
    ripple
    class="primary"
    :id = "id"
    ref="interactElement"
  >
    <slot/>
  </v-card>
</template>

<script>
import interact from 'interactjs';

export default {
  props: ['id'],
  mounted() {
    const element = this.$refs.interactElement;
    console.log(element);
    interact(element).draggable({
      onstart: () => {
        console.log('---------start dragging');
      },
      onend: () => {
        console.log('---------end dragging');
      },
    });
  },
};
</script>

<style scoped>
  .v-card {
    height: 7rem;
    width: 7rem;
  }

  .draggable{
    touch-action: none;
    user-select: none;
  }
</style>
</code>```

However my problem right now is that e.g onstart never triggers. What am I doing wrong here?

Also I am wondering if it is better to do it like this or test a wrapper for interact.js in vue like this one? I am not quite sure what such a wrapper would be beneficial for as I am quite new to vue?

Thanks in advance! :)

答: The on start method need to another vue method override property called Created () (same as Mounted object)</p>

Title: interact.js for vue component

Body:
up until now I had two boards between which someone could drag 'n drop cards.
Now I want to try out interact.js as it sounds like a nice and well maintained library.
As I am using vue for my project I am now a bit confused about how to tackle this.

I found this blog post here which uses interact.js with swipable cards and tried to fit it to my purpose.
My card component right now looks like this:

<template>
  <v-card
    ripple
    class="primary"
    :id = "id"
    ref="interactElement"
  >
    <slot/>
  </v-card>
</template>

However my problem right now is that e.g onstart never triggers. What am I doing wrong here?

Also I am wondering if it is better to do it like this or test a wrapper for interact.js in vue like this one? I am not quite sure what such a wrapper would be beneficial for as I am quite new to vue?

Thanks in advance! :)


答:
You can map it and inside that take the name out and get Object.values() of the rest of values:

var array = [ { "name": "product1", "Jan": 3, "Feb": 2, "Mar": 0, "Apr": 1, "May": 3, "Jun": 0, "Jul": 0, "Aug": 0, "Sep": 5, "Oct": 0, "Nov": 0, "Dec": 0 }, { "name": "product2", "Jan": 4, "Feb": 0, "Mar": 0, "Apr": 1, "May": 1, "Jun": 0, "Jul": 0, "Aug": 0, "Sep": 5, "Oct": 0, "Nov": 0, "Dec": 0 }]

var result = array.map(({name,...rest})=>({ name, data : Object.values(rest)}));

console.log(result);```

Title: put value of different keys to a single array

Body:
I have the following array of objects:

[
  {
    "name": "product1",
    "Jan": 3,
    "Feb": 2,
    "Mar": 0,
    "Apr": 1,
    "May": 3,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  },
  {
    "name": "product2",
    "Jan": 4,
    "Feb": 0,
    "Mar": 0,
    "Apr": 1,
    "May": 1,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  }
]

I would like to pass the value of all the months to a single array respecting the order of the months as follows:

[
  {
    "name": "product1",
    "data": [3, 2, 0, 1, 3, 0, 0, 0, 5, 0, 0, 0],
  },
  {
    "name": "product2",
    "data": [4, 0, 0, 1, 1, 0, 0, 0, 5, 0, 0, 0],
  }
]

so how can i do this?


问:
Adding text over an image in HTML CSS
I am trying to add text over top of an image on a 'product card' listing. The top left and top right div classes aren't appearing over top of the image. Here is my code:

.cardcontainer {
    position: relative;
}
.top-left {
    position: absolute;
    top: 8px;
    left: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}
.top-right {
    position: absolute;
    top: 8px;
    right: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="4u">
    <div class="cardcontainer">
        <img src={{ jinja image source }} alt="">
        <div class="top-left">top left text</div>
        <div class="top-right">top right text</div>
        <div class="textbox">
            <!--some stuff here that appears below the image-->
        </div>
    </div>
</section></code>```

Any ideas? thanks for your help!

答:
```<code><!DOCTYPE html>
<html>
<head>
<style>
.cardcontainer {
    position: relative;
}
.top-left {
  position: absolute;
  top: 8px;
  left: 16px;
}
.top-right {
  position: absolute;
  top: 8px;
  right: 16px;
}
</style>
</head>
<body>

<section class="4u">
    <div class="cardcontainer">
        <a href="" target="_blank" class="image featured"><img src="https://www.w3schools.com/howto/img_snow_wide.jpg" alt="" style="width:100%;"></a>
        <div class="top-left">top left text</div>
        <div class="top-right">top right text</div>
        <div class="textbox">
            Dummy Text
            Dummy Text
        </div>
    </div>
</section>

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

Title: Adding text over an image in HTML CSS

Body:
I am trying to add text over top of an image on a 'product card' listing. The top left and top right div classes aren't appearing over top of the image. Here is my code:

.cardcontainer {
    position: relative;
}
.top-left {
    position: absolute;
    top: 8px;
    left: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}
.top-right {
    position: absolute;
    top: 8px;
    right: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}

top left text

top right text

Any ideas? thanks for your help!


答:
At first I  was surprised,  I was like ... wtf. But after wrapping my brain on it a few seconds, I realized the example calls the getter function 1 million time in a loop.  Of course if the variable is wrapped in a getter, we have added instructions and of course it's going to take longer.

In my opinion in most situations this is very trivial because I have yet to come accross a script that comes event close to calling getters 1 million time when running.  If you do need to squeeze performance to the very last drop, it is good to know this optimisation technique.

Title: Calling the variable property directly vs getter/setters - OOP Design

Body:
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();

Suggested Optimization:

$rover = new dog();
$rover->name = 'rover';
echo $rover->name;

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?


问:
Update SQL from PHP with textbox and button
I am simply trying to create a home webpage to where we can enter the mileage hit update which grabs the vehicle, and current date then pushes it to the DB.

The code I have below displays correctly other than maybe formatting the number to have a , but that wouldn't be a necessity.

When I hit update I get Notice: Undefined variable: mileage in /var/www/html/Oil/cars.php on line 60

```<code><link href="status.css" rel="stylesheet">
<body bgcolor = #000000>
<font color = "white">

<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
 <META HTTP-EQUIV="refresh" CONTENT="86400"><style>
        body {
            animation: fadeInAnimation ease 3s;
            animation-iteration-count: 1;
            animation-fill-mode: forwards;
        }
        @keyframes fadeInAnimation {
            0% {
                opacity: 0;
            }
            100% {
                opacity: 1;
            }
        }
    </style>
</head>

<center>
<font color = "red">

<?php
try {

    $db = new PDO("sqlite:/var/www/html/Oil/Vehicles.db");
    print "<center><table border=10 bordercolorlight=#383838 bordercolordark=Gray>";
    print "<tr><td class='toprow'><u>Vehicle</u></td><td class='toprow'><u>Mileage</u></td><td class='toprow'><u>Filter Size</u></td><td class='toprow'><u>Oil Capacity</u></td><td class='toprow'><u>Oil Type</u></td><td class='toprow'><u>Change Date</u></td><td class='toprow'><u>New Miles</u></td><td class='toprow'><u>Update</u></td></tr>";
    $result2 = $db->query('SELECT * FROM Cars');

    foreach ($result2 as $row) {

        print '<tr><td>' . $row['vehicle'] .'</td>';
        print "<td>" . $row['mileage'] . "</td>";
        print '<td>' . $row['filter'] .'</td>';
        print '<td>' . $row['oilCap'] .'</td>';
        print '<td>' . $row['oilType'] .'</td>';
        print '<td>' . $row['changeDate'] .'</td>';
    print '<td><form action="" method="POST"><input type="Text" name= "mileage"/><input type="hidden" name="vehicle" value="' .$row['vehicle']. '"/></td>';
    print '<td><button class="btn btn-default" type="submit" name="update">Update</button></form></td></tr>';
    }
    print "</table></center>";

} catch (PDOException $e) {
    echo $e->getMessage();
}
if (isset($_POST['update'])) {
    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    $mileage = $_POST['mileage'];
    print $mileage;
    $vehicle = $_POST['vehicle'];
    print $vehicle;
    $change = date("m/d/Y");
    print $change;

    $sql = "UPDATE cars SET mileage = :mileage, chageDate = :change WHERE vehicle = :vehicle";

    try{
            $db2 = new PDO("sqlite:/var/www/html/Oil/Vehicles.db");
        if (!($results = $db2->prepare($sql))){
            echo "Prepare failed: (" . $db->errorInfo() . ") " . $db->errorCode();
        }elseif (!$results->bindValue(':mileage', $mileage)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->bindValue(':change', $change)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->bindValue(':vehicle', $vehicle)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->execute()) {
            echo "Execute failed:\n";
            print_r($results->errorInfo());
        }else{
            $count = $results ->rowCount();
            if($results ->rowCount() == 0)
                echo 'Error';
            else
                echo 'Changed!';
        }

        } catch (PDOException $e) {
            echo $e->getMessage();
        }

}

?>

</code>```

Maybe I'm not passing mileage correctly?

答:
Ended up being 2 spelling issues on my part and then ran into a permission error on the DB.
After fixing all it worked as intended</p>

Body:
I am simply trying to create a home webpage to where we can enter the mileage hit update which grabs the vehicle, and current date then pushes it to the DB.

The code I have below displays correctly other than maybe formatting the number to have a , but that wouldn't be a necessity.

When I hit update I get Notice: Undefined variable: mileage in /var/www/html/Oil/cars.php on line 60

<link href="status.css" rel="stylesheet">

<meta name="viewport" content="width=device-width, initial-scale=1.0">
 <META HTTP-EQUIV="refresh" CONTENT="86400">

<?php
try {

    $db = new PDO("sqlite:/var/www/html/Oil/Vehicles.db");
    print "
";
    print "
Vehicle	Mileage	Filter Size	Oil Capacity	Oil Type	Change Date	New Miles	Update
";
    $result2 = $db->query('SELECT * FROM Cars');

    foreach ($result2 as $row) {

        print '
' . $row['vehicle'] .'	';
        print "" . $row['mileage'] . "	";
        print '' . $row['filter'] .'	';
        print '' . $row['oilCap'] .'	';
        print '' . $row['oilType'] .'	';
        print '' . $row['changeDate'] .'	';
    print '<form action="" method="POST"><input type="Text" name= "mileage"/><input type="hidden" name="vehicle" value="' .$row['vehicle']. '"/>	';
    print '<button class="btn btn-default" type="submit" name="update">Update</button></form>
';
    }
    print "
";

} catch (PDOException $e) {
    echo $e->getMessage();
}
if (isset($_POST['update'])) {
    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    $mileage = $_POST['mileage'];
    print $mileage;
    $vehicle = $_POST['vehicle'];
    print $vehicle;
    $change = date("m/d/Y");
    print $change;

    $sql = "UPDATE cars SET mileage = :mileage, chageDate = :change WHERE vehicle = :vehicle";

    try{
            $db2 = new PDO("sqlite:/var/www/html/Oil/Vehicles.db");
        if (!($results = $db2->prepare($sql))){
            echo "Prepare failed: (" . $db->errorInfo() . ") " . $db->errorCode();
        }elseif (!$results->bindValue(':mileage', $mileage)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->bindValue(':change', $change)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->bindValue(':vehicle', $vehicle)){
            echo "Binding parameters failed: (" . $results->errorInfo() . ") " . $results->errorCode();
        }elseif (!$results->execute()) {
            echo "Execute failed:\n";
            print_r($results->errorInfo());
        }else{
            $count = $results ->rowCount();
            if($results ->rowCount() == 0)
                echo 'Error';
            else
                echo 'Changed!';
        }

        } catch (PDOException $e) {
            echo $e->getMessage();
        }

}

?>

Maybe I'm not passing mileage correctly?


问:
How to add SDK files manually that needs a package.xml in android studio?
I have just installed Android studio and it needs to download some SDK files. But my internet connection is slow and the download keeps failing.

so I took the links and downloaded all SDK files manually with my download manager and then I unzipped them and put them in SDK path which in my case is:

C:\Users\USERNAME\AppData\Local\Android\Sdk

the problem is when I open Android studio it still downloads these SDK files. I don't know how to tell android studio that these files are already downloaded. Can anyone solve this?
Android Studio that I am using is version 4.0.0.

Check the images for more information:

And when I click the edit:

And after clicking next:

答:
I finally figured it out. the SDK manager add a package.xml with some details after it download the sdk components and unzipped them. so manually unzipping sdk components to sdk folder won't work because sdk manager won't know if the component is already installed and it tries to download it again. (note: not all sdk components need a package.xml and work properly if you manually unzip them into sdk folder.)

Solution:

1- you should download the components manually with a download manager if you don't have the sdk components zip files. you can get the files link from the sdk download log:

2- wait until the downloading of that specific component fails. like in the picture

3- then the sdk manager start the download of another component, in the meantime you should go to sdk folder and inside .temp folder you would see folders with names like packageOperation followed by a number. in each one of this folders is a sdk component download file (in our case failed download) that probably has an extension of .asdownload.

4- Delete the file with .asdownload and paste your fully downloaded zip file.

5- you can follow the steps for every sdk component. at the end the sdk manager will give you a retry option if there was any failed downloads. click retry, this time the sdk manager won't download the sdk files that failed (because of the sdk zip files that we manually pasted inside packageOperation folders) and it automatically installs them.

and that's it. you should see sdk components finishes successfully.


问:
How to build a deep learning text classifier using convolutional neural networks (python)
What are the steps I would need to take to build a deep learning text classifier, more specifically a text classifier that identifies an author (authorship attribution) in a set of unlabeled texts? The model I am looking at using is word-word CNN (convolutional neural network) which has proven to be very successful in things such as text classification. I am looking to build this model in python.

I am new to deep learning so any resources and information is appreciated.

答:
An End to End Example to demonstrate how to use Convolutional Neural Networks for Text Classification using Tensorflow.Keras is shown below:

```<code>from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing import sequence
max_features = 10000
max_len = 500
print('Loading data...')
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
print(len(x_train), 'train sequences')
print(len(x_test), 'test sequences')
print('Pad sequences (samples x time)')
x_train = sequence.pad_sequences(x_train, maxlen=max_len)
x_test = sequence.pad_sequences(x_test, maxlen=max_len)
print('x_train shape:', x_train.shape)
print('x_test shape:', x_test.shape)

model = Sequential()
model.add(layers.Embedding(max_features, 128, input_length=max_len))
model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.MaxPooling1D(5))
model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.GlobalMaxPooling1D())
model.add(layers.Dense(1))
model.summary()
model.compile(optimizer=RMSprop(lr=1e-4),
loss='binary_crossentropy',
metrics=['acc'])
history = model.fit(x_train,y_train,epochs=10,batch_size=128,validation_split=0.2)
</code>```

For more information please refer Section 6.4 Sequence processing with convnets in the book, Deep Learning Using Python written by Francois Chollet, the Father of Keras.

Hope this helps. Happy Learning!

Body:
An End to End Example to demonstrate how to use Convolutional Neural Networks for Text Classification using Tensorflow.Keras is shown below:

from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing import sequence
max_features = 10000
max_len = 500
print('Loading data...')
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
print(len(x_train), 'train sequences')
print(len(x_test), 'test sequences')
print('Pad sequences (samples x time)')
x_train = sequence.pad_sequences(x_train, maxlen=max_len)
x_test = sequence.pad_sequences(x_test, maxlen=max_len)
print('x_train shape:', x_train.shape)
print('x_test shape:', x_test.shape)

model = Sequential()
model.add(layers.Embedding(max_features, 128, input_length=max_len))
model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.MaxPooling1D(5))
model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.GlobalMaxPooling1D())
model.add(layers.Dense(1))
model.summary()
model.compile(optimizer=RMSprop(lr=1e-4),
loss='binary_crossentropy',
metrics=['acc'])
history = model.fit(x_train,y_train,epochs=10,batch_size=128,validation_split=0.2)

For more information please refer Section 6.4 Sequence processing with convnets in the book, Deep Learning Using Python written by Francois Chollet, the Father of Keras.

Hope this helps. Happy Learning!


问:
Firestore startAfter() returning the same data in infinite scrolling when ordered by descending timestamp
I'm writing a profile page with chronological user posts (latest post on top) using Firestore on Ionic by setting orderBy() to "timestamp" descending. I'm using Ionic's infinite loading to load more posts when the user reaches the bottom, but the result is that Firestore loads the exact same posts over and over again. Please help!

Hi!

Sorry if this is a beginner question, but I've been wrapping my head around this for sever hours to no avail. The pagination works properly when in ascending order, but loads the same posts when in descending order. I've looked at trying the following alternatives, but they would not be cost-efficient:

Change the limit when user reaches the bottom: this would lead to reading all the posts again and again

Do it in ascending order but reverse the array: would defeat the purpose of pagination

use a query (where) to grab the documents before x timestamp: works in theory, but is a bit hacky and I would really want to know how startAfter() works since it's already there.

.

'''

```<code>READ_posts__profile(uid,limit, start) : Promise<[]>
  {
      return new Promise((resolve, reject) =>
      {

         if (start == null)
         {
            resolve();
         }
        else if(start == 'head')
        {
            start = new Date();
        }
            console.log(start);

         this._DB.collection(this.ref.posts + uid + '/userposts' )
         .orderBy("timestamp", 'desc').startAfter(start).limit(limit)
         .get()
         .then((querySnapshot) =>
         {

            let obj : any = [];

            console.log(obj);

            querySnapshot
            .forEach((doc : any) =>
            {
               obj.push({
                  id             : doc.id,
                  content        : doc.data().content,
                  likes          : doc.data().likes,
                  timestamp      : doc.data().timestamp,
                  comments       : doc.data().comments
               });

            });

            resolve(obj);
         })
         .catch((error : any) =>
         {
            reject(error);
         });
      });
  }
</code>```

'''

Expected result: Infinite scrolling of posts from latest to oldest
Result: Infinite scrolling of first x posts again and again (limit is x)

Thank you for taking the time to read. Hope to hear from you guys soon!

UPDATE FOR FUTURE REFERENCE:
Rather than using the doc itself in .startAfter(), it worked with using doc.timestamp like so:

```<code>      this._DB.collection(this.ref.posts + uid + '/userposts' )
  .orderBy("timestamp", "desc").startAfter(start.timestamp).limit(this.limit)
  .get()
  .then(querySnapshot =>
  {
</code>```

答:
In my case I added the query like this

```<code>query.startAfter(lastId)
</code>```

where it should have been

```<code>query = query.startAfter(lastId)
</code>```

Body:
I'm writing a profile page with chronological user posts (latest post on top) using Firestore on Ionic by setting orderBy() to "timestamp" descending. I'm using Ionic's infinite loading to load more posts when the user reaches the bottom, but the result is that Firestore loads the exact same posts over and over again. Please help!

Hi!

Sorry if this is a beginner question, but I've been wrapping my head around this for sever hours to no avail. The pagination works properly when in ascending order, but loads the same posts when in descending order. I've looked at trying the following alternatives, but they would not be cost-efficient:

Change the limit when user reaches the bottom: this would lead to reading all the posts again and again

Do it in ascending order but reverse the array: would defeat the purpose of pagination

use a query (where) to grab the documents before x timestamp: works in theory, but is a bit hacky and I would really want to know how startAfter() works since it's already there.

.

'''

READ_posts__profile(uid,limit, start) : Promise<[]>
  {
      return new Promise((resolve, reject) =>
      {

         if (start == null)
         {
            resolve();
         }
        else if(start == 'head')
        {
            start = new Date();
        }
            console.log(start);

         this._DB.collection(this.ref.posts + uid + '/userposts' )
         .orderBy("timestamp", 'desc').startAfter(start).limit(limit)
         .get()
         .then((querySnapshot) =>
         {

            let obj : any = [];

            console.log(obj);

            querySnapshot
            .forEach((doc : any) =>
            {
               obj.push({
                  id             : doc.id,
                  content        : doc.data().content,
                  likes          : doc.data().likes,
                  timestamp      : doc.data().timestamp,
                  comments       : doc.data().comments
               });

            });

            resolve(obj);
         })
         .catch((error : any) =>
         {
            reject(error);
         });
      });
  }

'''

Expected result: Infinite scrolling of posts from latest to oldest
Result: Infinite scrolling of first x posts again and again (limit is x)

Thank you for taking the time to read. Hope to hear from you guys soon!

UPDATE FOR FUTURE REFERENCE:
Rather than using the doc itself in .startAfter(), it worked with using doc.timestamp like so:

      this._DB.collection(this.ref.posts + uid + '/userposts' )
  .orderBy("timestamp", "desc").startAfter(start.timestamp).limit(this.limit)
  .get()
  .then(querySnapshot =>
  {

Body:
In my case I added the query like this

query.startAfter(lastId)

where it should have been

query = query.startAfter(lastId)


问:
Displaying Google Map page via jQuery AJAX
Here's what I am trying to do.

I am using a jQuery tooltip plug-in called jTip (http://www.codylindley.com/blogstuff/js/jtip/).

This plugin effectively loads another page into the tooltip it is displaying.

So I have created another page, which has a small google map in it. The page is nothing special, it just displays a google map with a single marker.

The link to the google map page is written as below.

```<code><a  href="my_ajax_page.php?width=375" class="jTip" id="one" name="This is a tooltip header">Click here!</a>
</code>```

If I go to this page directly, then the page displays fine. However, via the tooltip plugin, map doesn't show anymore. The map page is as follow.

```<code><!DOCTYPE html>
<html>
  <head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
  <script type="text/javascript">
    function initialize()
    {
        var latlng = new google.maps.LatLng(35, 101);
        var myOptions = { zoom: 15, center: latlng,
                          mapTypeId: google.maps.MapTypeId.ROADMAP };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var marker = new google.maps.Marker( { position:latlng,
                                               map: map,
                                               animation: google.maps.Animation.DROP });

    }
  </script>
</head>
<body>
  <div id="map_canvas" style="width:300px;height:300px"></div>
</body>
</html>
</code>```

Any suggestions on how this could be done?

答:
I would suggest using Google Maps API to do this:

http://code.google.com/apis/maps/documentation/javascript/

I successfully implemented this with a jQuery UI at this site:

http://www.exploresouthernindiana.com/wheretosleep.php?s2=servicelink.serviceid%3D4&submit=Submit

You are more than welcome to look at sabramedia.js where the code is interfacing with the Google API.

Note: I didn't design the site. I just setup the map dialog for them.

Body:
Here's what I am trying to do.

I am using a jQuery tooltip plug-in called jTip (http://www.codylindley.com/blogstuff/js/jtip/).

This plugin effectively loads another page into the tooltip it is displaying.

So I have created another page, which has a small google map in it. The page is nothing special, it just displays a google map with a single marker.

The link to the google map page is written as below.

Click here!

If I go to this page directly, then the page displays fine. However, via the tooltip plugin, map doesn't show anymore. The map page is as follow.

<!DOCTYPE html>

  <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

Any suggestions on how this could be done?


问:
Angular Toggle only the element click on
I have a method that toggles a div area.

At the moment I have 3 areas

app.component.ts

```<code>show = false;

toggle() {
    this.show = !this.show;
}
</code>```

app.component.html

```<code><div>
    <div *ngIf="show">
      <div>One</div>
    </div>
    <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="show">
      <div>Two</div>
    </div>
    <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="show">
      <div>Three</div>
    </div>
    <button type="button" toggle()"></button>
</div>
</code>```

At the moment is will show and hide the 3 sections.

How can I chan it so that it just toggles the div with the *ngIf="show" that I of the button I clicked?

答:
You could have a responsible class for doing this, with a property for each div:

```<code>class SectionVisibilityHandler {
     private boolean _div1 = false;
     private boolean _div2 = false;
     private boolean _div3 = false;

     public toggle(idx: number): boolean {
         this['_div' + idx] = !this['_div' + idx];
     }

     public get div1(): boolean {
         return this._div1;
     }

     public get div2(): boolean {
         return this._div2;
     }

     public get div3(): boolean {
         return this._div3;
     }
}
</code>```

And then, access these properties using getters:

```<code><div>
   <div *ngIf="visibilityHandler.div1">
     <div>One</div>
   </div>
   <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="visibilityHandler.div2">
      <div>Two</div>
    </div>
    <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="visibilityHandler.div3">
      <div>Three</div>
    </div>
    <button type="button" toggle()"></button>
</div>
</code>```

And the visibility handler object is defined in your component properties:

```<code>public visibilityHandler: SectionVisibilityHandler = new SectionVisbilityHandler();
</code>```

This way, you can customize your logic behind showing/hiding the div in a specific class and method.

However, you can define this class as a service and inject it inside the component.

NOTE: If your divs are dynamically generated then you need an array in the handling class and two methods, one for toggling a specific index and another one to access arrays' elements by index.

Body:
I have a method that toggles a div area.

At the moment I have 3 areas

app.component.ts

show = false;

toggle() {
    this.show = !this.show;
}

app.component.html

One

    <button type="button" toggle()"></button>

Two

    <button type="button" toggle()"></button>

Three

    <button type="button" toggle()"></button>

At the moment is will show and hide the 3 sections.

How can I chan it so that it just toggles the div with the *ngIf="show" that I of the button I clicked?

Body:
You could have a responsible class for doing this, with a property for each div:

class SectionVisibilityHandler {
     private boolean _div1 = false;
     private boolean _div2 = false;
     private boolean _div3 = false;

     public toggle(idx: number): boolean {
         this['_div' + idx] = !this['_div' + idx];
     }

     public get div1(): boolean {
         return this._div1;
     }

     public get div2(): boolean {
         return this._div2;
     }

     public get div3(): boolean {
         return this._div3;
     }
}

And then, access these properties using getters:

<div>
   <div *ngIf="visibilityHandler.div1">
     <div>One</div>
   </div>
   <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="visibilityHandler.div2">
      <div>Two</div>
    </div>
    <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="visibilityHandler.div3">
      <div>Three</div>
    </div>
    <button type="button" toggle()"></button>
</div>

And the visibility handler object is defined in your component properties:

public visibilityHandler: SectionVisibilityHandler = new SectionVisbilityHandler();

This way, you can customize your logic behind showing/hiding the div in a specific class and method.

However, you can define this class as a service and inject it inside the component.

NOTE: If your divs are dynamically generated then you need an array in the handling class and two methods, one for toggling a specific index and another one to access arrays' elements by index.


问:
MYSQL digit filtering query on text field
I have a database table which looks like this (simplified):

```<code>╔════╦══════════════╦═════════╗
║ ID ║  Product     ║ Tags    ║
╠════╬══════════════╬═════════╣
║  1 ║ Product1     ║a,1-5,b  ║
║  2 ║ Product2     ║a,6-12,d ║
║  3 ║ Product3     ║a,20-30,c║
║  4 ║ Product4     ║b,5-55,a ║
╚════╩══════════════╩═════════╝
</code>```

The query I'm struggling with should return the results based on Tags column.

Example

Should return all products that have the a tag (no matter of the position determined with , character) with number scope from 6-21 for the second tag, which represents the years of the ones potentially interested into product.

I'm clueless on how to do this.

答:
You should not store multiple values in a string column.  It is wrong, wrong, wrong.  SQL has a great way to store lists.  It is called a table, which has rows and columns for each value.

That said, sometimes we are stuck with other people's really, really, really bad decisions.  For those purposes, MySQL has a convenient function, find_in_set():

```<code>where find_in_set('a', tags) > 0
</code>```

Your effort should go into fixing the data model, rather than trying to work around it.

Body:
I have a database table which looks like this (simplified):

╔════╦══════════════╦═════════╗
║ ID ║  Product     ║ Tags    ║
╠════╬══════════════╬═════════╣
║  1 ║ Product1     ║a,1-5,b  ║
║  2 ║ Product2     ║a,6-12,d ║
║  3 ║ Product3     ║a,20-30,c║
║  4 ║ Product4     ║b,5-55,a ║
╚════╩══════════════╩═════════╝

The query I'm struggling with should return the results based on Tags column.

Example

Should return all products that have the a tag (no matter of the position determined with , character) with number scope from 6-21 for the second tag, which represents the years of the ones potentially interested into product.

I'm clueless on how to do this.

Body:
You should not store multiple values in a string column.  It is wrong, wrong, wrong.  SQL has a great way to store lists.  It is called a table, which has rows and columns for each value.

That said, sometimes we are stuck with other people's really, really, really bad decisions.  For those purposes, MySQL has a convenient function, find_in_set():

where find_in_set('a', tags) > 0

Your effort should go into fixing the data model, rather than trying to work around it.


问:
Tool for automated porting and language that can compile into others
I'm just asking this out of curiosity :

Is there any tool that can automatically convert a source code of reasonable complexity from one language to another ?

Is there any "meta-language" that can compile into several other languages ? For example CoffeeScript compiles into Javascript.

If you know any open-source example, it'd be great !

Thank you for your time.

PS: No idea how to tag this. Feel free to edit.

答:
You can convert Fortran code to C using the f2c tool.

For python, you can convert a subset of the language to C++ using shedskin.

The vala language is converted to C before the real compilation.


问:
How do I loop through columns in R?
I am trying to clean up my code for cleaning missing data. I have a dataset with 6 columns and the code works if I were to do them individually like this:

```<code>mammographic_masses <- mammographic_masses %>%
  mutate(birad = replace(birad, birad== "na", NA)) %>%
  mutate(birad = replace(birad, birad== "N/A", NA))
</code>```

But when I try to do it in a for loop like this:

```<code>for (i in ncol(mammographic_masses)){
  print(class(mammographic_masses[[i]]))
  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "na", NA)) %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
}
</code>```

I get an error:

```<code>Error: unexpected '=' in:
"  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] ="
>     mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
Error: unexpected '=' in "    mutate(mammographic_masses[[,i]] ="
> }
Error: unexpected '}' in "}"
</code>```

I also was reading up on other ways such as apply etc. but i cant figure a way to loop it per column

答:
Instead of looping, use mutate_all.

```<code>library(dplyr)

mammographic_masses %>%
  mutate_all(function(x) {is.na(x) <- x %in% c("na", "N/A"); x})
#     V1   V2   V3   V4
#1     d    b <NA>    c
#2     d    b <NA> <NA>
#3  <NA> <NA>    d    b
#4     a <NA> <NA>    b
#5     a    b    d <NA>
#6     d    c    b    c
#7     b    b    d <NA>
#8  <NA> <NA> <NA>    d
#9     a    d    d <NA>
#10 <NA>    b    d <NA>
</code>```

Test data creation code

```<code>set.seed(2020)
n <- 10
mammographic_masses <- replicate(4, sample(c(letters[1:4], "na", "N/A"), n, TRUE))
mammographic_masses <- as.data.frame(mammographic_masses)
</code>```

Title: How do I loop through columns in R?

Body:
I am trying to clean up my code for cleaning missing data. I have a dataset with 6 columns and the code works if I were to do them individually like this:

mammographic_masses <- mammographic_masses %>%
  mutate(birad = replace(birad, birad== "na", NA)) %>%
  mutate(birad = replace(birad, birad== "N/A", NA))

But when I try to do it in a for loop like this:

for (i in ncol(mammographic_masses)){
  print(class(mammographic_masses[[i]]))
  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "na", NA)) %>%
    mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
}

I get an error:

Error: unexpected '=' in:
"  mammographic_masses <- mammographic_masses %>%
    mutate(mammographic_masses[[,i]] ="
>     mutate(mammographic_masses[[,i]] = replace(mammographic_masses[[,i]], mammographic_masses[[,i]] == "N/A", NA))
Error: unexpected '=' in "    mutate(mammographic_masses[[,i]] ="
> }
Error: unexpected '}' in "}"

I also was reading up on other ways such as apply etc. but i cant figure a way to loop it per column

Body:
Instead of looping, use mutate_all.

library(dplyr)

mammographic_masses %>%
  mutate_all(function(x) {is.na(x) <- x %in% c("na", "N/A"); x})
#     V1   V2   V3   V4
#1     d    b <NA>    c
#2     d    b <NA> <NA>
#3  <NA> <NA>    d    b
#4     a <NA> <NA>    b
#5     a    b    d <NA>
#6     d    c    b    c
#7     b    b    d <NA>
#8  <NA> <NA> <NA>    d
#9     a    d    d <NA>
#10 <NA>    b    d <NA>

Test data creation code

set.seed(2020)
n <- 10
mammographic_masses <- replicate(4, sample(c(letters[1:4], "na", "N/A"), n, TRUE))
mammographic_masses <- as.data.frame(mammographic_masses)


问:
Making a new line in js string
I want to make a new line between Editing and Become.
I tried \n but it didn't work
Any clue?</p>

```<code>var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";

function typeWriter(){
    if(i < text.length){
        document.getElementById("text").innerHTML += text.charAt(i);
        i++;
        setTimeout(typeWriter, 50);
    }
}
typeWriter();
</code>```

答:
Because HTML doesn't render line feeds, you need to add a condition in your function or adapt your HTML code.

Solution #1

Update your Javascript function, add a special case in your first if statement:

var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";

function typeWriter(){
  if(i < text.length){
    if(text.charAt(i) === "\n")
      document.getElementById("text").innerHTML += "
";
    document.getElementById("text").innerHTML += text.charAt(i);
    i++;
    setTimeout(typeWriter, 50);
  }
}
typeWriter();
```
<p>In that case, HTML will render <code><br/></code> tag by adding a new line. Don't forget to add the <code>\n</code> in your <code>text</code> variable.</p>
<h3>Solution #2:</h3>
<p>Use <code>``` HTML tag, not recommended but content will be rendered too, without changing your Javascript function.

```<code><pre id="text">```
```

Title: Making a new line in js string

Body:
I want to make a new line between Editing and Become.
I tried \n but it didn't work
Any clue?

var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";

function typeWriter(){
    if(i < text.length){
        document.getElementById("text").innerHTML += text.charAt(i);
        i++;
        setTimeout(typeWriter, 50);
    }
}
typeWriter();

Body:
Because HTML doesn't render line feeds, you need to add a condition in your function or adapt your HTML code.

Solution #1

Update your Javascript function, add a special case in your first if statement:

var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";

function typeWriter(){
  if(i < text.length){
    if(text.charAt(i) === "\n")
      document.getElementById("text").innerHTML += "<br/>";
    document.getElementById("text").innerHTML += text.charAt(i);
    i++;
    setTimeout(typeWriter, 50);
  }
}
typeWriter();

In that case, HTML will render <br/> tag by adding a new line. Don't forget to add the \n in your text variable.

Solution #2:

Use <pre> HTML tag, not recommended but content will be rendered too, without changing your Javascript function.

<pre id="text"></pre>


问:
Insert object to specific list index
How can I add an object to a list at a specific spot in Python? This is what I mean:

I want to add the string 'String2' to spot x in a list, but spot x doesn't exist. How can I create spot x?

I want it to be something like this:

```<code>list = ['String1']
x = 4
list.create(x)
list[x] = 'String2'
print(list)
</code>```

Output:

```<code>['String1', None, None, 'String2']
</code>```

答: What you're looking for is a sparse list, where values can be entered at arbitrary indices. This question has some possible solutions, like a custom sparse list implementation or using a dict.</p>

Title: Insert object to specific list index

Body:
How can I add an object to a list at a specific spot in Python? This is what I mean:

I want to add the string 'String2' to spot x in a list, but spot x doesn't exist. How can I create spot x?

I want it to be something like this:

list = ['String1']
x = 4
list.create(x)
list[x] = 'String2'
print(list)

Output:

['String1', None, None, 'String2']


问:
Prepend string to list item and turn it into JSON in Ansible
I have a list of ports

ports:
  - 123
  - 456
  - 789
```

<p>that I like to turn into <code>containerPort</code> for usage in a Kubernetes deployment:</p>

```"container_ports": [
            {
                "containerPort": 123
            },
            {
                "containerPort": 456
            },
            {
                "containerPort": 789
            }
        ]
```

<p>The example above is created when I define <code>ports</code> as </p>

<pre class="lang-yaml prettyprint-override"><code>ports:
  - containerPort: 123
  - containerPort: 456
  - containerPort: 789
</code>```

However, I'd like to save the user some typing and add containerPort automatically. I am able to prepend it using

- name: Creating custom ports
  set_fact:
    container_ports: "{{ ports | map('regex_replace', '(^)', '- containerPort: \\1') | list }}"
  when: ports is defined

```

<p>This does only create </p>

```    ok: [localhost] => {
        "container_ports": [
            "- containerPort: 123",
            "- containerPort: 456",
            "- containerPort: 789"
        ]
    }
```

though, which is close, but not quite right.

Body:
I have a list of ports

ports:
  - 123
  - 456
  - 789

that I like to turn into containerPort for usage in a Kubernetes deployment:

"container_ports": [
            {
                "containerPort": 123
            },
            {
                "containerPort": 456
            },
            {
                "containerPort": 789
            }
        ]

The example above is created when I define ports as

ports:
  - containerPort: 123
  - containerPort: 456
  - containerPort: 789

However, I'd like to save the user some typing and add containerPort automatically. I am able to prepend it using

- name: Creating custom ports
  set_fact:
    container_ports: "{{ ports | map('regex_replace', '(^)', '- containerPort: \\1') | list }}"
  when: ports is defined

This does only create

    ok: [localhost] => {
        "container_ports": [
            "- containerPort: 123",
            "- containerPort: 456",
            "- containerPort: 789"
        ]
    }

though, which is close, but not quite right.

Body:
An other solution using json_query

---
- hosts: localhost
  gather_facts: false

  vars:
    ports:
      - 123
      - 456

  tasks:
    - name: Tranform raw list to Kubernetes compatible format
      debug:
        msg: "{{ ports | json_query('[].{\"containerPort\": @}') }}"

Which gives:

PLAY [localhost] ***********************************************************************************************************************************************************************************************************************

TASK [Tranform raw list to Kubernetes compatible format] *******************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        {
            "containerPort": 123
        },
        {
            "containerPort": 456
        }
    ]
}

PLAY RECAP *****************************************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


问:
Need to type https:// awlays after adding SSL certificate
I bought a SSL certificate from some company and i have installed it on my Windows 2016 server IIS 10.and it's bind like below image.

When i type https://example.com it works fine... BUT when i type just example.com then it goes to IIS default site. as well as when i type https://www.example.com it works fine but when i type just www.example.com then it goes to Default IIS site.

This means when i type https:// then it works fine... But normally users type example.com or www.example.com ..
So how can i configure thisone for the above requirement ?

答:
That's exactly what your current site bindings will lead to,

https://docs.jexusmanager.com/tutorials/binding-diagnostics.html#background

So my suggestions are,

Add HTTP bindings back to this, so that http://example.com and http://www.example.com can be handled by this site, not the Default Web Site.

Install URL Rewrite module and then add a rule or rules to redirect HTTP traffic to HTTPS. Tons of articles/posts all over the internet on that.