问:
Best design pattern to handle iOS Application State/Data
I am starting a new project (learning purposes) and I am trying to figure out what is the best software design pattern to use in the following scenario.

I have several data that need to be downloaded from multiple webservices and store somewhere in my app, to display it later. However each piece of data (e.g. list of teachers, students) will only be used in one or more specific view controllers (e.g. teachersViewController and studentsViewController).

I read that the Singleton pattern or use the AppDelegate to store a variable (an object like ApplicationData) is a bad practise, even more in this example which I want to restrict the data access.

So, which design pattern should I choose? I have read something about dependency injection, but I don't have any clue about it or if it even helps me in this question. If it helps, some examples with explanation would be nice.

答:
You need some sort of database to store downloaded data. Good choices are Realm and Core Data. The right way to process data is:

Check if data is already in DB and show it if available.

Download or update data from server and parse it to objects.

Save objects to DB.

Show data taken from DB to user.

Download data as needed. When you open VC with students then download only students data and so on.

EDITED: If you need all the data on app open then load it and put in a DB before first screen opens. Then just use DB to show data to user.


来源: stackexchange

问:
Errors converting pdf to jpg using wand, Imagemagick, and Django
I am using ImageMagick 6.7.7-10 2017-07-31 Q16 on Ubuntu 14.04, through Wand 0.4.4, Python 3.4.3 and Django 1.11. I am trying to create a jpg thumbnail of a pdf file.

On the command line, I can do this with no errors:

```<code>convert -thumbnail x300 -background white -alpha remove Lucy.pdf[0] output_thumbnail.jpg
</code>```

But when I try to use wand on the same image I get this error:

```<code>Traceback (most recent call last):
  File "/home/mark/python-projects/memorabilia-project/memorabilia/models.py", line 24, in make_thumb
    pages = Image(blob = b)
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2742, in __init__
    self.read(blob=blob, resolution=resolution)
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2822, in read
    self.raise_exception()
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/resource.py", line 222, in raise_exception
    raise e
wand.exceptions.MissingDelegateError: no decode delegate for this image format `' @ error/blob.c/BlobToImage/367
</code>```

I looked at the delegates.xml file for ImageMagic in /etc, and there are entries for pdf files.

Thanks for any suggestions on how to get this conversion to work through wand.

Mark

I hacked a simple Python script from my django code to test wand with pdfs, and it gives the same error. I also tested whether Ghostscript is in the path, and printed out the results of convert -list delegates.

```<code>from wand.image import Image
from os.path import splitext
import uuid
import os
import hashlib

newname = "sam.jpg"
oldnames = ["16u.jpg", "Lucy.pdf", "Jimbo.tiff", "john_edmonds.pdf", ]
size = "200"
RESOLUTION = 200
test = "4"
TEST_DATA = "test_data/"

def test_delegate():
    print ("test_delegate")
    print(os.system("convert -list delegate"))

def test_gs():
    print ("test_gs")
    retval = os.system("gs --version")
    print (retval)

def read_image(file_name):
    f = open(file_name, 'rb')
    h = hashlib.sha256()
    buff_size = 128*1024
    for b in iter(lambda : f.read(buff_size), b""):
        h.update(b)
    computed_sha256 = h.hexdigest()
    f.close()
    print ("b="+str(len(b))+", computed_sha256="+computed_sha256)
    return b

def create_thumb(names):
    for img in names:
        img = TEST_DATA + img
        print(img)
        thumb_name, thumb_extension = os.path.splitext(img)
        thumb_extension = thumb_extension.lower()
        bytes = read_image(img)
        if thumb_extension in [".pdf",]:
            print("found pdf")
            #pages = Image(filename = img)
            pages = Image(blob = bytes)
            first_page = pages.sequence[0]
            image = Image(first_page)
        else:
            print("found image")
            #image = Image(filename=img)
            image = Image(blob = bytes)
        image.transform(resize="x"+size)
        image.format = "jpg"
        image.save(filename=thumb_name+"_thumb_"+test+".jpg")
        print("finished successfully")

def main():
    print("main")
    test_delegate()
    test_gs()
    create_thumb(oldnames)

if __name__ == '__main__':
    main()
</code>```

The output from this program is as follows. It has the same missing delegates error. The same error also occurs with tiff files, but not with jpg files (the first test file is a jpg and the code processed the file and created the thumbnail image). The program also prints the version of GS, which is 9.10, so that is accessible from the program, and it prints out the delegates it found, which include pdfs.:

```<code>python thumbs.py
main
test_delegate

Path: /etc/ImageMagick/delegates.xml

Delegate                Command
-------------------------------------------------------------------------------
    blender =>          "blender" -b "%i" -F PNG -o "%o""\n"convert" -concatenate "%o*.png" "%o"
        cdr =>          "uniconvertor" "%i" "%o.svg"; mv "%o.svg" "%o"
        cgm =>          "ralcgm" -d ps -oC < "%i" > "%o" 2> "%Z"
 dng:decode =>          "ufraw-batch" --silent --create-id=also --out-type=png --out-depth=16 "--output=%u.png" "%i"
        dot =>          "dot" -Tsvg "%i" -o "%o"
        dvi =>          "dvips" -q -o "%o" "%i"
        eps<=>pdf       "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 "-sDEVICE=pdfwrite" "-sOutputFile=%o" "-f%i"
        eps<=>ps        "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=nodevice" "-sOutputFile=%o" "-f%i"
        fig =>          "fig2dev" -L ps "%i" "%o"
        hpg =>          "hp2xx" -q -m eps -f `basename "%o"` "%i";     mv -f `basename "%o"` "%o"
       hpgl =>          "if [ -e hp2xx -o -e /usr/bin/hp2xx ]; then     hp2xx -q -m eps -f `basename "%o"` "%i";     mv -f `basename "%o"` "%o";   else     echo "You need to install hp2xx to use HPGL files with ImageMagick.";     exit 1;   fi"
        htm =>          "html2ps" -U -o "%o" "%i"
       html =>          "html2ps" -U -o "%o" "%i"
      https =>          "curl" -s -k -o "%o" "https:%F"
       ilbm =>          "ilbmtoppm" "%i" > "%o"
        man =>          "groff" -man -Tps "%i" > "%o"
       miff<= show      "/usr/bin/display" -delay 0 -window-group %[group] -title "%l " "ephemeral:%i"
mpeg:decode =>          "ffmpeg" -v -1 -i "%i" -vframes %S -vcodec pam -an -f rawvideo -y "%u.pam" 2> "%Z"
        pdf<=>eps       "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=epswrite" "-sOutputFile=%o" "-f%i"
        pdf<=>ps        "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=nodevice" "-sOutputFile=%o" "-f%i"
        pnm<= ilbm      "ppmtoilbm" -24if "%i" > "%o"
        pov =>          "povray" "+i%i" -D0 "+o%o" +fn%q +w%w +h%h +a -q9 "-kfi%s" "-kff%n";"convert" -concatenate "%o*.png" "%o"
         ps<=>eps       "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=epswrite" "-sOutputFile=%o" "-f%i"
         ps<=>pdf       "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pdfwrite" "-sOutputFile=%o" "-f%i"
         ps<= print     "lpr "%i"
       rgba<= rle       "rawtorle" -o "%o" -v "%i"
       scan =>          "scanimage" -d "%i" > "%o"
      scanx =>          "scanimage" > "%o"
      shtml =>          "html2ps" -U -o "%o" "%i"
        sid =>          "mrsidgeodecode" -if sid -i "%i" -of tif -o "%o" > "%u"
        svg =>          "rsvg-convert" -o "%o" "%i"
       tiff<= launch    "gimp" "%i"
        txt<=>ps        "enscript" -o "%o" "%i"
        wmf =>          "wmf2eps" -o "%o" "%i"
0
test_gs
9.10
0
test_data/16u.jpg
b=43597, computed_sha256=0bac89048bbbcfa75ad7d9dbc84eae42ff6b30c0a057dd76e180a205d9021b8d
found image
finished successfully
test_data/Lucy.pdf
b=61053, computed_sha256=6e108603ad4f6ae2e08b3d2a419a65d3cc1f60b788e9377be15b1926892189f8
found pdf
Traceback (most recent call last):
  File "thumbs.py", line 63, in <module>
    main()
  File "thumbs.py", line 60, in main
    create_thumb(oldnames)
  File "thumbs.py", line 44, in create_thumb
    pages = Image(blob = bytes)
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2742, in __init__
    self.read(blob=blob, resolution=resolution)
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2822, in read
    self.raise_exception()
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/resource.py", line 222, in raise_exception
    raise e
wand.exceptions.MissingDelegateError: no decode delegate for this image format `' @ error/blob.c/BlobToImage/367
Exception ignored in: <bound method Image.__del__ of <wand.image.Image: (empty)>>
Traceback (most recent call last):
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/resource.py", line 232, in __del__
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2767, in destroy
TypeError: object of type 'NoneType' has no len()
</code>```

Maybe this simple python code will help someone give me a direction to go to solve this problem. However, I am beginning to suspect there is a bug in wand when one uses byte arrays instead of file names.

Thanks!

Mark

答:
In your installed ImageMagick delegates.xml file, you will find:

```<code>  <delegate decode="ps:alpha" stealth="True" command=""gs" -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pngalpha" -dTextAlphaBits=%u -dGraphicsAlphaBits=%u "-r%s" %s "-sOutputFile=%s" "-f%s" "-f%s""/>

  <delegate decode="ps:cmyk" stealth="True" command=""gs" -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pamcmyk32" -dTextAlphaBits=%u -dGraphicsAlphaBits=%u "-r%s" %s "-sOutputFile=%s" "-f%s" "-f%s""/>

  <delegate decode="ps:color" stealth="True" command=""gs" -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pnmraw" -dTextAlphaBits=%u -dGraphicsAlphaBits=%u "-r%s" %s "-sOutputFile=%s" "-f%s" "-f%s""/>

  <delegate decode="ps" encode="eps" mode="bi" command=""gs" -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=eps2write" "-sOutputFile=%o" "-f%i""/>

  <delegate decode="ps" encode="pdf" mode="bi" command=""gs" -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pdfwrite" "-sOutputFile=%o" "-f%i""/>
</code>```

Where it has command=""gs", change that to provide the full path to gs in place of gs; that is, command=""path2/gs"

Be sure that you change this in the installed file and not in the ImageMagick download directory. Reboot and see if that helps.

Sorry, this is my only suggestion. And again I am not really familiar with Wand. Apologies if it does not help.

P.S. Is ImageMagick in /usr/bin or /usr/local/bin. If the latter, is that also in your PATH environment variable. Sorry if this is obvious.

ContentLicense: CC BY-SA 3.0

Body:
I am using ImageMagick 6.7.7-10 2017-07-31 Q16 on Ubuntu 14.04, through Wand 0.4.4, Python 3.4.3 and Django 1.11. I am trying to create a jpg thumbnail of a pdf file.

On the command line, I can do this with no errors:

convert -thumbnail x300 -background white -alpha remove Lucy.pdf[0] output_thumbnail.jpg

But when I try to use wand on the same image I get this error:

Traceback (most recent call last):
  File "/home/mark/python-projects/memorabilia-project/memorabilia/models.py", line 24, in make_thumb
    pages = Image(blob = b)
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2742, in __init__
    self.read(blob=blob, resolution=resolution)
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2822, in read
    self.raise_exception()
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/resource.py", line 222, in raise_exception
    raise e
wand.exceptions.MissingDelegateError: no decode delegate for this image format `' @ error/blob.c/BlobToImage/367

I looked at the delegates.xml file for ImageMagic in /etc, and there are entries for pdf files.

Thanks for any suggestions on how to get this conversion to work through wand.

Mark

I hacked a simple Python script from my django code to test wand with pdfs, and it gives the same error. I also tested whether Ghostscript is in the path, and printed out the results of convert -list delegates.

from wand.image import Image
from os.path import splitext
import uuid
import os
import hashlib

newname = "sam.jpg"
oldnames = ["16u.jpg", "Lucy.pdf", "Jimbo.tiff", "john_edmonds.pdf", ]
size = "200"
RESOLUTION = 200
test = "4"
TEST_DATA = "test_data/"

def test_delegate():
    print ("test_delegate")
    print(os.system("convert -list delegate"))

def test_gs():
    print ("test_gs")
    retval = os.system("gs --version")
    print (retval)

def read_image(file_name):
    f = open(file_name, 'rb')
    h = hashlib.sha256()
    buff_size = 128*1024
    for b in iter(lambda : f.read(buff_size), b""):
        h.update(b)
    computed_sha256 = h.hexdigest()
    f.close()
    print ("b="+str(len(b))+", computed_sha256="+computed_sha256)
    return b

def create_thumb(names):
    for img in names:
        img = TEST_DATA + img
        print(img)
        thumb_name, thumb_extension = os.path.splitext(img)
        thumb_extension = thumb_extension.lower()
        bytes = read_image(img)
        if thumb_extension in [".pdf",]:
            print("found pdf")
            #pages = Image(filename = img)
            pages = Image(blob = bytes)
            first_page = pages.sequence[0]
            image = Image(first_page)
        else:
            print("found image")
            #image = Image(filename=img)
            image = Image(blob = bytes)
        image.transform(resize="x"+size)
        image.format = "jpg"
        image.save(filename=thumb_name+"_thumb_"+test+".jpg")
        print("finished successfully")

def main():
    print("main")
    test_delegate()
    test_gs()
    create_thumb(oldnames)

if __name__ == '__main__':
    main()

The output from this program is as follows. It has the same missing delegates error. The same error also occurs with tiff files, but not with jpg files (the first test file is a jpg and the code processed the file and created the thumbnail image). The program also prints the version of GS, which is 9.10, so that is accessible from the program, and it prints out the delegates it found, which include pdfs.:

python thumbs.py
main
test_delegate

Path: /etc/ImageMagick/delegates.xml

Delegate                Command
-------------------------------------------------------------------------------
    blender =>          "blender" -b "%i" -F PNG -o "%o""\n"convert" -concatenate "%o*.png" "%o"
        cdr =>          "uniconvertor" "%i" "%o.svg"; mv "%o.svg" "%o"
        cgm =>          "ralcgm" -d ps -oC < "%i" > "%o" 2> "%Z"
 dng:decode =>          "ufraw-batch" --silent --create-id=also --out-type=png --out-depth=16 "--output=%u.png" "%i"
        dot =>          "dot" -Tsvg "%i" -o "%o"
        dvi =>          "dvips" -q -o "%o" "%i"
        eps<=>pdf       "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 "-sDEVICE=pdfwrite" "-sOutputFile=%o" "-f%i"
        eps<=>ps        "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=nodevice" "-sOutputFile=%o" "-f%i"
        fig =>          "fig2dev" -L ps "%i" "%o"
        hpg =>          "hp2xx" -q -m eps -f `basename "%o"` "%i";     mv -f `basename "%o"` "%o"
       hpgl =>          "if [ -e hp2xx -o -e /usr/bin/hp2xx ]; then     hp2xx -q -m eps -f `basename "%o"` "%i";     mv -f `basename "%o"` "%o";   else     echo "You need to install hp2xx to use HPGL files with ImageMagick.";     exit 1;   fi"
        htm =>          "html2ps" -U -o "%o" "%i"
       html =>          "html2ps" -U -o "%o" "%i"
      https =>          "curl" -s -k -o "%o" "https:%F"
       ilbm =>          "ilbmtoppm" "%i" > "%o"
        man =>          "groff" -man -Tps "%i" > "%o"
       miff<= show      "/usr/bin/display" -delay 0 -window-group %[group] -title "%l " "ephemeral:%i"
mpeg:decode =>          "ffmpeg" -v -1 -i "%i" -vframes %S -vcodec pam -an -f rawvideo -y "%u.pam" 2> "%Z"
        pdf<=>eps       "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=epswrite" "-sOutputFile=%o" "-f%i"
        pdf<=>ps        "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=nodevice" "-sOutputFile=%o" "-f%i"
        pnm<= ilbm      "ppmtoilbm" -24if "%i" > "%o"
        pov =>          "povray" "+i%i" -D0 "+o%o" +fn%q +w%w +h%h +a -q9 "-kfi%s" "-kff%n";"convert" -concatenate "%o*.png" "%o"
         ps<=>eps       "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=epswrite" "-sOutputFile=%o" "-f%i"
         ps<=>pdf       "gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pdfwrite" "-sOutputFile=%o" "-f%i"
         ps<= print     "lpr "%i"
       rgba<= rle       "rawtorle" -o "%o" -v "%i"
       scan =>          "scanimage" -d "%i" > "%o"
      scanx =>          "scanimage" > "%o"
      shtml =>          "html2ps" -U -o "%o" "%i"
        sid =>          "mrsidgeodecode" -if sid -i "%i" -of tif -o "%o" > "%u"
        svg =>          "rsvg-convert" -o "%o" "%i"
       tiff<= launch    "gimp" "%i"
        txt<=>ps        "enscript" -o "%o" "%i"
        wmf =>          "wmf2eps" -o "%o" "%i"
0
test_gs
9.10
0
test_data/16u.jpg
b=43597, computed_sha256=0bac89048bbbcfa75ad7d9dbc84eae42ff6b30c0a057dd76e180a205d9021b8d
found image
finished successfully
test_data/Lucy.pdf
b=61053, computed_sha256=6e108603ad4f6ae2e08b3d2a419a65d3cc1f60b788e9377be15b1926892189f8
found pdf
Traceback (most recent call last):
  File "thumbs.py", line 63, in <module>
    main()
  File "thumbs.py", line 60, in main
    create_thumb(oldnames)
  File "thumbs.py", line 44, in create_thumb
    pages = Image(blob = bytes)
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2742, in __init__
    self.read(blob=blob, resolution=resolution)
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2822, in read
    self.raise_exception()
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/resource.py", line 222, in raise_exception
    raise e
wand.exceptions.MissingDelegateError: no decode delegate for this image format `' @ error/blob.c/BlobToImage/367
Exception ignored in: <bound method Image.__del__ of <wand.image.Image: (empty)>>
Traceback (most recent call last):
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/resource.py", line 232, in __del__
  File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2767, in destroy
TypeError: object of type 'NoneType' has no len()

Maybe this simple python code will help someone give me a direction to go to solve this problem. However, I am beginning to suspect there is a bug in wand when one uses byte arrays instead of file names.

Thanks!

Mark

Body:
In your installed ImageMagick delegates.xml file, you will find:

  <delegate decode="ps:alpha" stealth="True" command="&quot;gs&quot; -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 &quot;-sDEVICE=pngalpha&quot; -dTextAlphaBits=%u -dGraphicsAlphaBits=%u &quot;-r%s&quot; %s &quot;-sOutputFile=%s&quot; &quot;-f%s&quot; &quot;-f%s&quot;"/>

  <delegate decode="ps:cmyk" stealth="True" command="&quot;gs&quot; -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 &quot;-sDEVICE=pamcmyk32&quot; -dTextAlphaBits=%u -dGraphicsAlphaBits=%u &quot;-r%s&quot; %s &quot;-sOutputFile=%s&quot; &quot;-f%s&quot; &quot;-f%s&quot;"/>

  <delegate decode="ps:color" stealth="True" command="&quot;gs&quot; -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 &quot;-sDEVICE=pnmraw&quot; -dTextAlphaBits=%u -dGraphicsAlphaBits=%u &quot;-r%s&quot; %s &quot;-sOutputFile=%s&quot; &quot;-f%s&quot; &quot;-f%s&quot;"/>

  <delegate decode="ps" encode="eps" mode="bi" command="&quot;gs&quot; -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 &quot;-sDEVICE=eps2write&quot; &quot;-sOutputFile=%o&quot; &quot;-f%i&quot;"/>

  <delegate decode="ps" encode="pdf" mode="bi" command="&quot;gs&quot; -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 &quot;-sDEVICE=pdfwrite&quot; &quot;-sOutputFile=%o&quot; &quot;-f%i&quot;"/>

Where it has command="&quot;gs&quot;, change that to provide the full path to gs in place of gs; that is, command="&quot;path2/gs&quot;

Be sure that you change this in the installed file and not in the ImageMagick download directory. Reboot and see if that helps.

Sorry, this is my only suggestion. And again I am not really familiar with Wand. Apologies if it does not help.

P.S. Is ImageMagick in /usr/bin or /usr/local/bin. If the latter, is that also in your PATH environment variable. Sorry if this is obvious.


问:
Does the Either type constructor contain a phantom type each for the left/right case?
AFAIK, only types are inhabited by values in Haskell, not type constructors. Either is a binary type constructor of kind * -> * -> *. Left and Right both apply this type constructor to a single type, which is provided by the passed value. Doesn't that mean that in both cases Either is merely partially applied and thus still a type constructor awaiting the missing type argument?

```<code>let x = Right 'x' -- Either a Char
</code>```

x has the type Either a Char. I would assume that this type would have the kind * -> *. This is clearly a polymorphic type, not a ground one. Yet Either a Char can be inhabited by values like 'x'.

My suspicion is that the type variable a is a phantom type for the Right case resp. b for Left. I know phantom types in connection with  Const, where the respective type variable isn't used at all. Am I on the right tack?

答:
Haskell has "implicit universal quantification", which means that type variables have an implicit forall. Either a Int is equivalent to forall a. Either a Int.

One way to consider a forall is that it's like a lambda, but for type variables. If we use the syntax @ for type application, then, you can "apply" a type to this and get a new type out.

```<code>let foo = Right 1 :: forall a. Either a Int
foo @Char   :: Either Char Int
foo @Double :: Either Double Int
</code>```

Body:
AFAIK, only types are inhabited by values in Haskell, not type constructors. Either is a binary type constructor of kind * -> * -> *. Left and Right both apply this type constructor to a single type, which is provided by the passed value. Doesn't that mean that in both cases Either is merely partially applied and thus still a type constructor awaiting the missing type argument?

let x = Right 'x' -- Either a Char

x has the type Either a Char. I would assume that this type would have the kind * -> *. This is clearly a polymorphic type, not a ground one. Yet Either a Char can be inhabited by values like 'x'.

My suspicion is that the type variable a is a phantom type for the Right case resp. b for Left. I know phantom types in connection with  Const, where the respective type variable isn't used at all. Am I on the right tack?

Body:
Haskell has "implicit universal quantification", which means that type variables have an implicit forall. Either a Int is equivalent to forall a. Either a Int.

One way to consider a forall is that it's like a lambda, but for type variables. If we use the syntax @ for type application, then, you can "apply" a type to this and get a new type out.

let foo = Right 1 :: forall a. Either a Int
foo @Char   :: Either Char Int
foo @Double :: Either Double Int


问:
How to get Polymer 2.0 ES5 elements working with v1 spec?
I've successfully built a number of Polymer 2.0 elements and they run great in ES6 capable browsers.

When I try to transpile them to ES5, the browser throws a bunch of errors, like these:

```<code>Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
</code>```

After some research, it looks like you need a native-shim, which comes along with the webcomponentsjs-es5-loader, but after switching to that now I'm getting a new error:

```<code>Class constructor DomModule cannot be invoked without 'new'
</code>```

How do transpiled Polymer 2.0 elements get used in a ES5 browser? Am I missing something?

答:
To use The Custom Element V1 Spec you must use classes. But ES5 browsers don't support classes. So there is an adapter that allows an ES5 browser to act like it is using classes.

See: https://github.com/webcomponents/webcomponentsjs#custom-elements-es5-adapterjs for more information.

You need to include the adapter on your ES5 browser before defining your Custom Element. This goes for Native components as well as Polymer 2+ components.

Body:
I've successfully built a number of Polymer 2.0 elements and they run great in ES6 capable browsers.

When I try to transpile them to ES5, the browser throws a bunch of errors, like these:

Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

After some research, it looks like you need a native-shim, which comes along with the webcomponentsjs-es5-loader, but after switching to that now I'm getting a new error:

Class constructor DomModule cannot be invoked without 'new'

How do transpiled Polymer 2.0 elements get used in a ES5 browser? Am I missing something?


问:
How can we pass pandoc_args to yaml header in rmarkdown?
I'm using rmarkdown to produce a word (.docx) report. I would like to change the header of the toc. This seems possible as pandoc_args can be passed as options in the yaml header in the case of a doc file (1). But I'm not doing it right. Could anyone provide a working example ?

(1) pandoc.args is included in the rmarkdown possible options and in the pandoc manual, there is a toc-title option

```<code>---
title: "yaml header"
author: "cedric"
output:
  word_document:
   toc: true
pandoc_args: toc-title="Table des matières"
---
# One section
# Another
</code>```

This produces :

答:
The title of the table of contents is document metadata, so you can set it with YAML metadata block.

```<code>---
title: "yaml header"
author: "cedric"
output:
  word_document:
    toc: true
toc-title: "Table des matières"
---
</code>```

Or passed it in with the -M command-line flag.

```<code>---
title: "yaml header"
author: "cedric"
output:
  word_document:
    toc: true
    pandoc_args: [
      "-M", "toc-title=Table des matières"
    ]
---
</code>```

Body:
I'm using rmarkdown to produce a word (.docx) report. I would like to change the header of the toc. This seems possible as pandoc_args can be passed as options in the yaml header in the case of a doc file (1). But I'm not doing it right. Could anyone provide a working example ?

(1) pandoc.args is included in the rmarkdown possible options and in the pandoc manual, there is a toc-title option

---
title: "yaml header"
author: "cedric"
output:
  word_document:
   toc: true
pandoc_args: toc-title="Table des matières"
---
# One section
# Another

This produces :

Body:
The title of the table of contents is document metadata, so you can set it with YAML metadata block.

---
title: "yaml header"
author: "cedric"
output:
  word_document:
    toc: true
toc-title: "Table des matières"
---

Or passed it in with the -M command-line flag.

---
title: "yaml header"
author: "cedric"
output:
  word_document:
    toc: true
    pandoc_args: [
      "-M", "toc-title=Table des matières"
    ]
---


问:
Time varies in postgres server and excel
I am trying a query which groups the data by months.

```<code>test_db=# select date_trunc('month', install_ts) AS month, count(id) AS count from api_booking group by month order by month asc;
 month                  | count
------------------------+-------
 2016-08-01 00:00:00+00 |   297
 2016-09-01 00:00:00+00 |  2409
 2016-10-01 00:00:00+00 |  2429
 2016-11-01 00:00:00+00 |  3512
(4 rows)
</code>```

This is the output in my postgres db shell.

How ever, when I try this query in excel, this is the output,

```<code> month                  | count
------------------------+-------
 2016-07-31 17:00:00+00 |   297
 2016-08-31 17:00:00+00 |  2409
 2016-09-30 17:00:00+00 |  2429
 2016-10-31 17:00:00+00 |  3512
(4 rows)
</code>```

The problem is I think excel is understanding date format in some different timezone.
So, How can I tell excel to read it correctly?
OR any solution to this problem?

答:
Try...

```<code>select date(date_trunc('month', install_ts)) AS month, count(id) AS count from api_booking
</code>```

The date()  strips out the time from a date with a time.

Body:
I am trying a query which groups the data by months.

test_db=# select date_trunc('month', install_ts) AS month, count(id) AS count from api_booking group by month order by month asc;
 month                  | count
------------------------+-------
 2016-08-01 00:00:00+00 |   297
 2016-09-01 00:00:00+00 |  2409
 2016-10-01 00:00:00+00 |  2429
 2016-11-01 00:00:00+00 |  3512
(4 rows)

This is the output in my postgres db shell.

How ever, when I try this query in excel, this is the output,

 month                  | count
------------------------+-------
 2016-07-31 17:00:00+00 |   297
 2016-08-31 17:00:00+00 |  2409
 2016-09-30 17:00:00+00 |  2429
 2016-10-31 17:00:00+00 |  3512
(4 rows)

The problem is I think excel is understanding date format in some different timezone.
So, How can I tell excel to read it correctly?
OR any solution to this problem?

Body:
Try...

select date(date_trunc('month', install_ts)) AS month, count(id) AS count from api_booking

The date()  strips out the time from a date with a time.


问:
Python Multiple Inheritance using Classes with non matching variables
How can I set up multiple inheritance in python using class constructors with arguments? I've seen many examples with no arg constructors but that's no fun... I've done this setup in c++. I am learning python and figured I would try to recreate the same setup.

How can I get my Student_Worker constructor to work without all the *args,*kwargs bs?

If override works from Person to Student and to Worker why doesn't it work from Student and Worker to Student_Worker?

If the diamond case works on classes with no arguments in any of 4 constructors why wouldn't it work in a diamond case that has arguments in the constructors?

Am I just missing something simple? I can't find a decent guide anywhere.

```<code>class Person:        #BASE CLASS
    num_of_persons = 0;

    def __init__(self,x,y,z):
        Person.num_of_persons += 1
        print("Greetings!")
        self.Name = x
        self.Sex = y
        self.DOB = z
        print("I am " + self.Name)

    def get_info(self):
        return '{} {} {}'.format(self.Name,self.Sex,self.DOB)

class Student(Person): #DERIVED CLASS
    def __init__(self, x, y, z, s):
        self.school = s
        return super().__init__(x, y, z)

    def get_info(self):
        return super().get_info() + ' {}'.format(self.school)

class Worker(Person):  #DERIVED CLASS
    def __init__(self, x, y, z, c):
        self.company = c
        return super().__init__(x, y, z)

    def get_info(self):
        return super().get_info() + ' {}'.format(self.company)

class Student_Worker(Student, Worker): #MULTIPLE DERIVED CLASS
    def __init__(self,x,y,z,s,c):
        Student.__init__(x,y,z,c)
        Worker.__init__(c)

p1 = Person("John","M", "1900")
s1 = Student("Sam","F","1910","iSchool")
w1 = Worker("Larry","M","1920","E-SITE")
sw1 = Student_Worker("Brandy","F","1930","iSchool","E-Site")

print(p1.get_info())
print(s1.get_info())
print(w1.get_info())
print(sw1.get_info())
</code>```

答:
You can try creating the constructors as following:

1) Student

```<code>class Student(Person): #DERIVED CLASS
    def __init__(self, x, y, z, s):
        Person.__init__(self,x, y, z)
        self.school = s
</code>```

2) Worker

```<code>class Worker(Person):  #DERIVED CLASS
    def __init__(self, x, y, z, c):
        Person.__init__(self,x, y, z)
        self.company = c
</code>```

3) Student Worker

```<code>class Student_Worker(Student, Worker): #MULTIPLE DERIVED CLASS
    def __init__(self,x,y,z,s,c):
        Student.__init__(self,x,y,z,s)
        Worker.__init__(self,x,y,z,c)
</code>```

If you run your code, you will get this output:

```<code>Greetings!
I am John
Greetings!
I am Sam
Greetings!
I am Larry
Greetings!
I am Brandy
Greetings!
I am Brandy
John M 1900
Sam F 1910 iSchool
Larry M 1920 E-SITE
Brandy F 1930 E-Site iSchool
</code>```

Body:
How can I set up multiple inheritance in python using class constructors with arguments? I've seen many examples with no arg constructors but that's no fun... I've done this setup in c++. I am learning python and figured I would try to recreate the same setup.

How can I get my Student_Worker constructor to work without all the *args,*kwargs bs?

If override works from Person to Student and to Worker why doesn't it work from Student and Worker to Student_Worker?

If the diamond case works on classes with no arguments in any of 4 constructors why wouldn't it work in a diamond case that has arguments in the constructors?

Am I just missing something simple? I can't find a decent guide anywhere.

class Person:        #BASE CLASS
    num_of_persons = 0;

    def __init__(self,x,y,z):
        Person.num_of_persons += 1
        print("Greetings!")
        self.Name = x
        self.Sex = y
        self.DOB = z
        print("I am " + self.Name)

    def get_info(self):
        return '{} {} {}'.format(self.Name,self.Sex,self.DOB)

class Student(Person): #DERIVED CLASS
    def __init__(self, x, y, z, s):
        self.school = s
        return super().__init__(x, y, z)

    def get_info(self):
        return super().get_info() + ' {}'.format(self.school)

class Worker(Person):  #DERIVED CLASS
    def __init__(self, x, y, z, c):
        self.company = c
        return super().__init__(x, y, z)

    def get_info(self):
        return super().get_info() + ' {}'.format(self.company)

class Student_Worker(Student, Worker): #MULTIPLE DERIVED CLASS
    def __init__(self,x,y,z,s,c):
        Student.__init__(x,y,z,c)
        Worker.__init__(c)

p1 = Person("John","M", "1900")
s1 = Student("Sam","F","1910","iSchool")
w1 = Worker("Larry","M","1920","E-SITE")
sw1 = Student_Worker("Brandy","F","1930","iSchool","E-Site")

print(p1.get_info())
print(s1.get_info())
print(w1.get_info())
print(sw1.get_info())

Body:
You can try creating the constructors as following:

1) Student

class Student(Person): #DERIVED CLASS
    def __init__(self, x, y, z, s):
        Person.__init__(self,x, y, z)
        self.school = s

2) Worker

class Worker(Person):  #DERIVED CLASS
    def __init__(self, x, y, z, c):
        Person.__init__(self,x, y, z)
        self.company = c

3) Student Worker

class Student_Worker(Student, Worker): #MULTIPLE DERIVED CLASS
    def __init__(self,x,y,z,s,c):
        Student.__init__(self,x,y,z,s)
        Worker.__init__(self,x,y,z,c)

If you run your code, you will get this output:

Greetings!
I am John
Greetings!
I am Sam
Greetings!
I am Larry
Greetings!
I am Brandy
Greetings!
I am Brandy
John M 1900
Sam F 1910 iSchool
Larry M 1920 E-SITE
Brandy F 1930 E-Site iSchool


问:
How to set several default CSS stylesheet for an application with JavaFX 9 (a replace for StyleManager)?
Whose damn idea it was to exclude StyleManager without direct and clear replacement - it broke many programs as I see!

I need to make some restyling for the whole application (custom components, custom pseudo classes, custom platform-specific patches etc.).
In JavaFX 8 I could use: com.sun.javafx.css.StyleManager.getInstance().addUserAgentStylesheet("MyShit.css");

But in Java 9 StyleManager is not available. So is there a way to set CSS for every scene?

Using "Application.setUserAgentStylesheet" is not an option because I don't want to lose default lookandfeel and I already call it to set MODENA style. I want to extend the default CSS not to replace it.
And I don't want to rewrite the whole MODENA also (obviously).

And I really don't want to set the same stylesheet for every form/scene in the application manually (or add it to every FXML file). There many forms, dynamically constructed dialogs. And the main reason, there are parts (and libraries) which is shared between several applications so I don't want to hardcode any stylesheets (which might have different names and paths for different applications).

So I need a way to set an additional stylesheet for every possible scene of the application in one point of the program. Is that possible in FX9?

P.S. I looked into custom FXML loaders, CSS loaders, scene loaders and other ways to intercept scene creation - there is no way!

答:
It's just another lack of JavaFX - simply use the JVM parameter below to make the StyleManager accessible.</p>

```<code>--add-exports=javafx.graphics/com.sun.javafx.css=ALL-UNNAMED
</code>```

Body:
It's just another lack of JavaFX - simply use the JVM parameter below to make the StyleManager accessible.

--add-exports=javafx.graphics/com.sun.javafx.css=ALL-UNNAMED


问:
Migrate huge cassandra table to another cluster using spark
I want to migrate our old Cassandra cluster to a new one.

Requirements:-

I have a cassandra cluster of 10 nodes and the table i want to migrate is ~100GB. I am using spark for migrating the data. My spark cluster has 10 nodes and each node has around 16GB memory.
In the table we have some junk data which i don't want to migrate to the new table. eg:- Let's say i don't want to transfer the rows which has the cid = 1234. So, what is the best way to migrate this using spark job ? I can't put a where filtering on the cassandraRdd directly as the cid is not the only column included in partitioned key.

Cassandra Table:-

```<code>test_table (
    cid text,
    uid text,
    key text,
    value map<text, timestamp>,
    PRIMARY KEY ((cid, uid), key)
)
</code>```

Sample Data:-

```<code>cid   | uid                | key       | value
------+--------------------+-----------+-------------------------------------------------------------------------
 1234 | 899800070709709707 | testkey1  | {'8888': '2017-10-22 03:26:09+0000'}
 6543 | 097079707970709770 | testkey2  | {'9999': '2017-10-20 11:08:45+0000', '1111': '2017-10-20 15:31:46+0000'}
</code>```

I am thinking of something like below. But i guess this is not the best efficient approach.

```<code>val filteredRdd = rdd.filter { row => row.getString("cid") != "1234" }
filteredRdd.saveToCassandra(KEYSPACE_NAME,NEW_TABLE_NAME)
</code>```

What will be the best possible approach here ?

答:
That method is pretty good. You may want to write it in DataFrames to take advantage of the row encoding but this may only have a slight benefit. The key bottleneck in this operation will be writing and reading from Cassandra.</p>

DF Example

```<code>spark
  .read
  .format("org.apache.spark.sql.cassandra")
  .option("keyspace", ks)
  .option("table", table)
  .load
  .filter( 'cid !== "1234" )
  .write
  .format("org.apache.spark.sql.cassandra")
  .option("keyspace", ks2)
  .option("table", table2)
  .save
</code>```

Body:
I want to migrate our old Cassandra cluster to a new one.

Requirements:-

I have a cassandra cluster of 10 nodes and the table i want to migrate is ~100GB. I am using spark for migrating the data. My spark cluster has 10 nodes and each node has around 16GB memory.
In the table we have some junk data which i don't want to migrate to the new table. eg:- Let's say i don't want to transfer the rows which has the cid = 1234. So, what is the best way to migrate this using spark job ? I can't put a where filtering on the cassandraRdd directly as the cid is not the only column included in partitioned key.

Cassandra Table:-

test_table (
    cid text,
    uid text,
    key text,
    value map<text, timestamp>,
    PRIMARY KEY ((cid, uid), key)
)

Sample Data:-

cid   | uid                | key       | value
------+--------------------+-----------+-------------------------------------------------------------------------
 1234 | 899800070709709707 | testkey1  | {'8888': '2017-10-22 03:26:09+0000'}
 6543 | 097079707970709770 | testkey2  | {'9999': '2017-10-20 11:08:45+0000', '1111': '2017-10-20 15:31:46+0000'}

I am thinking of something like below. But i guess this is not the best efficient approach.

val filteredRdd = rdd.filter { row => row.getString("cid") != "1234" }
filteredRdd.saveToCassandra(KEYSPACE_NAME,NEW_TABLE_NAME)

What will be the best possible approach here ?

Body:
That method is pretty good. You may want to write it in DataFrames to take advantage of the row encoding but this may only have a slight benefit. The key bottleneck in this operation will be writing and reading from Cassandra.

DF Example

spark
  .read
  .format("org.apache.spark.sql.cassandra")
  .option("keyspace", ks)
  .option("table", table)
  .load
  .filter( 'cid !== "1234" )
  .write
  .format("org.apache.spark.sql.cassandra")
  .option("keyspace", ks2)
  .option("table", table2)
  .save


问:
Launching an executable from a website?
We're developing a site that will only run on the intranet, and computers with access to this intranet will have this executable installed.  We can't have any "Would you like to open [filename].exe?" prompts.  Click a link and the program begins running.

I realize that giving websites the ability to run executables on the client machine is very, very bad, but management refuses to budge on this.

Machines will have Windows (XP or up) with Firefox 3.

答:
Been there done that. MIME types (accepted answer at the moment I add this) requires a lot of configuring on client and server.This is quite a bit of work, and you end up with temporary files etc.

Our solution was to add our own "Custom URL Protocol Handler". Basically, add URL type x-our-intranet and make your corporate app the URL handler for it. Now any  link will start your corporate app, passing "x-our-intrenet:foo" as a command-line argument. All it takes is a client-side registry entry, similar to the MIME types.

OwnerDisplayName: Tinister

ContentLicense: CC BY-SA 2.5

Title: Launching an executable from a website?

OwnerDisplayName: MSalters


问:
function switching between singular and plural?
I'm looking for a function that given a string it switches the string to singular/plural. I need it to work for european languages other than English.

Are there any functions that can do the trick? (Given a string to convert and the language?)

Thanks

答:
This is not easy: each language has its own rules for forming plurals of nouns. In English it tends to be that you put "-s" on the end of a word, unless it ends in "-x", "-s", "-z", "-sh", "-ch" in which case you add "-es". But then there's "mouse"=>"mice", "sheep"=>"sheep" etc.

The first thing to do, then, is to find out what the rule(s) are for forming the plural from the singular noun in the language(s) you want to work with. But that's not the whole solution. Another problem is recognising nouns. If you are given a noun, and need to convert it from singular to plural that's not too hard, but if you are given a piece of free text and you have to find the singular nouns and convert them to plural, that's a lot harder. You can get lists of nouns, but of course some words can be nouns and verbs ("hunt", "fish", "break" etc.) so then you need to parse the text to identify the nouns.

It's a big problem. There's probably an AI system out there that would do what you need, but I don't imagine there'll be anything free that does it all.

ContentLicense: CC BY-SA 4.0


问:
What does the turtle.tilt() method do?
https://docs.python.org/2/library/turtle.html#turtle.tilt

```<code>def right():
    turtle.tilt(30)
def left():
    turtle.tilt(-30)
def move():
    turtle.fd(100)

wn.onkey(left,'Left')
wn.onkey(right,'Right')
wn.onkey(move,'Up')
wn.listen()
</code>```

Answer: I'm trying to tilt a external shape(image file), which does not work as specified in the turtle.addshape section of the turtle documentation. https://docs.python.org/2/library/turtle.html#turtle.addshape

答:
The method does what it says on the tin: rotate the turtle shape without altering the heading of the turtle.

The turtle library displays a shape at the current turtle position on the screen. The default shape is an arrow, but several other options are available. The shape marks the current position, and is also indicative of the heading of the turtle.

So the shape can be rotated. It usually rotates together with the heading of the turtle; the direction that a forward command will move the turtle in. However, you can also rotate the shape independently from the heading, and turtle.tilt() does this by a certain number of degrees.

The documentation includes a short sample of code to demonstrate what this means. It sets the shape to a circle, then stretches out the shape to form an ellipsis. It then tilts the ellipsis by 30 degrees, moves the turtle forward to show that it still moves in the default direction (straight to the right), tilts the ellipsis again by another 30 degrees and moves forward once more, again showing that the tilt did not alter the direction.

However, if you are trying to use an external GIF image for the shape, that those shapes then do not rotate. From the turtle.addshape() documentation:

Note: Image shapes do not rotate when turning the turtle, so they do not display the heading of the turtle!

Setting the shape tilt won't have any effect on such shapes, and they won't rotate to show the turtle heading either.

Title: What does the turtle.tilt() method do?

Body:
https://docs.python.org/2/library/turtle.html#turtle.tilt

def right():
    turtle.tilt(30)
def left():
    turtle.tilt(-30)
def move():
    turtle.fd(100)

wn.onkey(left,'Left')
wn.onkey(right,'Right')
wn.onkey(move,'Up')
wn.listen()

Answer: I'm trying to tilt a external shape(image file), which does not work as specified in the turtle.addshape section of the turtle documentation. https://docs.python.org/2/library/turtle.html#turtle.addshape


问:
In C, how to add 3rd party Libraries and call from my existing code base using Makefile
I am new to IOT and cloud.

For IOT project, we are trying to send on the fly data to cloud for Analytics.
We are using only c, cpp code in my target board. Debian OS.

Every one second, 2 seconds, 3 seconds different types of data will come.

In my target board, I want to use 3rd party libraries(https_client) to send data to the cloud. I need to hit the service(URL) in the cloud with data (using only GET method).

For this, I downloaded https_client code and trying to integrate into my code base.

In the below 1st make file is original Makefile, 2nd one is only 3rd party s/w Makefile, the 3rd one is modified original Makefile to integrate 3rd party library.

In my target board, we don't have much space, so what is best light weight approach to send data to the cloud? My cloud will support only https and WSS.
Is my approach is correct? Any other easy way is available?

In the modified Makefile I am getting below error.

make: *** No rule to make target

  `https_client-master/https_client-master/main.c', needed by `all'.

  Stop.

My changes in Makefile is not the standard way. Can anyone review my modified Makefile and correct me.

Waiting for your valuable suggestion.

```<code>#---------------------------------------------------------------------------
-
--
#1.  Below is the original make file of my existing code base
#---------------------------------------------------------------------------
---
SOURCES=./SRC/MMC/Main.cpp \
    ./SRC/MMC/ModbusMasterController.cpp \
    ./SRC/DM/DeviceManager.cpp \
    .......
    ./Wrapper/MtrWrapper.cpp

OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=BusMaster
CFLAGS = -c -w -I/usr/include/libxml2 -I./INC/Common -I./INC/ADM -I./INC/MMC
-I./INC/DM  -I./INC/CM  -I./INC/MMT -I./INC/MPI -I./INC/MMT/DataProc -
I./INC/MMT/CmdProc -I./INC/MMT/CmdProc/Fileoperations -I./INC/SH -
I./INC/FT_MBUS -I./INC/Timer -I./Wrapper -I./INC/DC -Wall

LDFLAGS = -Bdynamic -lSharedMemory -lMessageQueue -luspepc -lxml2 -
lmbusmaster -lrt

CC=g++

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
$(CC) $(OBJECTS) -o $@ $(LDFLAGS)

.cpp.o:
$(CC) $(CFLAGS) $< -o $@

clean:
rm -rf $(OBJECTS) $(EXECUTABLE)

#----------------------------------------original make end------------------
 -
-------------------

#----------------------------------------2. Below is the 3rd pary Library
Makefile I want to add--------------------------------------
#CROSS = arm-linux-gnueabihf-

MAKE = make

CC = $(CROSS)gcc
LD = $(CROSS)ld
STRIP = $(CROSS)strip

ROOT_DIR = $(CURDIR)
MBEDTLS = $(ROOT_DIR)/mbedtls

CFLAGS = -fPIC -DHAVE_CONFIG_H -D_U_="__attribute__((unused))" -O2
LDFLAGS =

INCLUDES = -I$(MBEDTLS)/include
LIBS = $(MBEDTLS)/library/libmbedx509.a $(MBEDTLS)/library/libmbedtls.a
$(MBEDTLS)/library/libmbedcrypto.a

SOURCES = main.c https.c

OBJS = $(SOURCES:.c=.o)

.SUFFIXES:.c .o

all: https_client

mbedtls_make:
@for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir ; \
    if [ $$? != 0 ]; then exit 1; fi; \
done

https_client: mbedtls_make $(OBJS)
@echo Linking: $@ ....
$(CC) -o $@ $(OBJS) $(LDFLAGS) $(LIBS)
$(STRIP) -s $@

.c.o:
@echo Compiling: $< ....
$(CC) -c $(CFLAGS) $(INCLUDES) -o $@ $<

clean: mbedtls_clean
rm -f https_client *.o

mbedtls_clean:
 @for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir clean; \
    if [ $$? != 0 ]; then exit 1; fi; \
 done
#----------------------------------------3rd pary Library Makefile end------
  -
-------------------------------

#----------------------------------------3. Modified original Makefile to
add
3rd party library----------------

SOURCES=./SRC/MMC/Main.cpp \
    ./SRC/MMC/ModbusMasterController.cpp \
    ./SRC/DM/DeviceManager.cpp \
    .......
    ./Wrapper/MtrWrapper.cpp

 SOURCES2=./https_client-master/https_client-master/main.c \
    ./https_client-master/https_client-master/https.c

OBJECTS=$(SOURCES1:.cpp=.o)
OBJS=$(SOURCES2:.c=.o)
.SUFFIXES:.c .o
ROOT_DIR = $(CURDIR)
MBEDTLS = $(ROOT_DIR)/https_client-master/https_client-master/mbedtls
EXECUTABLE1=BusMaster
EXECUTABLE2=https_client
CFLAGS = -c -w -I/usr/include/libxml2 -I./INC/Common -I./INC/ADM -I./INC/MMC
-I./INC/DM  -I./INC/CM  -I./INC/MMT -I./INC/MPI -I./INC/MMT/DataProc -
I./INC/MMT/CmdProc -I./INC/MMT/CmdProc/Fileoperations -I./INC/SH -
I./INC/FT_MBUS -I./INC/Timer -I./Wrapper -I./INC/DC -Wall
CFLAGS2 = -fPIC -DHAVE_CONFIG_H -D_U_="__attribute__((unused))" -O2
INCLUDES = -I$(MBEDTLS)/include
LIBS = $(MBEDTLS)/library/libmbedx509.a $(MBEDTLS)/library/libmbedtls.a
$(MBEDTLS)/library/libmbedcrypto.a
LDFLAGS = -Bdynamic -lSharedMemory -lMessageQueue -luspepc -lxml2 -
lmbusmaster -lrt
LDFLAGS2 =
STRIP = strip

CC1=g++
CC2=gcc

 all: $(SOURCES1) $(EXECUTABLE1) $(SOURCES2) $(EXECUTABLE2)
 #$(SOURCES2)
 $(EXECUTABLE1): $(OBJECTS)
 @echo EXECUTABLE1:
 $(CC1) $(OBJECTS) -o $@ $(LDFLAGS)

 mbedtls_make:
 @echo mbedtls_make: ....
 @for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir ; \
    if [ $$? != 0 ]; then exit 1; fi; \
 done

 $(EXECUTABLE2): mbedtls_make $(OBJS)
 @echo Linking: $@ ....
 $(CC1) -o $@ $(OBJS) $(LDFLAGS2) $(LIBS)
 $(STRIP) -s $@

 .c.o:
 @echo Compiling c: $< ....
 $(CC2) -c $(CFLAGS2) $(INCLUDES) -o $@ $<

 .cpp.o:
 @echo Compiling cpp: $< ....
 $(CC1) $(CFLAGS) $< -o $@

 clean: mbedtls_clean
 rm -rf $(OBJECTS) $(EXECUTABLE1)
 rm -f https_client *.o
 mbedtls_clean:
 @for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir clean; \
    if [ $$? != 0 ]; then exit 1; fi; \
 done

 #------------------------------------------Modified original Makefile end--
 -
 ---------------------------------
</code>```

答:
I don't think you should have 2 lists of sources. Below is snippet of how MBEDTLS is included in Makefile.

https://github.com/acornblue/AZURE_LAB

```<code>#####################################################
# Projects/Multi/Applications/Azure_Sns_DM/Makefile
#####################################################
C_SOURCE = \
...
Middlewares/Third_Parties/mbedtls/library/aes.c \
Middlewares/Third_Parties/mbedtls/library/aesni.c \
...
-DUSE_MBED_TLS \
-DMBEDTLS_CONFIG_FILE='<mbedtls_config.h>'
...
-IMiddlewares/Third_Parties/mbedTLS/include \
</code>```

Body:
I am new to IOT and cloud.

For IOT project, we are trying to send on the fly data to cloud for Analytics.
We are using only c, cpp code in my target board. Debian OS.

Every one second, 2 seconds, 3 seconds different types of data will come.

In my target board, I want to use 3rd party libraries(https_client) to send data to the cloud. I need to hit the service(URL) in the cloud with data (using only GET method).

For this, I downloaded https_client code and trying to integrate into my code base.

In the below 1st make file is original Makefile, 2nd one is only 3rd party s/w Makefile, the 3rd one is modified original Makefile to integrate 3rd party library.

In my target board, we don't have much space, so what is best light weight approach to send data to the cloud? My cloud will support only https and WSS.
Is my approach is correct? Any other easy way is available?

In the modified Makefile I am getting below error.

make: *** No rule to make target

  `https_client-master/https_client-master/main.c', needed by `all'.

  Stop.

My changes in Makefile is not the standard way. Can anyone review my modified Makefile and correct me.

Waiting for your valuable suggestion.

#---------------------------------------------------------------------------
-
--
#1.  Below is the original make file of my existing code base
#---------------------------------------------------------------------------
---
SOURCES=./SRC/MMC/Main.cpp \
    ./SRC/MMC/ModbusMasterController.cpp \
    ./SRC/DM/DeviceManager.cpp \
    .......
    ./Wrapper/MtrWrapper.cpp

OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=BusMaster
CFLAGS = -c -w -I/usr/include/libxml2 -I./INC/Common -I./INC/ADM -I./INC/MMC
-I./INC/DM  -I./INC/CM  -I./INC/MMT -I./INC/MPI -I./INC/MMT/DataProc -
I./INC/MMT/CmdProc -I./INC/MMT/CmdProc/Fileoperations -I./INC/SH -
I./INC/FT_MBUS -I./INC/Timer -I./Wrapper -I./INC/DC -Wall

LDFLAGS = -Bdynamic -lSharedMemory -lMessageQueue -luspepc -lxml2 -
lmbusmaster -lrt

CC=g++

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
$(CC) $(OBJECTS) -o $@ $(LDFLAGS)

.cpp.o:
$(CC) $(CFLAGS) $< -o $@

clean:
rm -rf $(OBJECTS) $(EXECUTABLE)

#----------------------------------------original make end------------------
 -
-------------------

#----------------------------------------2. Below is the 3rd pary Library
Makefile I want to add--------------------------------------
#CROSS = arm-linux-gnueabihf-

MAKE = make

CC = $(CROSS)gcc
LD = $(CROSS)ld
STRIP = $(CROSS)strip

ROOT_DIR = $(CURDIR)
MBEDTLS = $(ROOT_DIR)/mbedtls

CFLAGS = -fPIC -DHAVE_CONFIG_H -D_U_="__attribute__((unused))" -O2
LDFLAGS =

INCLUDES = -I$(MBEDTLS)/include
LIBS = $(MBEDTLS)/library/libmbedx509.a $(MBEDTLS)/library/libmbedtls.a
$(MBEDTLS)/library/libmbedcrypto.a

SOURCES = main.c https.c

OBJS = $(SOURCES:.c=.o)

.SUFFIXES:.c .o

all: https_client

mbedtls_make:
@for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir ; \
    if [ $$? != 0 ]; then exit 1; fi; \
done

https_client: mbedtls_make $(OBJS)
@echo Linking: $@ ....
$(CC) -o $@ $(OBJS) $(LDFLAGS) $(LIBS)
$(STRIP) -s $@

.c.o:
@echo Compiling: $< ....
$(CC) -c $(CFLAGS) $(INCLUDES) -o $@ $<

clean: mbedtls_clean
rm -f https_client *.o

mbedtls_clean:
 @for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir clean; \
    if [ $$? != 0 ]; then exit 1; fi; \
 done
#----------------------------------------3rd pary Library Makefile end------
  -
-------------------------------

#----------------------------------------3. Modified original Makefile to
add
3rd party library----------------

SOURCES=./SRC/MMC/Main.cpp \
    ./SRC/MMC/ModbusMasterController.cpp \
    ./SRC/DM/DeviceManager.cpp \
    .......
    ./Wrapper/MtrWrapper.cpp

 SOURCES2=./https_client-master/https_client-master/main.c \
    ./https_client-master/https_client-master/https.c

OBJECTS=$(SOURCES1:.cpp=.o)
OBJS=$(SOURCES2:.c=.o)
.SUFFIXES:.c .o
ROOT_DIR = $(CURDIR)
MBEDTLS = $(ROOT_DIR)/https_client-master/https_client-master/mbedtls
EXECUTABLE1=BusMaster
EXECUTABLE2=https_client
CFLAGS = -c -w -I/usr/include/libxml2 -I./INC/Common -I./INC/ADM -I./INC/MMC
-I./INC/DM  -I./INC/CM  -I./INC/MMT -I./INC/MPI -I./INC/MMT/DataProc -
I./INC/MMT/CmdProc -I./INC/MMT/CmdProc/Fileoperations -I./INC/SH -
I./INC/FT_MBUS -I./INC/Timer -I./Wrapper -I./INC/DC -Wall
CFLAGS2 = -fPIC -DHAVE_CONFIG_H -D_U_="__attribute__((unused))" -O2
INCLUDES = -I$(MBEDTLS)/include
LIBS = $(MBEDTLS)/library/libmbedx509.a $(MBEDTLS)/library/libmbedtls.a
$(MBEDTLS)/library/libmbedcrypto.a
LDFLAGS = -Bdynamic -lSharedMemory -lMessageQueue -luspepc -lxml2 -
lmbusmaster -lrt
LDFLAGS2 =
STRIP = strip

CC1=g++
CC2=gcc

 all: $(SOURCES1) $(EXECUTABLE1) $(SOURCES2) $(EXECUTABLE2)
 #$(SOURCES2)
 $(EXECUTABLE1): $(OBJECTS)
 @echo EXECUTABLE1:
 $(CC1) $(OBJECTS) -o $@ $(LDFLAGS)

 mbedtls_make:
 @echo mbedtls_make: ....
 @for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir ; \
    if [ $$? != 0 ]; then exit 1; fi; \
 done

 $(EXECUTABLE2): mbedtls_make $(OBJS)
 @echo Linking: $@ ....
 $(CC1) -o $@ $(OBJS) $(LDFLAGS2) $(LIBS)
 $(STRIP) -s $@

 .c.o:
 @echo Compiling c: $< ....
 $(CC2) -c $(CFLAGS2) $(INCLUDES) -o $@ $<

 .cpp.o:
 @echo Compiling cpp: $< ....
 $(CC1) $(CFLAGS) $< -o $@

 clean: mbedtls_clean
 rm -rf $(OBJECTS) $(EXECUTABLE1)
 rm -f https_client *.o
 mbedtls_clean:
 @for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir clean; \
    if [ $$? != 0 ]; then exit 1; fi; \
 done

 #------------------------------------------Modified original Makefile end--
 -
 ---------------------------------

Body:
I don't think you should have 2 lists of sources. Below is snippet of how MBEDTLS is included in Makefile.

https://github.com/acornblue/AZURE_LAB

#####################################################
# Projects/Multi/Applications/Azure_Sns_DM/Makefile
#####################################################
C_SOURCE = \
...
Middlewares/Third_Parties/mbedtls/library/aes.c \
Middlewares/Third_Parties/mbedtls/library/aesni.c \
...
-DUSE_MBED_TLS \
-DMBEDTLS_CONFIG_FILE='<mbedtls_config.h>'
...
-IMiddlewares/Third_Parties/mbedTLS/include \


问:
Multi-platform programming language with GUI
I want to create a multi-platform application with the focus on handling data from serial port, data processing/analysis and plotting. By now I wrote the application in Python (with a GUI generated by pyQTgraph) which works quiet well - but it is not possible to export my .py to .exe or .app (for Windows and Mac OS). I tried many tools like py2exe, PyInstaller, ...

Now I'm looking for a multi-platform programming language (C, C++, ..., but not Java) witch makes the transfer to other OS easy. Preferably it is possible to transfer the application frow Windows to Mac without big code-changes or redesigning the GUI. It is a lightweight application which should run without a previous installation.

Do you have some hints which programming language and frontend (like QT) is the best for the job?

Does your suggested language works well with serial-port-data?

How does the workflow from writing the code to exporting the final .exe/.app looks like?

Best and thanks

答: You should probably take a look at Xojo. It builds separate, native apps for Windows, macOS and Linux from the same source project. It also has serial support.</p>


问:
Creating JavaScript dictionary while preserving quotes and escapes
I've got the following object:

```<code>var data = {
            "parameter": []
        };
</code>```

I want to add an element to it like so, preserving the quotes on the keys as well as the escapes within the string values:

```<code>data.parameter.push({
                "name": "TIBCO_Copy",
                "value": "[{\"Source_Server\":[" + tibcoCopyJobs.map(function (i) { return i.sourceServer; }).join(',') +
                                        "]},{\"Source_Path\":[" + tibcoCopyJobs.map(function (i) { return i.sourcePath; }).join(',') +
                                        "]},{\"Destination_Server\":[" + tibcoCopyJobs.map(function (i) { return i.destinationServer; }).join(',') +
                                        "]},{\"Destination_Path\":[" + tibcoCopyJobs.map(function (i) { return i.destinationPath; }).join(',') + "]}]"
            });
</code>```

Expected result:

```<code>{
  "parameter": [
    {
      "name": "TIBCO_Copy",
      "value": "[{\"Source_Server\":[1s, 2s, 3s]},{\"Source_Path\":[1sp, 2sp, 3sp]},{\"Destination_Server\":[1d, 2d, 3d]},{\"Destination_Path\":[1dp, 2dp, 3dp]}]"
    }
  ]
}
</code>```

Actual result as seen in chrome inspector:

```<code>name: "TIBCO_Copy",
value: "[{"Source_Server":[1,5]},{"Source_Path":[2,6]},{"Destination_Server":[3,7]},{"Destination_Path":[4,8]}]"
</code>```

Notice that it interpreted the escaped quotes around the nested keys as well as the regular quotes on the top-level keys. Using JSON.stringify() preserves the escapes, but adds another set of quotes, making it:

```<code>name: "TIBCO_Copy",
value: ""[{\"Source_Server\":[1,5]},{\"Source_Path\":[2,6]…on_Server\":[3,7]},{\"Destination_Path\":[4,8]}]""
</code>```

In all of these though, I still have the issue of the name and value keys being interpreted since I can't seem to escape them.

I need it to be formatted this way because it gets POSTed to Jenkins to trigger a remote build, and then sent to Ansible via the Build over SSH plugin to be executed with Ansible's CLI. Thus the escaping is necessary for the data to be in the correct format when it reaches its destination.

答:
I figured it out.

Instead of using JSON.stringify(), I just escape a backslash in addition to the escaped quote. The result is a \ followed by a ", being \". So now it looks like this:

```<code>data.parameter.push({
                "name": "TIBCO_Copy",
                "value": "[{\\\"Source_Server\\\":[" + tibcoCopyJobs.map(function (i) { return i.sourceServer; }).join(',') +
                        "]},{\\\"Source_Path\\\":[" + tibcoCopyJobs.map(function (i) { return i.sourcePath; }).join(',') +
                        "]},{\\\"Destination_Server\\\":[" + tibcoCopyJobs.map(function (i) { return i.destinationServer; }).join(',') +
                        "]},{\\\"Destination_Path\\\":[" + tibcoCopyJobs.map(function (i) { return i.destinationPath; }).join(',') + "]}]"
            });
</code>```

EDIT: The above was a solution for preserving format when being parsed by the JS interpreter and was useful for when the data needs to be used again before sending it off with an HTTP request. However, my use case for the data changed, and it turns out that @JoshuaK in the comments on the original question above was mostly correct, if not spot on. Essentially, I left it with the singly escaped quotes rather than the escaped back slash with an escaped quote. When using it to POST via the standard method in AngularJS using $http I was able to declare the form-data to be a JSON object like so:

data: 'json=' + JSON.stringify(data)

The above is exactly as it appears in my associative array (dictionary) object containing the parameters for the call to $http. You can also see this other question for details on how I POSTed the data using the $http service of AngularJS.

Body:
I've got the following object:

var data = {
            "parameter": []
        };

I want to add an element to it like so, preserving the quotes on the keys as well as the escapes within the string values:

data.parameter.push({
                "name": "TIBCO_Copy",
                "value": "[{\"Source_Server\":[" + tibcoCopyJobs.map(function (i) { return i.sourceServer; }).join(',') +
                                        "]},{\"Source_Path\":[" + tibcoCopyJobs.map(function (i) { return i.sourcePath; }).join(',') +
                                        "]},{\"Destination_Server\":[" + tibcoCopyJobs.map(function (i) { return i.destinationServer; }).join(',') +
                                        "]},{\"Destination_Path\":[" + tibcoCopyJobs.map(function (i) { return i.destinationPath; }).join(',') + "]}]"
            });

Expected result:

{
  "parameter": [
    {
      "name": "TIBCO_Copy",
      "value": "[{\"Source_Server\":[1s, 2s, 3s]},{\"Source_Path\":[1sp, 2sp, 3sp]},{\"Destination_Server\":[1d, 2d, 3d]},{\"Destination_Path\":[1dp, 2dp, 3dp]}]"
    }
  ]
}

Actual result as seen in chrome inspector:

name: "TIBCO_Copy",
value: "[{"Source_Server":[1,5]},{"Source_Path":[2,6]},{"Destination_Server":[3,7]},{"Destination_Path":[4,8]}]"

Notice that it interpreted the escaped quotes around the nested keys as well as the regular quotes on the top-level keys. Using JSON.stringify() preserves the escapes, but adds another set of quotes, making it:

name: "TIBCO_Copy",
value: ""[{\"Source_Server\":[1,5]},{\"Source_Path\":[2,6]…on_Server\":[3,7]},{\"Destination_Path\":[4,8]}]""

In all of these though, I still have the issue of the name and value keys being interpreted since I can't seem to escape them.

I need it to be formatted this way because it gets POSTed to Jenkins to trigger a remote build, and then sent to Ansible via the Build over SSH plugin to be executed with Ansible's CLI. Thus the escaping is necessary for the data to be in the correct format when it reaches its destination.

Body:
I figured it out.

Instead of using JSON.stringify(), I just escape a backslash in addition to the escaped quote. The result is a \ followed by a ", being \". So now it looks like this:

data.parameter.push({
                "name": "TIBCO_Copy",
                "value": "[{\\\"Source_Server\\\":[" + tibcoCopyJobs.map(function (i) { return i.sourceServer; }).join(',') +
                        "]},{\\\"Source_Path\\\":[" + tibcoCopyJobs.map(function (i) { return i.sourcePath; }).join(',') +
                        "]},{\\\"Destination_Server\\\":[" + tibcoCopyJobs.map(function (i) { return i.destinationServer; }).join(',') +
                        "]},{\\\"Destination_Path\\\":[" + tibcoCopyJobs.map(function (i) { return i.destinationPath; }).join(',') + "]}]"
            });

EDIT: The above was a solution for preserving format when being parsed by the JS interpreter and was useful for when the data needs to be used again before sending it off with an HTTP request. However, my use case for the data changed, and it turns out that @JoshuaK in the comments on the original question above was mostly correct, if not spot on. Essentially, I left it with the singly escaped quotes rather than the escaped back slash with an escaped quote. When using it to POST via the standard method in AngularJS using $http I was able to declare the form-data to be a JSON object like so:

data: 'json=' + JSON.stringify(data)

The above is exactly as it appears in my associative array (dictionary) object containing the parameters for the call to $http. You can also see this other question for details on how I POSTed the data using the $http service of AngularJS.


问:
Perl6: use module inside other module
I have 4 files.

C:\perlCode2\start.pl6

C:\perlCode2\file0.pm6

C:\perlCode2\folder1\file1.pm6

C:\perlCode2\folder2\file2.pm6

start.pl6 is used to run my program. The 3 module files contain or generate data that is eventually used by start.pl6. I use atom.io to run the code.

Here is the code:

start.pl6:

```<code>use v6;
use lib ".";
use file0;
use lib "folder1";
use file1;
use lib "folder2";
use file2;

say 'start';
my $file0 = file0.new();
say $file0.mystr;
my $file1 = file1.new();
say $file1.mystr;
my $file2 = file2.new();
say $file2.mystr;
say 'end';
</code>```

file0.pm6:

```<code>class file0 is export {
  has Str $.mystr = "file 0";

  submethod BUILD() {
    say "hello file 0";
  }
}
</code>```

file1.pm6:

```<code>class file1 is export {
  has Str $.mystr = "file 1";
}
</code>```

file2.pm6:

```<code>class file2 is export {
  has Str $.mystr = "file 2";
}
</code>```

output:

```<code>start
hello file 0
file 0
file 1
file 2
end
[Finished in 0.51s]
</code>```

Rather than making instances of all 3 module files inside start.pl6, I want to create an instance of file2 inside file1, and of file1 inside file0. This way I only have to create an instance of file0 in start.pl6 to see the same output;

Here are the changes I had in mind:

file1.pm6:

```<code>use lib "../folder2";
use "file2.pl6";

class file1 is export {
  has Str $.mystr = "file 1";

  submethod BUILD() {
    my $file2 = file2.new();
    $!mystr = $!mystr ~ "\n" ~ $file2.mystr;
        # I want to instantiate file2 inside the constructor,
        # so I can be sure the line
        # $!mystr = $!mystr ~ "\n" ~ $file2.mystr;
        # takes effect before i call any of file0's methods;
  }
}
</code>```

file0.pm6:

```<code>use lib "folder1";
use "file1.pl6";

class file0 is export {
  has Str $.mystr = "file 0";

  submethod BUILD() {
    say "hello file 0";
    my $file1 = file1.new();
    $!mystr = $!mystr ~ "\n" ~ $file1.mystr;
  }
}
</code>```

In file0, the lines
use lib "folder1";
use "file1.pl6";
 yields this error:

```<code>===SORRY!=== Error while compiling C:\perlCode2\file0.pm6 (file0)
'use lib' may not be pre-compiled
at C:\perlCode2\file0.pm6 (file0):2
------> use lib "folder1/file1.pl6"<HERE>;
[Finished in 0.584s]
</code>```

I file1, the line
use lib "../folder2";
use "file2";
doesnt work but also doesnt give an error. I just get the output:
[Finished in 0.31s]

In the end, the file start.pl6 should look like this to produce the output:

start.pl6:

```<code>use v6;
use lib ".";
use file0;

say 'start';
my $file0 = file0.new();
say $file0.mystr;
say 'end';
</code>```

output:

```<code>start
hello file 0
file 0
file 1
file 2
end
</code>```

答:
What you are trying to do makes no sense to me. It seems you are putting those modules in folders arbitrarily.

If the names of those modules does make sense here is how I might structure it.

C:\perlCode2\start.pl6
C:\perlCode2\lib\file0.pm6
C:\perlCode2\lib\folder1\file1.pm6
C:\perlCode2\lib\folder2\file2.pm6
```

<p><em>start.pl6</em>:</p>

<pre class="lang-perl6 prettyprint-override"><code>use v6;

END say "[Finished in {(now - $*INIT-INSTANT).fmt("%0.2fs")}";

use lib 'lib';
use file0;

say 'start';
my $file0 = file0.new;
say $file0.mystr;
say 'end';
</code>```

lib\file0.pm6:

use folder1::file1;

class file0 is export {
  has Str $.mystr = "file 0";

  submethod TWEAK() {
    say "hello file 0";
    $!mystr ~= "\n" ~ folder1::file1.new.mystr;
  }
}
```

<p><em>lib\folder1\file1.pm6</em>:</p>

<pre class="lang-perl6 prettyprint-override"><code>use folder2::file2;

class folder1::file1 is export {
  has Str $.mystr = "file 1";

  submethod TWEAK() {
    $!mystr ~= "\n" ~ folder2::file2.new.mystr;
  }
}
</code>```

lib\folder2\file2.pm6

class folder2::file2 is export {
  has Str $.mystr = "file 2";
}
```

Title: Perl6: use module inside other module

Body:
I have 4 files.

C:\perlCode2\start.pl6

C:\perlCode2\file0.pm6

C:\perlCode2\folder1\file1.pm6

C:\perlCode2\folder2\file2.pm6

start.pl6 is used to run my program. The 3 module files contain or generate data that is eventually used by start.pl6. I use atom.io to run the code.

Here is the code:

start.pl6:

use v6;
use lib ".";
use file0;
use lib "folder1";
use file1;
use lib "folder2";
use file2;

say 'start';
my $file0 = file0.new();
say $file0.mystr;
my $file1 = file1.new();
say $file1.mystr;
my $file2 = file2.new();
say $file2.mystr;
say 'end';

file0.pm6:

class file0 is export {
  has Str $.mystr = "file 0";

  submethod BUILD() {
    say "hello file 0";
  }
}

file1.pm6:

class file1 is export {
  has Str $.mystr = "file 1";
}

file2.pm6:

class file2 is export {
  has Str $.mystr = "file 2";
}

output:

start
hello file 0
file 0
file 1
file 2
end
[Finished in 0.51s]

Rather than making instances of all 3 module files inside start.pl6, I want to create an instance of file2 inside file1, and of file1 inside file0. This way I only have to create an instance of file0 in start.pl6 to see the same output;

Here are the changes I had in mind:

file1.pm6:

use lib "../folder2";
use "file2.pl6";

class file1 is export {
  has Str $.mystr = "file 1";

  submethod BUILD() {
    my $file2 = file2.new();
    $!mystr = $!mystr ~ "\n" ~ $file2.mystr;
        # I want to instantiate file2 inside the constructor,
        # so I can be sure the line
        # $!mystr = $!mystr ~ "\n" ~ $file2.mystr;
        # takes effect before i call any of file0's methods;
  }
}

file0.pm6:

use lib "folder1";
use "file1.pl6";

class file0 is export {
  has Str $.mystr = "file 0";

  submethod BUILD() {
    say "hello file 0";
    my $file1 = file1.new();
    $!mystr = $!mystr ~ "\n" ~ $file1.mystr;
  }
}

In file0, the lines
use lib "folder1";
use "file1.pl6";
 yields this error:

===SORRY!=== Error while compiling C:\perlCode2\file0.pm6 (file0)
'use lib' may not be pre-compiled
at C:\perlCode2\file0.pm6 (file0):2
------> use lib "folder1/file1.pl6"<HERE>;
[Finished in 0.584s]

I file1, the line
use lib "../folder2";
use "file2";
doesnt work but also doesnt give an error. I just get the output:
[Finished in 0.31s]

In the end, the file start.pl6 should look like this to produce the output:

start.pl6:

use v6;
use lib ".";
use file0;

say 'start';
my $file0 = file0.new();
say $file0.mystr;
say 'end';

output:

start
hello file 0
file 0
file 1
file 2
end

Body:
What you are trying to do makes no sense to me. It seems you are putting those modules in folders arbitrarily.

If the names of those modules does make sense here is how I might structure it.

C:\perlCode2\start.pl6
C:\perlCode2\lib\file0.pm6
C:\perlCode2\lib\folder1\file1.pm6
C:\perlCode2\lib\folder2\file2.pm6

start.pl6:

use v6;

END say "[Finished in {(now - $*INIT-INSTANT).fmt("%0.2fs")}";

use lib 'lib';
use file0;

say 'start';
my $file0 = file0.new;
say $file0.mystr;
say 'end';

lib\file0.pm6:

use folder1::file1;

class file0 is export {
  has Str $.mystr = "file 0";

  submethod TWEAK() {
    say "hello file 0";
    $!mystr ~= "\n" ~ folder1::file1.new.mystr;
  }
}

lib\folder1\file1.pm6:

use folder2::file2;

class folder1::file1 is export {
  has Str $.mystr = "file 1";

  submethod TWEAK() {
    $!mystr ~= "\n" ~ folder2::file2.new.mystr;
  }
}

lib\folder2\file2.pm6

class folder2::file2 is export {
  has Str $.mystr = "file 2";
}


问:
Moonmail/Serverless: "s-variables-<stage>-<region>" location?
I'm looking to install Moonmail. One early step of installing Moonmail is:

Add variables to s-variables-< stage >-< region >:

```<code>{
    ...,
    "apiHost": "yourendpointhost.com"
}
</code>```

I can't find the relevant file to enter this information. Where exactly do I enter this?

The files created by serverless in my Moonmail location are:
s-project.json, s-resources-cf.json, and s-templates.json

答:
The file is inside a new folder created when you ran sls project init -c -n your-lower-case-project-name. For example, if you stage is dev and your region is us-east-1, you should see this file:

```<code>_meta/variables/s-variables-dev-useast1.json
</code>```

Body:
I'm looking to install Moonmail. One early step of installing Moonmail is:

Add variables to s-variables-< stage >-< region >:

{
    ...,
    "apiHost": "yourendpointhost.com"
}

I can't find the relevant file to enter this information. Where exactly do I enter this?

The files created by serverless in my Moonmail location are:
s-project.json, s-resources-cf.json, and s-templates.json

Body:
The file is inside a new folder created when you ran sls project init -c -n your-lower-case-project-name. For example, if you stage is dev and your region is us-east-1, you should see this file:

_meta/variables/s-variables-dev-useast1.json


问:
Mailchimp in a single page app - API key made public?
My single page app has no backend per se (firebase) and now needs to interface with Mailchimp to allow visitors to register to the newsletter.

So far, I have this API key - it seems to give full access to my mailchimp account.
Can one simply call the Mailchimp api from an SPA to register, without providing an api key?

答:
You are correct, the API key gives access to your account and should therefore be kept private. There isn't a way to use the MailChimp API without providing an API key, but if you are only using it to subscribe users, you can do this through a simple AJAX call instead. This method uses a User ID instead of a private API key to identify your account.

The request below is adapted from this answer:

```<code>$.ajax({
    type: 'post',
    url: 'http://xxxxx.us#.list-manage.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?',
    data: $('form').serialize(),
    cache       : false,
    dataType    : 'json',
    contentType: "application/json; charset=utf-8",
    error       : function(err) { alert("Could not connect to the registration server. Please try again later."); },
    success     : function(data) {
        if (data.result != "success") {
            //Failed
        } else {
            //Success
        }
    }
});
</code>```

To find the values that need to be placed in the url string, follow the instructions on this page from MailChimp's knowledgebase. You'll need your username, the correct us# server, the u value (which is the User ID previously described), and the id value (which is the list ID).

Body:
You are correct, the API key gives access to your account and should therefore be kept private. There isn't a way to use the MailChimp API without providing an API key, but if you are only using it to subscribe users, you can do this through a simple AJAX call instead. This method uses a User ID instead of a private API key to identify your account.

The request below is adapted from this answer:

$.ajax({
    type: 'post',
    url: 'http://xxxxx.us#.list-manage.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?',
    data: $('form').serialize(),
    cache       : false,
    dataType    : 'json',
    contentType: "application/json; charset=utf-8",
    error       : function(err) { alert("Could not connect to the registration server. Please try again later."); },
    success     : function(data) {
        if (data.result != "success") {
            //Failed
        } else {
            //Success
        }
    }
});

To find the values that need to be placed in the url string, follow the instructions on this page from MailChimp's knowledgebase. You'll need your username, the correct us# server, the u value (which is the User ID previously described), and the id value (which is the list ID).


问:
How do I verify the order of MANIFEST.MF within jar?
I've run into interesting problem which is absolutely new to me. As I've suddenly discovered, Jar specification says that, being included, META-INF and MANIFEST.MF must be first and second entries of *.jar package and not just directory and file within archive.

I'm working with Java framework being very watchful about this requirement and not as much verbose. How do I check that META-INF and MANIFEST.MF are properly ordered within jar?

UPDATE:
Many of jars are third-party, and there are many of them. I'm not able to open these jars in notepad, excel, hexeditor, photoshop or whatever looking for byte sequences. I need command-line tool. Thanks!

UPDATE 2:
Here is the reason why I'm asking this question:
http://www.mail-archive.com/dev@felix.apache.org/msg17097.html

答:
The following command will list the contents of a JAR in order:

```<code>jar tf foo.jar
</code>```

Note that there is no actual requirement in the JAR specification for META-INF/MANIFEST.MF to appear first. However JARs built by the jar tool (supplied with the JDK) do have the manifest first, and therefore it has become a convention.

Body:
The following command will list the contents of a JAR in order:

jar tf foo.jar

Note that there is no actual requirement in the JAR specification for META-INF/MANIFEST.MF to appear first. However JARs built by the jar tool (supplied with the JDK) do have the manifest first, and therefore it has become a convention.


问:
MongoDB - custom sort aggregation with embedded doccument
The application collection includes status field and an embedded offer field which has a status field as well. an application might come with no offer.

The conditions I have to consider to sort is a bit complicated.

The order has to be:

1st: Applications with Offer and the Offer status is pending

2nd: Applications with no Offer and any value for status except these: rejected, assigned, accepted

3rd: Applications with Offer and the offer status is: rejected

4th: Applications with Offer and the offer status is: withdrawn

5th: other cases

The query I am trying is this:

```<code>db.application.aggregate([
{
    "$project": {
        "_id": 1,
        "status": 1,
        "job": 1,
        "offer": 1,
        "user": 1,
        "denormalized": 1,
        "custom_sort": {
            $cond: {
                if: { $eq: ["offer.$status", "pending"] }, then: 1,
                else: {
                    $cond: {
                        if: { $ne: ["$status", ["rejected", "assigned", "accepted"]] }, then: 2,
                        else: {
                            $cond: {
                                if: { $eq: ["offer$status", "rejected"] }, then: 3,
                                else: {
                                    $cond: {
                                        if: { $eq: ["offer$status", "withdrawn"] }, then: 4,
                                        else: 5
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
{"$sort": {"custom_sort": 1}},
{ "$project": { "_id": 1, "status": 1, "job": 1, "offer": 1, "user": 1, "denormalized": 1, "custom_sort": 1 } }
])
</code>```

The Query works. But, not as expected.
There are two problems I have:

1- If application does not have offer, the first condition will be ignored

2- how can I use and or or in if conditions

Some sample application documents:

```<code>{
    "_id" : ObjectId("59f0c8c517587d306033f9f2"),
    "status" : "new",
    "offer" : {
        "status" : "withdrawn"
    }
},

{
    "_id" : ObjectId("59f0b38517587d29bb1eb6b3"),
    "status" : "new",
    "offer" : {
        "status" : "rejected"
    }
},

{
    "_id" : ObjectId("59f0b35717587d29bb1eb6b2"),
    "status" : "new",
    "offer" : {
        "status" : "pending"
    }
},

{
    "_id" : ObjectId("58de110e46fc387b39744285"),
    "status" : "rejected"
},

{
    "_id" : ObjectId("58de119946fc3876035f823c"),
    "status" : "new"
}
</code>```

答:
There are $and and $or operators you can use in if conditions, but you don't need them in this particulr case.

You will be better with $switch case:

```<code>    "custom_sort": { $cond: {
        if: { $eq: [ { $type: "$offer" }, "object" ] },
        then: { $switch: {
            branches: [
                { case: { $eq: [ "$offer.status", "pending" ] }, then: 1 },
                { case: { $eq: [ "$offer.status", "rejected" ] }, then: 3 },
                { case: { $eq: [ "$offer.status", "withdrawn" ] }, then: 4 },
            ],
            default: 5
        } },
        else: { $cond : {
            if: { $in: [ "$status", [ "rejected", "assigned", "accepted" ] ] },
            then: 2,
            else: 5
        } }
    } }
</code>```

Body:
The application collection includes status field and an embedded offer field which has a status field as well. an application might come with no offer.

The conditions I have to consider to sort is a bit complicated.

The order has to be:

1st: Applications with Offer and the Offer status is pending

2nd: Applications with no Offer and any value for status except these: rejected, assigned, accepted

3rd: Applications with Offer and the offer status is: rejected

4th: Applications with Offer and the offer status is: withdrawn

5th: other cases

The query I am trying is this:

db.application.aggregate([
{
    "$project": {
        "_id": 1,
        "status": 1,
        "job": 1,
        "offer": 1,
        "user": 1,
        "denormalized": 1,
        "custom_sort": {
            $cond: {
                if: { $eq: ["offer.$status", "pending"] }, then: 1,
                else: {
                    $cond: {
                        if: { $ne: ["$status", ["rejected", "assigned", "accepted"]] }, then: 2,
                        else: {
                            $cond: {
                                if: { $eq: ["offer$status", "rejected"] }, then: 3,
                                else: {
                                    $cond: {
                                        if: { $eq: ["offer$status", "withdrawn"] }, then: 4,
                                        else: 5
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
{"$sort": {"custom_sort": 1}},
{ "$project": { "_id": 1, "status": 1, "job": 1, "offer": 1, "user": 1, "denormalized": 1, "custom_sort": 1 } }
])

The Query works. But, not as expected.
There are two problems I have:

1- If application does not have offer, the first condition will be ignored

2- how can I use and or or in if conditions

Some sample application documents:

{
    "_id" : ObjectId("59f0c8c517587d306033f9f2"),
    "status" : "new",
    "offer" : {
        "status" : "withdrawn"
    }
},

{
    "_id" : ObjectId("59f0b38517587d29bb1eb6b3"),
    "status" : "new",
    "offer" : {
        "status" : "rejected"
    }
},

{
    "_id" : ObjectId("59f0b35717587d29bb1eb6b2"),
    "status" : "new",
    "offer" : {
        "status" : "pending"
    }
},

{
    "_id" : ObjectId("58de110e46fc387b39744285"),
    "status" : "rejected"
},

{
    "_id" : ObjectId("58de119946fc3876035f823c"),
    "status" : "new"
}

Body:
There are $and and $or operators you can use in if conditions, but you don't need them in this particulr case.

You will be better with $switch case:

    "custom_sort": { $cond: {
        if: { $eq: [ { $type: "$offer" }, "object" ] },
        then: { $switch: {
            branches: [
                { case: { $eq: [ "$offer.status", "pending" ] }, then: 1 },
                { case: { $eq: [ "$offer.status", "rejected" ] }, then: 3 },
                { case: { $eq: [ "$offer.status", "withdrawn" ] }, then: 4 },
            ],
            default: 5
        } },
        else: { $cond : {
            if: { $in: [ "$status", [ "rejected", "assigned", "accepted" ] ] },
            then: 2,
            else: 5
        } }
    } }


问:
HSL Image Adjustements on GPU
I have an application where the user should be able to modify an image with sliders for hue, saturation and lightness. All image processing is done on the GPU using GLSL fragment shaders.

My problem is that RGB -> HSL -> RGB conversions are rather expensive on the gpu due to the extensive branching.

My question is whether I can convert the users "color adjustments" to some other color space which can more efficiently compute the adjusted image on the GPU.

答:
You could use a 3D Look Up Table to store the color transform, the table would be updated by the user variables, but there may be simpler approches.

More informations are available in GPU Gems 2.

Title: HSL Image Adjustements on GPU


问:
Passing dotenv to ActiveRecord rake tasks (no Rails)
I'm using ActiveRecords in no-Rails app and I'm trying to use dotenv with ActiveRecord rake tasks.

In the documentation of dotenv there is stated that you need to pass it to tasks like this:

```<code>require 'dotenv/tasks'

task mytask: :dotenv do
   # things that require .env
end
</code>```

But I'm loading my ActiveRecord rake tasks like this in my Rakefile:

```<code>load 'active_record/railties/databases.rake'
</code>```

How can I pass dotenv to ActiveRecord tasks?

Thanks

答:
Along with DotEnv setup, make sure you run:

```<code>rake db:environment:set
</code>```

to set the environment variables before running any commands that require ENV.

Body:
I'm using ActiveRecords in no-Rails app and I'm trying to use dotenv with ActiveRecord rake tasks.

In the documentation of dotenv there is stated that you need to pass it to tasks like this:

require 'dotenv/tasks'

task mytask: :dotenv do
   # things that require .env
end

But I'm loading my ActiveRecord rake tasks like this in my Rakefile:

load 'active_record/railties/databases.rake'

How can I pass dotenv to ActiveRecord tasks?

Thanks

Body:
Along with DotEnv setup, make sure you run:

rake db:environment:set

to set the environment variables before running any commands that require ENV.


问:
Listing by alphabetical order not ignoring special characters like "Ó"
I got some search results listed alphabetically by groups like this:

A --
Andre, Amalia...

B --
Bart, Bruno,
etc...

The problem is, if some name starts with a special character like "Ólga"
i got another group like this:

Ó --
Olga

My question: How to list names starting with "Ó" inside the group "O"? Thanks.

My code:

```<code><?php
$previous = null;
foreach($rows as $row1) {
 $firstLetter = substr($row1->titolo, 0, 1);
  if($previous !== $firstLetter) echo $firstLetter."<br />";
$previous = $firstLetter;
  echo $row1->titolo;
}
?>
</code>```

Body:
I got some search results listed alphabetically by groups like this:

A --
Andre, Amalia...

B --
Bart, Bruno,
etc...

The problem is, if some name starts with a special character like "Ólga"
i got another group like this:

Ó --
Olga

My question: How to list names starting with "Ó" inside the group "O"? Thanks.

My code:

<?php
$previous = null;
foreach($rows as $row1) {
 $firstLetter = substr($row1->titolo, 0, 1);
  if($previous !== $firstLetter) echo $firstLetter."
";
$previous = $firstLetter;
  echo $row1->titolo;
}
?>

Body:
The class Collator is part of the intl extension, so if you don't have it or you can't install it, I suggest you to use this utility conversion array in this answer Replacing accented characters php

<?php
$unwanted_array = array('Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
                        'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
                        'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
                        'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
                        'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );
$previous = null;
foreach($rows as $row1) {
    $firstLetter = substr($row1->titolo, 0, 1);
    $firstLetter = strtr( $firstLetter, $unwanted_array );
    if($previous !== $firstLetter) echo $firstLetter."<br />";
    $previous = $firstLetter;
    echo $row1->titolo;
}
?>


问:
@Output communication between child and parent. Angular 2(5)
I'm trying to learn angular 2 and am trying to set a variable in a parent component with data from my child components.  Basically I have a subheader in my parent view and I want the title and some HTML to change based on what child is loaded.

Parent component:

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ParentComponent {
  childDetails: {title: String, helperBar: String};

  onChildLoaded(childData: {
    childTitle: string,
    childHelperBar: string
  }) {
    this.childDetails ={
      title: childData.childTitle,
      helperBar: childData.childHelperBar
    };
    console.log (childDetails);
  }
}
</code>```

Child Component :

```<code>import { Component, OnInit, ViewEncapsulation, Output, EventEmitter }
from '@angular/core';

@Component({
  selector: 'app-first-child',
  templateUrl: './first-child.component.html',
  styleUrls: ['./first-child.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class FirstChildComponent implements OnInit {
  @Output() childLoaded = new EventEmitter<{childTitle: string,
childHelperBar: string}>();

  constructor() { }

  ngOnInit() {
    this.childLoaded.emit({
      childTitle: 'Dashboard',
      childHelperBar: '<div class="test"><button>Dash Button</button>
</div>'
    });
  }

}
</code>```

And finally my parent HTML:

```<code><div class="subheader">
  <h1>{{ childDetails.title }}</h1>
  {{ childDetails.helperBar }}
</div>
<nav class="sidebar">

</nav>

<main role="main" class="">
  <router-outlet (childLoaded)="onChildLoaded($event)"></router-outlet>
</main>
</code>```

For the life of me I can't get this approach to work and can't pinpoint where I'm going wrong.  I could always just put the subheader in my children but I dont like the idea of repeating the code so many times and it will make my layout a bit harder to achieve.

答:
Are you getting ? $event in your parent method?

If YES then why are you using let childDetails ={} inside parent class method . Instead you should use this.childDetails={}

```<code>onChildLoaded($event){
 this.childDetails ={ title: $event.childTitle, helperBar: $event.childHelperBar };
console.log (childDetails);
}
</code>```

and parent html shoul be

```<code><div class="subheader"> <h1>{{ childDetails.title }}</h1> {{ childDetails.helperBar }} </div>
<nav class="sidebar"> </nav>
<main role="main" class="">
 <app-first-child (childLoaded)="onChildLoaded($event)"></app-first-child> </main>
</code>```

If you don't want to use <app-first-child/> then you should use shared service

Body:
I'm trying to learn angular 2 and am trying to set a variable in a parent component with data from my child components.  Basically I have a subheader in my parent view and I want the title and some HTML to change based on what child is loaded.

Parent component:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ParentComponent {
  childDetails: {title: String, helperBar: String};

  onChildLoaded(childData: {
    childTitle: string,
    childHelperBar: string
  }) {
    this.childDetails ={
      title: childData.childTitle,
      helperBar: childData.childHelperBar
    };
    console.log (childDetails);
  }
}

Child Component :

import { Component, OnInit, ViewEncapsulation, Output, EventEmitter }
from '@angular/core';

@Component({
  selector: 'app-first-child',
  templateUrl: './first-child.component.html',
  styleUrls: ['./first-child.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class FirstChildComponent implements OnInit {
  @Output() childLoaded = new EventEmitter<{childTitle: string,
childHelperBar: string}>();

  constructor() { }

  ngOnInit() {
    this.childLoaded.emit({
      childTitle: 'Dashboard',
      childHelperBar: '
<button>Dash Button</button>

'
    });
  }

}

And finally my parent HTML:

{{ childDetails.title }}

  {{ childDetails.helperBar }}

  <router-outlet (childLoaded)="onChildLoaded($event)"></router-outlet>

For the life of me I can't get this approach to work and can't pinpoint where I'm going wrong.  I could always just put the subheader in my children but I dont like the idea of repeating the code so many times and it will make my layout a bit harder to achieve.

Body:
Are you getting ? $event in your parent method?

If YES then why are you using let childDetails ={} inside parent class method . Instead you should use this.childDetails={}

onChildLoaded($event){
 this.childDetails ={ title: $event.childTitle, helperBar: $event.childHelperBar };
console.log (childDetails);
}

and parent html shoul be

<div class="subheader"> <h1>{{ childDetails.title }}</h1> {{ childDetails.helperBar }} </div>
<nav class="sidebar"> </nav>
<main role="main" class="">
 <app-first-child (childLoaded)="onChildLoaded($event)"></app-first-child> </main>

If you don't want to use <app-first-child/> then you should use shared service