问:
How do you use an object type as a parameter for method/constructor?
I'm currently working on a Java TD game. I have a class called "Wave" that holds the enemy types to spawn (that all extend the class "Enemy") and the delay between the spawns.

```<code>public class Wave {

*I dunno what*[] enemyTypes;
int[] delays;
private Point spawnPoint;

Wave(*I dunno what*[] enemyTypes, int[] delays, Point spawnPoint) {

    this.enemyTypes = enemyTypes;
    this.delays = delays;
    this.spawnPoint = spawnPoint;

}

void spawnWave() {

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

        try {

            Thread.sleep(delays[i]);

        } catch (InterruptedException e) {
          e.printStackTrace();
        }

        Point sP = new Point(spawnPoint);

        *The enemy type to spawn* enemy = new *The enemy type to spawn*.spawn(sP);

    }

}
</code>```

}

I don't know how to code the bits within the **

答:
What about something like this?

You can get more information at Oracle Java Documentation

```<code>public class Wave<T extends Enemy> {

  List<T> enemyTypes;
  int[] delays;
  private Point spawnPoint;

  Wave(int[] delays, Point spawnPoint) {

    this.enemyTypes = new ArrayList<>();
    this.delays = delays;
    this.spawnPoint = spawnPoint;

  }

  boolean addEnemy(T enemy) {
    if(enemyTypes.contains(enemy)) {
      return false;
    }
    this.enemyTypes.add(enemy);
    return true;
  }

  void spawnWave() {

    for (int i = 0; i < enemyTypes.size(); i++) {

        try {

            Thread.sleep(delays[i]);

        } catch (Exception e) {}

        Point sP = new Point(spawnPoint);

        Enemy enemy = enemyTypes.get(i);
        enemy.spawn(sP);

    }
  }
}
</code>```

Body:
I'm currently working on a Java TD game. I have a class called "Wave" that holds the enemy types to spawn (that all extend the class "Enemy") and the delay between the spawns.

public class Wave {

*I dunno what*[] enemyTypes;
int[] delays;
private Point spawnPoint;

Wave(*I dunno what*[] enemyTypes, int[] delays, Point spawnPoint) {

    this.enemyTypes = enemyTypes;
    this.delays = delays;
    this.spawnPoint = spawnPoint;

}

void spawnWave() {

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

        try {

            Thread.sleep(delays[i]);

        } catch (InterruptedException e) {
          e.printStackTrace();
        }

        Point sP = new Point(spawnPoint);

        *The enemy type to spawn* enemy = new *The enemy type to spawn*.spawn(sP);

    }

}

}

I don't know how to code the bits within the **

Body:
What about something like this?

You can get more information at Oracle Java Documentation

public class Wave<T extends Enemy> {

  List<T> enemyTypes;
  int[] delays;
  private Point spawnPoint;

  Wave(int[] delays, Point spawnPoint) {

    this.enemyTypes = new ArrayList<>();
    this.delays = delays;
    this.spawnPoint = spawnPoint;

  }

  boolean addEnemy(T enemy) {
    if(enemyTypes.contains(enemy)) {
      return false;
    }
    this.enemyTypes.add(enemy);
    return true;
  }

  void spawnWave() {

    for (int i = 0; i < enemyTypes.size(); i++) {

        try {

            Thread.sleep(delays[i]);

        } catch (Exception e) {}

        Point sP = new Point(spawnPoint);

        Enemy enemy = enemyTypes.get(i);
        enemy.spawn(sP);

    }
  }
}


来源: stackexchange

问:
Remove Zeros Before Decimal- PowerBI
Numbers under 1 are currently being represented with a leading zero before the decimal point (example: 0.50). Because I'm working with baseball statistics (which almost never have the zero before the decimal) I would like to remove that. I want to keep the number before the decimal if its greater than 1 though. How would I do that?

For instance if I'm working with this measure. Is there something I can add to that?

```<code>AVG = SUM(Batter[H])/sum(Batter[AB])
</code>```

Thanks. I appreciate the help.

Here is some sample data

```<code>Name            AB  H
Gleyber Torres  546 152
Brett Gardner   491 123
Aaron Judge     378 103
Adam Ottavino   0   0
Aroldis Chapman 0   0
</code>```

答:
The NAN error is occurring because you are dividing by 0. You should add an IF condition to avoid that:

```<code>AVG = IF(sum(Batter[AB])=0,BLANK(),SUM(Batter[H])/sum(Batter[AB]))
</code>```

To tackle the formatting issue you can use the FORMAT function as mentioned by Andrey:

```<code>AVG = IF(sum(Batter[AB])=0,BLANK(),FORMAT(SUM(Batter[H])/sum(Batter[AB]),"###.0#"))
</code>```

Hope this helps.

ContentLicense: CC BY-SA 4.0

Title: Remove Zeros Before Decimal- PowerBI

Body:
Numbers under 1 are currently being represented with a leading zero before the decimal point (example: 0.50). Because I'm working with baseball statistics (which almost never have the zero before the decimal) I would like to remove that. I want to keep the number before the decimal if its greater than 1 though. How would I do that?

For instance if I'm working with this measure. Is there something I can add to that?

AVG = SUM(Batter[H])/sum(Batter[AB])

Thanks. I appreciate the help.

Here is some sample data

Name            AB  H
Gleyber Torres  546 152
Brett Gardner   491 123
Aaron Judge     378 103
Adam Ottavino   0   0
Aroldis Chapman 0   0

Body:
The NAN error is occurring because you are dividing by 0. You should add an IF condition to avoid that:

AVG = IF(sum(Batter[AB])=0,BLANK(),SUM(Batter[H])/sum(Batter[AB]))

To tackle the formatting issue you can use the FORMAT function as mentioned by Andrey:

AVG = IF(sum(Batter[AB])=0,BLANK(),FORMAT(SUM(Batter[H])/sum(Batter[AB]),"###.0#"))

Hope this helps.


问:
How might someone crack the SQL Server 2005 encryption stack?
This is one for all you security gurus out there.

I have a SQL Server 2005 database with a database master key, which is encrypted with a very strong password using the server key, which in turn is encrypted using the service account credentials in the Windows Data Protection layer.

I have a certificate which is encrypted using the database master key.

I have a symmetric key using AES256 which is encrypted using the certificate, and I am using the symmetric key to encrypt and decrypt confidential fields in the database.

What does someone need to crack the encrypted fields in the database? My only assumption is that brute force can't be employed due to the strength of the symmetric encryption algorithm, and the symmetric key itself is protected by 4 additional layers of encryption:

Windows DPAPI -> Server -> Database -> Certificate -> Symmetric Key

which seems pretty tight to me.

Let's not include the obvious answer of "get the system administrator's username and password by drugging and sleeping with him", which is definitely relevant but not what I'm after.

答:
K. Brian Kelley specializes in SQL Server security, and he's written several good articles about how encryption gets bypassed in SQL Server environments, like these:

http://www.sqlservercentral.com/blogs/brian_kelley/archive/2009/02/20/you-must-trust-someone.aspx

http://www.sqlservercentral.com/blogs/brian_kelley/archive/2009/02/27/a-security-control-inconsistently-applied-is-not-a-control.aspx

http://www.sqlservercentral.com/blogs/brian_kelley/archive/2009/02/20/you-must-trust-your-dbas.aspx

If you're really into security, I'd highly recommend subscribing to his blog.  He's also available on Twitter at http://twitter.com/kbriankelley.

OwnerDisplayName: Sam

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Brent Ozar


问:
Call CreateProcess() and get return value of a string
I have a C++ application that calls an EXE written in C# which grabs some information, and I want to pass it back as a string to the calling C++ application.

So my question is, "is it possible to get a return value of string data from an EXE called with CreateProcess()?

I hope I didn't violate any "question" etiquette here.

答:
I don't see how another process can return a string. Processes don't return anything, they just run.

You can reference (or link) some DLL or EXE and then call a method returning a string. But this will run within your own process and not start another one.

See: Calling C# .NET methods from unmanaged C/C++ code (CodeProject).


问:
Can't install or run html-pdf on nodejs
I have a application that generates PDF's using html-pdf on nodejs, but after I made a deploy to the production server, I'm not able to generate. It gives this error:

'html-pdf: Failed to load PhantomJS module. You have to set the path
  to the PhantomJS binary using 'options.phantomPath'

And if I run npm install html-pdf again, it gives this error

```<code>npm ERR! errno 1
npm ERR! node@11.8.0 preinstall: `node installArchSpecificPackage`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node@11.8.0 preinstall script.
</code>```

And this error replicates to other modules, but I made a turn around.

Runing node 13.7.0 and npm 6.9.0

答:
Can you try again with the -g flag

```<code>npm install -g html-pdf
</code>```

If still not working, execute after that:

```<code>npm link html-pdf
npm link phantomjs-prebuilt
</code>```

from https://github.com/marcbachmann/node-html-pdf/issues/437#issuecomment-467463285

Title: Can't install or run html-pdf on nodejs

Body:
I have a application that generates PDF's using html-pdf on nodejs, but after I made a deploy to the production server, I'm not able to generate. It gives this error:

'html-pdf: Failed to load PhantomJS module. You have to set the path
  to the PhantomJS binary using 'options.phantomPath'

And if I run npm install html-pdf again, it gives this error

npm ERR! errno 1
npm ERR! node@11.8.0 preinstall: `node installArchSpecificPackage`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node@11.8.0 preinstall script.

And this error replicates to other modules, but I made a turn around.

Runing node 13.7.0 and npm 6.9.0

Body:
Can you try again with the -g flag

npm install -g html-pdf

If still not working, execute after that:

npm link html-pdf
npm link phantomjs-prebuilt

from https://github.com/marcbachmann/node-html-pdf/issues/437#issuecomment-467463285


问:
Python requirements conflict with PyPi
I have a project that needs some DevOps TLC, so I am finally building my installation script. This will eventually be a package that will be install-able by pip locally, but may not end up in PyPI.

It has a dependency for a module called u2py. It is this package, created for U2 Database operations, not this package, for... something else. The one I want is only ever installed by a 3rd party vendor (Rocket), the one I don't want is in PyPI.

What should be the expected behavior of my package in this case? I will include a blurb about this in my readme doc, but is that sufficient?

I've thought about throwing an exception to identify when the wrong package is present, but that makes me feel weird. It seems that maybe the most pythonic thing is to NOT add this to my install script, and blindly assume import u2py results in a module I can use. If it quacks like a duck, parses DynArrays like a duck, and call()s SUBROUTINEs like a duck, then it's a duck, right? Otherwise, if there is an error the user will just go and actually read the docs.

I've looked a classifiers, but not sure if they apply here.

答:
Ideally there would be a way at install-time (in setup.py) to detect whether the package is being installed into a "u2 environment" or not, and could fail the installation (with an appropriate error message) if that's the case.

With this solution, you won't be able to provide built distributions (wheels) since they don't execute the setup.py file at install-time, but just publishing source distributions should be fine.

Title: Python requirements conflict with PyPi


问:
Memory managment. Dealloc. iOS
Is this correct?

```<code>- (void)dealloc {

    [super dealloc];

    [stageObjects release];
}
</code>```

Or should I call

```<code>[super dealloc]
</code>```

Always after all releases, I mean last line of this function?

答: You must always call [super dealloc]; last. After all, this very object might always be deallocated after the call to super returns.

ContentLicense: CC BY-SA 3.0

Title: Memory managment. Dealloc. iOS

Body:
Is this correct?

- (void)dealloc {

    [super dealloc];

    [stageObjects release];
}

Or should I call

[super dealloc]

Always after all releases, I mean last line of this function?


问:
class name and then the tag name contains the distinguish text
I have class name active and then there is unique text called active text in span(which is nested). Class name active is the unique among other class names then nested text is unique. How would i click on that. I have used following methods.

```<code>  FindElement(By.XPath("//li[@class='active']//*[contains(.,'active text')]"));
</code>```

also i tried

```<code>  findelement(BY.xpath(//li[@class='active']//div//div//div//span[contains(.,'active text')]"))
</code>```

also tried this

```<code>  FindElement(By.XPath("//li[contains(@class,'active')] and //span[contains(.,'active text')]")).Text;
</code>```

Every time i get no such element found
ANythoughts
this is the html code

```<code><li class="active">
 <div class="a">
  <div class="b">
   <div class="c">
    <h1></h1>
     <h3 class="d"> some text</h3>
      <div class="e">
       <span class="f">
         Active Text</span>
</div></div></div></div>
</li>
</code>```

答:
You can use either of the following Locator Strategies:

CssSelector:

```<code>FindElement(By.CssSelector("li.active span.f"));
</code>```

XPath 1:

```<code>FindElement(By.XPath("//li[@class='active']//span[normalize-space()='Active Text']"));
</code>```

XPath 2:

```<code>FindElement(By.XPath("//li[@class='active']//span[@class='f' and normalize-space()='Active Text']"));
</code>```

Body:
I have class name active and then there is unique text called active text in span(which is nested). Class name active is the unique among other class names then nested text is unique. How would i click on that. I have used following methods.

  FindElement(By.XPath("//li[@class='active']//*[contains(.,'active text')]"));

also i tried

  findelement(BY.xpath(//li[@class='active']//div//div//div//span[contains(.,'active text')]"))

also tried this

  FindElement(By.XPath("//li[contains(@class,'active')] and //span[contains(.,'active text')]")).Text;

Every time i get no such element found
ANythoughts
this is the html code

 some text

         Active Text

Body:
You can use either of the following Locator Strategies:

CssSelector:

FindElement(By.CssSelector("li.active span.f"));

XPath 1:

FindElement(By.XPath("//li[@class='active']//span[normalize-space()='Active Text']"));

XPath 2:

FindElement(By.XPath("//li[@class='active']//span[@class='f' and normalize-space()='Active Text']"));


问:
How i can print thread status?
Task:
Sequentially override the state of the child stream and print to the console (possibly through an intermediate state): BLOCKED WAITING TERMINATED method Thread.sleep () not to use.

My code:

```<code>public class Test {

private static final Object M = new Object();

  public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread() {
        public void run() {
                synchronized(M) {
                    try {
                        M.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
    };
    t.start();
    synchronized(M) {
        System.out.println(t.getState());
        M.notify();
        M.notifyAll();
}
    System.out.println(t.getState());

    System.out.println(t.getState());
    t.join();

    synchronized(M) {

        M.notify();
        M.notifyAll();
        System.out.println(t.getState());
    }
  }
}
</code>```

RESULT:

Question:
Pls help how to make it appear in the given sequence: BLOCKED WAITING TERMINATED

答:
This is solution:</p>

```<code>    public class Test {

    private static final Object M = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread() {
            public void run() {

                    try {
                        synchronized(M) {
                            M.notifyAll(); // notify before you stay on wait
                            M.wait();
                            M.notifyAll();
                            M.wait();
                            M.notifyAll();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        };
        synchronized(M) { // you need to lock M before start thread
            t.start();
            M.wait(); //wait and notifyAll need for make sure before thread t already get lock M and will blocked next time
            M.notifyAll();
            System.out.println(t.getState()); //BLOCKED
            M.wait();
            System.out.println(t.getState()); //WAITING
            M.notifyAll();

        }
        t.join();

        synchronized(M) {
            M.notifyAll();
            System.out.println(t.getState());
        }
    }
}
</code>```

Title: How i can print thread status?

Body:
Task:
Sequentially override the state of the child stream and print to the console (possibly through an intermediate state): BLOCKED WAITING TERMINATED method Thread.sleep () not to use.

My code:

public class Test {

private static final Object M = new Object();

  public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread() {
        public void run() {
                synchronized(M) {
                    try {
                        M.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
    };
    t.start();
    synchronized(M) {
        System.out.println(t.getState());
        M.notify();
        M.notifyAll();
}
    System.out.println(t.getState());

    System.out.println(t.getState());
    t.join();

    synchronized(M) {

        M.notify();
        M.notifyAll();
        System.out.println(t.getState());
    }
  }
}

RESULT:

Question:
Pls help how to make it appear in the given sequence: BLOCKED WAITING TERMINATED

Body:
This is solution:

    public class Test {

    private static final Object M = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread() {
            public void run() {

                    try {
                        synchronized(M) {
                            M.notifyAll(); // notify before you stay on wait
                            M.wait();
                            M.notifyAll();
                            M.wait();
                            M.notifyAll();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        };
        synchronized(M) { // you need to lock M before start thread
            t.start();
            M.wait(); //wait and notifyAll need for make sure before thread t already get lock M and will blocked next time
            M.notifyAll();
            System.out.println(t.getState()); //BLOCKED
            M.wait();
            System.out.println(t.getState()); //WAITING
            M.notifyAll();

        }
        t.join();

        synchronized(M) {
            M.notifyAll();
            System.out.println(t.getState());
        }
    }
}


问:
Create dynamic library using MSVC command line
I've read a lot of posts and yet I don't understand how to create a simple dynamic library on windows using MSVC in command line. What I'm doing is:

1º) Code the DLL

dynamic.h

#pragma once

__declspec(dllexport) void HelloWorld();
```

<p><strong>dynamic.c</strong></p>

<pre class="lang-c prettyprint-override"><code>#include "dynamic.h"
#include <stdio.h>

void HelloWorld(){
    printf("Hello World");
}
</code>```

2º) Compile it

```<code>cl /LD dynamic.c
</code>```

(it compiles correctly and without errors generating dynamic.dll and dynamic.lib)

3º) Try to test it

main.c

#include<stdio.h>
#include"dynamic.h"
int main(){

    HelloWorld();

    return 0;
}
```

```cl main.c dynamic.lib
```

<p><strong>ERROR</strong> (by cl.exe x64)</p>

```main.cpp
Microsoft (R) Incremental Linker Version 14.16.27034.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:main.exe
main.obj
.\dynamic.lib
main.obj : error LNK2019: unresolved external symbol "void __cdecl HelloWorld(void)" (?HelloWorld@@YAXXZ) referred in main
main.exe : fatal error LNK1120: unresolved externals
```

Please teach me how dynamic libraries compilation really work because I can't understand

答:
Try this way in dynamic.h :

```<code>#ifdef __cplusplus
extern "C" {
#endif
    __declspec(dllexport) void HelloWorld();
#ifdef __cplusplus
}
#endif
</code>```

Use 'dumpbin.exe /exports dynamic.dll' to show exported symbols

Body:
I've read a lot of posts and yet I don't understand how to create a simple dynamic library on windows using MSVC in command line. What I'm doing is:

1º) Code the DLL

dynamic.h

#pragma once

__declspec(dllexport) void HelloWorld();

dynamic.c

#include "dynamic.h"
#include <stdio.h>

void HelloWorld(){
    printf("Hello World");
}

2º) Compile it

cl /LD dynamic.c

(it compiles correctly and without errors generating dynamic.dll and dynamic.lib)

3º) Try to test it

main.c

#include<stdio.h>
#include"dynamic.h"
int main(){

    HelloWorld();

    return 0;
}

cl main.c dynamic.lib

ERROR (by cl.exe x64)

main.cpp
Microsoft (R) Incremental Linker Version 14.16.27034.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:main.exe
main.obj
.\dynamic.lib
main.obj : error LNK2019: unresolved external symbol "void __cdecl HelloWorld(void)" (?HelloWorld@@YAXXZ) referred in main
main.exe : fatal error LNK1120: unresolved externals

Please teach me how dynamic libraries compilation really work because I can't understand

Body:
Try this way in dynamic.h :

#ifdef __cplusplus
extern "C" {
#endif
    __declspec(dllexport) void HelloWorld();
#ifdef __cplusplus
}
#endif

Use 'dumpbin.exe /exports dynamic.dll' to show exported symbols


问:
React: how to maintain performance when updating a large parent record from a controlled child input field?
Imagine a React page that allows users to edit a bill (invoice). The bill has a fair number of editable fields, say 100. Additionally, a bill can have any number of line items. Let's imagine 100 of them, each with, say, 20 fields.

If the bill is the "parent," and is rendered by a React component, the line items are "children," each rendered by a "child" component.

I'm maintaining the state of the bill (and its line items) in the parent component, which feels right.

I want to use controlled input fields in the child (line item) component. However, this means, at least naively, that every keypress results in a state update in the parent (bill) component, and some re-renders, even if I use React.memo judiciously.

Performance has quickly gotten unacceptably slow, even with as few as 10 line items, like a 500-800ms lag on each keypress. I've done a fair bit of performance sleuthing, and have a couple of potential answers, but I'm not going to report them here, in order not to thwart any routes to the best answer.

There must be a common solution to this, no? I'd like to do it without one of the form libraries, though I'm not totally opposed to that.

The stripped-down example below, just to demonstrate the basic architecture. The example doesn't have a performance issue. :-)

Help! What's the magic that I'm missing to keep this performant?

```<code>
const INITIAL_STATE = {
  invoiceNumber: "ABC123",
  customer: "Phil's Dills",
  lineItems: [
    { index: 0, item: "Pickles", quantity: 2 },
    { index: 1, item: "Pickle Juice", quantity: 5 },
  ]
}

export function Bill() {
  const [ bill, setBill ] = useState(INITIAL_STATE);

  function updateBill(updatedLineItem) {
    const newLineItems = [...bill.lineItems];
    newLineItems[updatedLineItem.index] = updatedLineItem;
    setBill({
      ...bill,
      lineItems: newLineItems
    })
  }

  return(
    <div id="parent">
    <h1>Bill {bill.invoiceNumber} for {bill.customer}</h1>
    {bill.lineItems.map((lineItem) => (
      <LineItem key={lineItem.index} line={lineItem} updateBill={updateBill} />
    ))}
    </div>
    );
}

function LineItem({ line, updateBill }) {
  function updateField(e) {
    updateBill({
      ...line,
      [e.target.id]: e.target.value
    });
  }

  return(
    <div id="child">
      <input id="quantity" value={line.quantity} onChange={updateField} />
      <input id="item" value={line.item} onChange={updateField} />
    </div>
    );
}```
```

答: Thanks to everyone for your thoughts and suggestions. You helped clear my head, and I found the problem. bill, which gets updated on every keypress, was a dependency to a useEffect hook that, as it turns out, was very expensive and caused a lot of re-renders. I refactored that useEffect and my keypress performance is now very acceptable, even in development mode.

Body:
Imagine a React page that allows users to edit a bill (invoice). The bill has a fair number of editable fields, say 100. Additionally, a bill can have any number of line items. Let's imagine 100 of them, each with, say, 20 fields.

If the bill is the "parent," and is rendered by a React component, the line items are "children," each rendered by a "child" component.

I'm maintaining the state of the bill (and its line items) in the parent component, which feels right.

I want to use controlled input fields in the child (line item) component. However, this means, at least naively, that every keypress results in a state update in the parent (bill) component, and some re-renders, even if I use React.memo judiciously.

Performance has quickly gotten unacceptably slow, even with as few as 10 line items, like a 500-800ms lag on each keypress. I've done a fair bit of performance sleuthing, and have a couple of potential answers, but I'm not going to report them here, in order not to thwart any routes to the best answer.

There must be a common solution to this, no? I'd like to do it without one of the form libraries, though I'm not totally opposed to that.

The stripped-down example below, just to demonstrate the basic architecture. The example doesn't have a performance issue. :-)

Help! What's the magic that I'm missing to keep this performant?

const INITIAL_STATE = {
  invoiceNumber: "ABC123",
  customer: "Phil's Dills",
  lineItems: [
    { index: 0, item: "Pickles", quantity: 2 },
    { index: 1, item: "Pickle Juice", quantity: 5 },
  ]
}

export function Bill() {
  const [ bill, setBill ] = useState(INITIAL_STATE);

  function updateBill(updatedLineItem) {
    const newLineItems = [...bill.lineItems];
    newLineItems[updatedLineItem.index] = updatedLineItem;
    setBill({
      ...bill,
      lineItems: newLineItems
    })
  }

  return(

Bill {bill.invoiceNumber} for {bill.customer}

    {bill.lineItems.map((lineItem) => (
      <LineItem key={lineItem.index} line={lineItem} updateBill={updateBill} />
    ))}

    );
}

function LineItem({ line, updateBill }) {
  function updateField(e) {
    updateBill({
      ...line,
      [e.target.id]: e.target.value
    });
  }

  return(

      <input id="quantity" value={line.quantity} onChange={updateField} />
      <input id="item" value={line.item} onChange={updateField} />

    );
}```


问:
Gulp project deploy to Tomcat server
I am trying to deploy Gulp project to Tomcat server when I release it and deploy to server the project can not load the resource
Here is will find that the server Failed to find the files such as the css and js:

答:
You must configure the tomcat by specifying the path to ready resources after gulp building
Tomcat docs

```<code>  <servlet-mapping>
       <servlet-name>default</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>
</code>```

Or you can reconfigurate you gulp for current tomcat mapping

Title: Gulp project deploy to Tomcat server

Body:
You must configure the tomcat by specifying the path to ready resources after gulp building
Tomcat docs

  <servlet-mapping>
       <servlet-name>default</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>

Or you can reconfigurate you gulp for current tomcat mapping


问:
Is Python 3 continue loop statement a problem in compute methods in Odoo 13?
I am migrating a module to version 13.0, which uses continue in a loop inside a compute method, and an error was driving me crazy for a while.

I simplified the code to the minimum until I had this kind of nosense:

```<code>@api.depends('move_lines', 'move_lines.price_subtotal')
def _compute_subtotal(self):
    for picking in self:
        if picking.picking_type_id.code not in ['incoming', 'outgoing']:
            continue
        picking.update({
            'amount_untaxed': 3.0,
        })
</code>```

But I was still receiving the error, which by the way was this (and only was shown when creating new pickings):

```<code>stock.picking(<NewId 0x7f5404ba5eb8>,).amount_untaxed
</code>```

So I realised that the problem was the continue statement, if I removed it, it worked. And I tried to use continue in several loops of other compute methods of standard Odoo modules, with same result.

Until now, if you did not assign a value for a field in a computed method, it automatically took False, so continue was not a problem.

Does anyone experience this problem with continue too?

答:
The problem is not the continue statement itself but is that Odoo expect you to set the the value for your computed field because if you check the code of __get__ of Field class:

```<code>def __get__(self):
     ....
     .....
        elif self.compute:
            ........
            ........
            else:
                recs = record if self.recursive or not record.id else record._in_cache_without(self)
                try:
                    # Here it's computing the value for this record
                    self.compute_value(recs)
                except AccessError:
                    self.compute_value(record)
                # after computation they try the get the value from the environment cache
                value = env.cache.get(record, self)
</code>```

And because you didn't set the value for this record, this will raise this error odoo.exceptions.CacheMiss: ('stock.picking(ID_OF_RECORD,).amount_untaxed', None).
You need to set a value for each compute field that is computed in that method.

Body:
I am migrating a module to version 13.0, which uses continue in a loop inside a compute method, and an error was driving me crazy for a while.

I simplified the code to the minimum until I had this kind of nosense:

@api.depends('move_lines', 'move_lines.price_subtotal')
def _compute_subtotal(self):
    for picking in self:
        if picking.picking_type_id.code not in ['incoming', 'outgoing']:
            continue
        picking.update({
            'amount_untaxed': 3.0,
        })

But I was still receiving the error, which by the way was this (and only was shown when creating new pickings):

stock.picking(<NewId 0x7f5404ba5eb8>,).amount_untaxed

So I realised that the problem was the continue statement, if I removed it, it worked. And I tried to use continue in several loops of other compute methods of standard Odoo modules, with same result.

Until now, if you did not assign a value for a field in a computed method, it automatically took False, so continue was not a problem.

Does anyone experience this problem with continue too?

Body:
The problem is not the continue statement itself but is that Odoo expect you to set the the value for your computed field because if you check the code of __get__ of Field class:

def __get__(self):
     ....
     .....
        elif self.compute:
            ........
            ........
            else:
                recs = record if self.recursive or not record.id else record._in_cache_without(self)
                try:
                    # Here it's computing the value for this record
                    self.compute_value(recs)
                except AccessError:
                    self.compute_value(record)
                # after computation they try the get the value from the environment cache
                value = env.cache.get(record, self)

And because you didn't set the value for this record, this will raise this error odoo.exceptions.CacheMiss: ('stock.picking(ID_OF_RECORD,).amount_untaxed', None).
You need to set a value for each compute field that is computed in that method.


问:
Golang: how to send html body email with image using base64 string as attachment content
I have the following msg which i receive in my golang handler:

```<code>{"fromDisplayName":"ForgottenPassword","to":["example@gmail.com"],"cc":[],"bcc":[],"subject":"ForgottenPassword","body":" \t<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html> \t<head> \t\t<meta http-equiv=\"Content-Type\" content=\"text/html charset=UTF-8\" /> \t\t<title>Forgot Password Email</title> \t</head> \t<body style=\"width:100%; border:0; padding:0; margin:0; text-align:center; background-color:#f3f3f3; font-family:Gotham, 'Helvetica Neue', Helvetica, Arial, 'sans-serif'; font-size:1em\">\t\t \t\t<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"width: 100%; max-width: 680px; margin: auto; margin-top: 30px; box-shadow: 0 1px 2px rgba(0,0,0,0.3);\"> \t\t\t<tr> \t\t\t\t<td>\t\t\t\t\t \t\t\t\t\t<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"width: 100%;\"> \t\t\t\t\t\t<tr> \t\t\t\t\t\t\t<td style=\"background-color:#ffffff; height:4em; padding:1.5em;\"> \t\t\t\t\t\t\t\t<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"width: 100%;\"> \t\t\t\t\t\t\t\t\t<tr> \t\t\t\t\t\t\t\t\t\t<td style=\"padding-bottom: 20px; text-align: left;\"></td> \t\t\t\t\t\t\t\t\t</tr> \t\t\t\t\t\t\t\t\t<tr> \t\t\t\t\t\t\t\t\t\t<td style=\"width: 100%; height: 1px; background-color: #ccc;\"></td> \t\t\t\t\t\t\t\t\t</tr> \t\t\t\t\t\t\t\t</table> \t\t\t\t\t\t\t</td> \t\t\t\t\t\t</tr> \t\t\t\t\t</table> \t\t\t\t\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"width: 100%;\"> \t\t\t\t\t\t<tbody> \t\t\t\t\t\t\t<tr> \t\t\t\t\t\t\t\t<td style=\"width:100%; padding:30px; text-align: center; background-color:#ffffff\"> \t\t\t\t\t\t\t\t\t<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\"> \t\t\t\t\t\t\t\t\t\t<tr> \t\t\t\t\t\t\t\t\t\t\t<td style=\"padding: 40px 40px 0px 40px; text-align: center; font-size:2.5em; font-weight:lighter; mso-height-rule: exactly; line-height: 28px; color: #434795;\">Hi user</td> \t\t\t\t\t\t\t\t\t\t</tr> \t\t\t\t\t\t\t\t\t\t<tr> \t\t\t\t\t\t\t\t\t\t\t<td style=\"text-align: center; font-size:1em; padding-top:0.8em; padding-bottom:2em; color:#999999\">You're already a user, so there is no need to sign up.</td> \t\t\t\t\t\t\t\t\t\t</tr> \t\t\t\t\t\t\t\t\t\t<tr> \t\t\t\t\t\t\t\t\t\t\t<td style=\"text-align: center; font-size:1em; padding-top:0.8em; padding-bottom:2em; color:#999999\">If you forgot your password, you can reset it .</td> \t\t\t\t\t\t\t\t\t\t</tr> \t\t\t\t\t\t\t\t\t\t<tr> \t\t\t\t\t\t\t\t\t\t\t<td style=\"text-align: center;\"> \t\t\t\t\t\t\t\t\t\t\t\t<a><img src=\"cid:278da187427a4bdcaceb76781f4a3753\" alt=\"forgot password\" width=\"100\" height=\"60\" border=\"0\"></a> \t\t\t\t\t\t\t\t\t\t\t</td> \t\t\t\t\t\t\t\t\t\t</tr> \t\t\t\t\t\t\t\t\t</table> \t\t\t\t\t\t\t\t\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"> \t\t\t\t\t\t\t\t\t\t<tr> \t\t\t\t\t\t\t\t\t\t\t<td> \t\t\t\t\t\t\t\t\t\t\t\t<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\"> \t\t\t\t\t\t\t\t\t\t\t\t\t<tr> \t\t\t\t\t\t\t\t\t\t\t\t\t\t<td style = \"font-size:0.75em; padding-top:3.5em; padding-bottom:1.25em; text-align: center; color:#999999\">If you received this email by mistake, you can just delete it.</td> \t\t\t\t\t\t\t\t\t\t\t\t\t</tr> \t\t\t\t\t\t\t\t\t\t\t\t</table> \t\t\t\t\t\t\t\t\t\t\t</td> \t\t\t\t\t\t\t\t\t\t</tr> \t\t\t\t\t\t\t\t\t</table> \t\t\t\t\t\t\t\t\t<table cellspacing=\"0\" cellpadding=\"0\" text-align=\"center\" align=\"center\" bgcolor=\"#f3f3f3\" width=\"100%\" style=\"max-width: 680px\"> \t\t\t\t\t\t\t\t\t\t <tr> \t\t\t\t\t\t\t\t\t\t\t<td style=\" font-size: 0.75em; text-align: center; mso-height-rule: exactly; line-height:17px; padding-top: 20px;\"> \t\t\t\t\t\t\t\t\t\t\t\t<span style=\"color: #999999;\">We don't check this mailbox, so please don't reply to this message.</span><br> \t\t\t\t\t\t\t\t\t\t\t\t<span class=\"mobile-link--footer;\" style=\"color: #999999;\"></span><br><br> \t\t\t\t\t\t\t\t\t\t\t</td> \t\t\t\t\t\t\t\t\t\t</tr> \t\t\t\t\t\t\t\t\t</table> \t\t\t\t\t\t\t\t</td> \t\t\t\t\t\t\t</tr> \t\t\t\t\t\t</tbody> \t\t\t\t\t</table>\t\t\t\t\t \t\t\t\t</td>\t \t\t\t</tr> \t\t</table>\t\t \t</body> </html>","isHtmlBody":true,"attachments":[{"fileName":"click_button.png","content":"[encoded data, 5172 characters]","contentType":"image/png","contentDisposition":"inline","cid":"278da187427a4bdcaceb76781f4a3753"}]}
</code>```

My purpose is to send the information in the msg as an email via google smtp.

im able so send the message but the image content in the message(base64 string) is not embeded in the email html body. when i send the same message using nodejs and nodemailer - the image is shown correctly.

how can i achive this?

this is an example of one of the approaches i tried and does not show the  image in the email body ("github.com/jordan-wright/email"):

```<code>func EmailServiceBusinessLogic(receivedMsg emailModels.ReceivedMsgModel) error{

    mail := email.NewEmail()

    for _,v := range receivedMsg.Attachments{
        if v.FileName == "" {
            fmt.Println("received empty file name for attachment")
            continue
        }
        if v.Cid == "" {
            fmt.Println("received empty cid for file name: ", v.FileName)
            continue
        }
        if v.ContentType == "" {
            fmt.Println("received empty ContentType for file name: ", v.FileName)
            continue
        }
        if v.Content == "" {
            fmt.Println("received empty Content for file name: ", v.FileName)
            continue
        }

        mail.Attach(strings.NewReader(v.Content)  , v.Cid, v.ContentType)
    }

    if receivedMsg.FromDisplayName == "" {
        fmt.Println("received empty FromDisplayName: aborting send")
        return errors.New("received empty FromDisplayName: aborting send")

    }
    fromWithoutWhiteSpaces := strings.Join(strings.Fields(receivedMsg.FromDisplayName), "")

    mail.From = fromWithoutWhiteSpaces+"@dont-reply.com"
    mail.To = receivedMsg.To
    mail.Bcc = receivedMsg.Bcc
    mail.Cc = receivedMsg.Cc
    mail.Subject = receivedMsg.Subject
    if receivedMsg.IsHtmlBody {
        mail.HTML = []byte(receivedMsg.Body)
    }else {
        mail.Text = []byte(receivedMsg.Body)
    }

    err := mail.Send(emailGlobals.SmtpConf.Body[0].Value.Host+":587", smtp.PlainAuth("", emailGlobals.SmtpConf.Body[0].Value.Username, emailGlobals.SmtpConf.Body[0].Value.Password, emailGlobals.SmtpConf.Body[0].Value.Host))
    if err != nil {
        return err
    }
}

</code>```

EDIT:

SOLVED

thanks to  @Steffen Ullrich comments Because in my json the image content already base64 encoded and the library will put another base64 layer on top of it, so I had to base64 decode it first like so:

```<code>func EmailServiceBusinessLogic(receivedMsg emailModels.ReceivedMsgModel) error {

    mail := email.NewEmail()

    for _, v := range receivedMsg.Attachments {
        if v.FileName == "" {
            fmt.Println("received empty file name for attachment")
            continue
        }
        if v.Cid == "" {
            fmt.Println("received empty cid for file name: ", v.FileName)
            continue
        }
        if v.ContentType == "" {
            fmt.Println("received empty ContentType for file name: ", v.FileName)
            continue
        }
        if v.Content == "" {
            fmt.Println("received empty Content for file name: ", v.FileName)
            continue
        }

        // Base64 Standard Decoding <-this is the part that was missing!!
        sDec, err := base64.StdEncoding.DecodeString(v.Content)
        if err != nil {
            fmt.Printf("Error decoding Content: %s ", err.Error())
            continue
        }

        mail.Attach(strings.NewReader(string(sDec)), v.Cid, v.ContentType)
    }

    if receivedMsg.FromDisplayName == "" {
        fmt.Println("received empty FromDisplayName: aborting send")
        return errors.New("received empty FromDisplayName: aborting send")

    }
    fromWithoutWhiteSpaces := strings.Join(strings.Fields(receivedMsg.FromDisplayName), "")

    mail.From = fromWithoutWhiteSpaces + "@dont-reply.com"
    mail.To = receivedMsg.To
    mail.Bcc = receivedMsg.Bcc
    mail.Cc = receivedMsg.Cc
    mail.Subject = receivedMsg.Subject
    if receivedMsg.IsHtmlBody {
        mail.HTML = []byte(receivedMsg.Body)
    } else {
        mail.Text = []byte(receivedMsg.Body)
    }

    err := mail.Send(emailGlobals.SmtpConf.Body[0].Value.Host+":587", smtp.PlainAuth("", emailGlobals.SmtpConf.Body[0].Value.Username, emailGlobals.SmtpConf.Body[0].Value.Password, emailGlobals.SmtpConf.Body[0].Value.Host))
    if err != nil {
        return err
    }
}
</code>```

答:
To reference an attached image from inside the HTML it must have a Content-Id, i.e. in the HTML it needs to look like this:

```<code>`<img src="cid:000001.png">
</code>```

Looking at the source of Attach in "github.com/jordan-wright/email which I assume you use it shows that it is using the given filename as Content-Id:

```<code>func (e *Email) Attach(r io.Reader, filename string, c string) (a *Attachment, err error) {
    ....
    at.Header.Set("Content-ID", fmt.Sprintf("<%s>", filename))
</code>```

Thus, make sure that the v.FileName you use as name for your attachment is actually used as the cid in the HTML part.

After more information were added to the question:

... the only information i have regarding the attachments is: file name, content(string), content type(image/png) and contentDisposition atribute set to inline and cid

In this case you the cid and not file name.

With even more information added to the question:

have the following msg which i receive in my golang handler:

```<code>{"fromDisplayName":"Forg...
</code>```

It looks like that your image is already base64 encoded, but the library you use does an additional base64 encoding, so you have to decode it first. Also the library explicitly uses a Content-Type of multipart/mixed but it needs to be multipart/related so that the images are associated with the HTML.

The following code works for me with the JSON from your question stored as mail.json. Note that I omitted error checking in several places in order to focus on the solution. And I don't directly send the mail but store it only as a string to store it as an EML file and check it. You likely need to change the Bytes function to set multipart/related directly there:

```<code>package main

import (
    "github.com/jordan-wright/email"
    "encoding/json"
    "encoding/base64"
    "fmt"
    "os"
    "bytes"
    "strings"
)

type Attachments struct {
    Filename string `json:"filename"`
    Content string `json:"content"`
    ContentType string `json:"contentType"`
    ContentDisposition string `json:"contentDisposition"`
    Cid string `json:"cid"`
}

type Mail struct {
    To []string `json:"to"`
    Subject string `json:"subject"`
    Body string `json:"body"`
    Parts []Attachments `json:"attachments"`
}

func main() {
    f,_ := os.Open("mail.json")
    d := json.NewDecoder(f)
    m := &Mail{}
    d.Decode(&m)
    // fmt.Println(m)

    e := email.NewEmail()
    e.To = m.To
    e.Subject = m.Subject
    e.HTML = []byte(m.Body)
    for _,p := range m.Parts {
        s,_ := base64.StdEncoding.DecodeString(string(p.Content))
        e.Attach(bytes.NewReader(s), p.Cid, p.ContentType)
    }
    s,_ := e.Bytes()
    mail := strings.Replace(string(s),": multipart/mixed;",": multipart/related;",1)
    fmt.Println(mail)
}

</code>```

Body:
I have the following msg which i receive in my golang handler:

{"fromDisplayName":"ForgottenPassword","to":["example@gmail.com"],"cc":[],"bcc":[],"subject":"ForgottenPassword","body":" \t<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">  \t \t\t<meta http-equiv=\"Content-Type\" content=\"text/html charset=UTF-8\" /> \t\t<title>Forgot Password Email</title> \t \t\t\t \t\t
 \t\t\t
 \t\t\t\t\t\t\t\t\t \t\t\t\t\t
 \t\t\t\t\t\t
 \t\t\t\t\t\t\t \t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t	 \t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t	 \t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t	 \t\t\t\t\t\t
 \t\t\t\t\t
 \t\t\t\t\t
 \t\t\t\t\t\t
 \t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t\tHi user	 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t\tYou're already a user, so there is no need to sign up.	 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t\tIf you forgot your password, you can reset it .	 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\t	 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t\t\t\t\tIf you received this email by mistake, you can just delete it.	 \t\t\t\t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t\t	 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\t\tWe don't check this mailbox, so please don't reply to this message.
 \t\t\t\t\t\t\t\t\t\t\t\t

 \t\t\t\t\t\t\t\t\t\t\t	 \t\t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t\t
 \t\t\t\t\t\t\t\t	 \t\t\t\t\t\t\t
 \t\t\t\t\t\t
 \t\t\t\t\t
\t\t\t\t\t \t\t\t\t	\t \t\t\t
 \t\t
\t\t \t ","isHtmlBody":true,"attachments":[{"fileName":"click_button.png","content":"[encoded data, 5172 characters]","contentType":"image/png","contentDisposition":"inline","cid":"278da187427a4bdcaceb76781f4a3753"}]}

My purpose is to send the information in the msg as an email via google smtp.

im able so send the message but the image content in the message(base64 string) is not embeded in the email html body. when i send the same message using nodejs and nodemailer - the image is shown correctly.

how can i achive this?

this is an example of one of the approaches i tried and does not show the  image in the email body ("github.com/jordan-wright/email"):

func EmailServiceBusinessLogic(receivedMsg emailModels.ReceivedMsgModel) error{

    mail := email.NewEmail()

    for _,v := range receivedMsg.Attachments{
        if v.FileName == "" {
            fmt.Println("received empty file name for attachment")
            continue
        }
        if v.Cid == "" {
            fmt.Println("received empty cid for file name: ", v.FileName)
            continue
        }
        if v.ContentType == "" {
            fmt.Println("received empty ContentType for file name: ", v.FileName)
            continue
        }
        if v.Content == "" {
            fmt.Println("received empty Content for file name: ", v.FileName)
            continue
        }

        mail.Attach(strings.NewReader(v.Content)  , v.Cid, v.ContentType)
    }

    if receivedMsg.FromDisplayName == "" {
        fmt.Println("received empty FromDisplayName: aborting send")
        return errors.New("received empty FromDisplayName: aborting send")

    }
    fromWithoutWhiteSpaces := strings.Join(strings.Fields(receivedMsg.FromDisplayName), "")

    mail.From = fromWithoutWhiteSpaces+"@dont-reply.com"
    mail.To = receivedMsg.To
    mail.Bcc = receivedMsg.Bcc
    mail.Cc = receivedMsg.Cc
    mail.Subject = receivedMsg.Subject
    if receivedMsg.IsHtmlBody {
        mail.HTML = []byte(receivedMsg.Body)
    }else {
        mail.Text = []byte(receivedMsg.Body)
    }

    err := mail.Send(emailGlobals.SmtpConf.Body[0].Value.Host+":587", smtp.PlainAuth("", emailGlobals.SmtpConf.Body[0].Value.Username, emailGlobals.SmtpConf.Body[0].Value.Password, emailGlobals.SmtpConf.Body[0].Value.Host))
    if err != nil {
        return err
    }
}

EDIT:

SOLVED

thanks to  @Steffen Ullrich comments Because in my json the image content already base64 encoded and the library will put another base64 layer on top of it, so I had to base64 decode it first like so:

func EmailServiceBusinessLogic(receivedMsg emailModels.ReceivedMsgModel) error {

    mail := email.NewEmail()

    for _, v := range receivedMsg.Attachments {
        if v.FileName == "" {
            fmt.Println("received empty file name for attachment")
            continue
        }
        if v.Cid == "" {
            fmt.Println("received empty cid for file name: ", v.FileName)
            continue
        }
        if v.ContentType == "" {
            fmt.Println("received empty ContentType for file name: ", v.FileName)
            continue
        }
        if v.Content == "" {
            fmt.Println("received empty Content for file name: ", v.FileName)
            continue
        }

        // Base64 Standard Decoding <-this is the part that was missing!!
        sDec, err := base64.StdEncoding.DecodeString(v.Content)
        if err != nil {
            fmt.Printf("Error decoding Content: %s ", err.Error())
            continue
        }

        mail.Attach(strings.NewReader(string(sDec)), v.Cid, v.ContentType)
    }

    if receivedMsg.FromDisplayName == "" {
        fmt.Println("received empty FromDisplayName: aborting send")
        return errors.New("received empty FromDisplayName: aborting send")

    }
    fromWithoutWhiteSpaces := strings.Join(strings.Fields(receivedMsg.FromDisplayName), "")

    mail.From = fromWithoutWhiteSpaces + "@dont-reply.com"
    mail.To = receivedMsg.To
    mail.Bcc = receivedMsg.Bcc
    mail.Cc = receivedMsg.Cc
    mail.Subject = receivedMsg.Subject
    if receivedMsg.IsHtmlBody {
        mail.HTML = []byte(receivedMsg.Body)
    } else {
        mail.Text = []byte(receivedMsg.Body)
    }

    err := mail.Send(emailGlobals.SmtpConf.Body[0].Value.Host+":587", smtp.PlainAuth("", emailGlobals.SmtpConf.Body[0].Value.Username, emailGlobals.SmtpConf.Body[0].Value.Password, emailGlobals.SmtpConf.Body[0].Value.Host))
    if err != nil {
        return err
    }
}

Body:
To reference an attached image from inside the HTML it must have a Content-Id, i.e. in the HTML it needs to look like this:

`<img src="cid:000001.png">

Looking at the source of Attach in "github.com/jordan-wright/email which I assume you use it shows that it is using the given filename as Content-Id:

func (e *Email) Attach(r io.Reader, filename string, c string) (a *Attachment, err error) {
    ....
    at.Header.Set("Content-ID", fmt.Sprintf("<%s>", filename))

Thus, make sure that the v.FileName you use as name for your attachment is actually used as the cid in the HTML part.

After more information were added to the question:

... the only information i have regarding the attachments is: file name, content(string), content type(image/png) and contentDisposition atribute set to inline and cid

In this case you the cid and not file name.

With even more information added to the question:

have the following msg which i receive in my golang handler:

{"fromDisplayName":"Forg...

It looks like that your image is already base64 encoded, but the library you use does an additional base64 encoding, so you have to decode it first. Also the library explicitly uses a Content-Type of multipart/mixed but it needs to be multipart/related so that the images are associated with the HTML.

The following code works for me with the JSON from your question stored as mail.json. Note that I omitted error checking in several places in order to focus on the solution. And I don't directly send the mail but store it only as a string to store it as an EML file and check it. You likely need to change the Bytes function to set multipart/related directly there:

package main

import (
    "github.com/jordan-wright/email"
    "encoding/json"
    "encoding/base64"
    "fmt"
    "os"
    "bytes"
    "strings"
)

type Attachments struct {
    Filename string `json:"filename"`
    Content string `json:"content"`
    ContentType string `json:"contentType"`
    ContentDisposition string `json:"contentDisposition"`
    Cid string `json:"cid"`
}

type Mail struct {
    To []string `json:"to"`
    Subject string `json:"subject"`
    Body string `json:"body"`
    Parts []Attachments `json:"attachments"`
}

func main() {
    f,_ := os.Open("mail.json")
    d := json.NewDecoder(f)
    m := &Mail{}
    d.Decode(&m)
    // fmt.Println(m)

    e := email.NewEmail()
    e.To = m.To
    e.Subject = m.Subject
    e.HTML = []byte(m.Body)
    for _,p := range m.Parts {
        s,_ := base64.StdEncoding.DecodeString(string(p.Content))
        e.Attach(bytes.NewReader(s), p.Cid, p.ContentType)
    }
    s,_ := e.Bytes()
    mail := strings.Replace(string(s),": multipart/mixed;",": multipart/related;",1)
    fmt.Println(mail)
}


问:
Submit a Spark application via AWS [EMR]
Hello I'm very new to cloud computing so I apologize for (maybe) the stupid question. I need help to know if what i do is actually computing on the cluster or just on the master (useless thing).

WHAT I CAN DO:
Well I can set up a cluster of a certain number of nodes with Spark installed on all of them using the AWS console. I can connect to the master node via SSH. What is it required then it to run my jar with Spark code on the cluster.

WHAT I'D DO:
I'd call spark-submit to run my code:

```<code>spark-submit --class cc.Main /home/ubuntu/MySparkCode.jar 3 [arguments]
</code>```

MY DOUBTS:

Is it needed to specify the master with --master and the
"spark://" reference of the master? Where could I find that
reference? Should I run the script in sbin/start-master.sh to start
a Standalone cluster manager or is it already set? If I run the code
above I imagine that code would run only locally on the master,
right?

Can I keep my input files only on the master node? Suppose i want
    to count the words of a huge text file, can I keep it only on the
    disk of the master? Or to maintain the parallelism I need a
    distributed memory like HDFS? I don't understand this, I'd keep it
    on the master node disk if it fits.

So thanks for the reply.

UPDATE1:
I tried to run the Pi example on the cluster and I can't get the result.

```<code>$ sudo spark-submit   --class org.apache.spark.examples.SparkPi   --master yarn   --deploy-mode cluster   /usr/lib/spark/examples/jars/spark-examples.jar   10
</code>```

I would expect to get a line with printed Pi is roughly 3.14... instead I get:

```<code>17/04/15 13:16:01 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/04/15 13:16:03 INFO RMProxy: Connecting to ResourceManager at ip-172-31-37-222.us-west-2.compute.internal/172.31.37.222:8032
17/04/15 13:16:03 INFO Client: Requesting a new application from cluster with 2 NodeManagers
17/04/15 13:16:03 INFO Client: Verifying our application has not requested more than the maximum memory capability of the cluster (5120 MB per container)
17/04/15 13:16:03 INFO Client: Will allocate AM container, with 5120 MB memory including 465 MB overhead
17/04/15 13:16:03 INFO Client: Setting up container launch context for our AM
17/04/15 13:16:03 INFO Client: Setting up the launch environment for our AM container
17/04/15 13:16:03 INFO Client: Preparing resources for our AM container
17/04/15 13:16:06 WARN Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.
17/04/15 13:16:10 INFO Client: Uploading resource file:/mnt/tmp/spark-aa757ca0-4ff7-460c-8bee-27bc8c8dada9/__spark_libs__5838015067814081789.zip -> hdfs://ip-172-31-37-222.us-west-2.compute.internal:8020/user/root/.sparkStaging/application_1492261407069_0007/__spark_libs__5838015067814081789.zip
17/04/15 13:16:12 INFO Client: Uploading resource file:/usr/lib/spark/examples/jars/spark-examples.jar -> hdfs://ip-172-31-37-222.us-west-2.compute.internal:8020/user/root/.sparkStaging/application_1492261407069_0007/spark-examples.jar
17/04/15 13:16:12 INFO Client: Uploading resource file:/mnt/tmp/spark-aa757ca0-4ff7-460c-8bee-27bc8c8dada9/__spark_conf__1370316719712336297.zip -> hdfs://ip-172-31-37-222.us-west-2.compute.internal:8020/user/root/.sparkStaging/application_1492261407069_0007/__spark_conf__.zip
17/04/15 13:16:13 INFO SecurityManager: Changing view acls to: root
17/04/15 13:16:13 INFO SecurityManager: Changing modify acls to: root
17/04/15 13:16:13 INFO SecurityManager: Changing view acls groups to:
17/04/15 13:16:13 INFO SecurityManager: Changing modify acls groups to:
17/04/15 13:16:13 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(root); groups with view permissions: Set(); users  with modify permissions: Set(root); groups with modify permissions: Set()

17/04/15 13:16:13 INFO Client: Submitting application application_1492261407069_0007 to ResourceManager
17/04/15 13:16:13 INFO YarnClientImpl: Submitted application application_1492261407069_0007
17/04/15 13:16:14 INFO Client: Application report for application_1492261407069_0007 (state: ACCEPTED)
17/04/15 13:16:14 INFO Client:
     client token: N/A
     diagnostics: N/A
     ApplicationMaster host: N/A
     ApplicationMaster RPC port: -1
     queue: default
     start time: 1492262173096
     final status: UNDEFINED
     tracking URL: http://ip-172-31-37-222.us-west-2.compute.internal:20888/proxy/application_1492261407069_0007/
     user: root
17/04/15 13:16:15 INFO Client: Application report for application_1492261407069_0007 (state: ACCEPTED)
17/04/15 13:16:24 INFO Client: Application report for application_1492261407069_0007 (state: ACCEPTED)
17/04/15 13:16:25 INFO Client: Application report for application_1492261407069_0007 (state: RUNNING)
17/04/15 13:16:25 INFO Client:
     client token: N/A
     diagnostics: N/A
     ApplicationMaster host: 172.31.33.215
     ApplicationMaster RPC port: 0
     queue: default
     start time: 1492262173096
     final status: UNDEFINED
     tracking URL: http://ip-172-31-37-222.us-west-2.compute.internal:20888/proxy/application_1492261407069_0007/
     user: root
17/04/15 13:16:26 INFO Client: Application report for application_1492261407069_0007 (state: RUNNING)
17/04/15 13:16:55 INFO Client: Application report for application_1492261407069_0007 (state: RUNNING)
17/04/15 13:16:56 INFO Client: Application report for application_1492261407069_0007 (state: FINISHED)
17/04/15 13:16:56 INFO Client:
     client token: N/A
     diagnostics: N/A
     ApplicationMaster host: 172.31.33.215
     ApplicationMaster RPC port: 0
     queue: default
     start time: 1492262173096
     final status: SUCCEEDED
     tracking URL: http://ip-172-31-37-222.us-west-2.compute.internal:20888/proxy/application_1492261407069_0007/
     user: root
17/04/15 13:16:56 INFO ShutdownHookManager: Shutdown hook called
17/04/15 13:16:56 INFO ShutdownHookManager: Deleting directory /mnt/tmp/spark-aa757ca0-4ff7-460c-8bee-27bc8c8dada9
</code>```

答:
You can use this:</p>

```<code>spark-submit --deploy-mode client --executor-memory 4g --class org.apache.spark.examples.SparkPi /usr/lib/spark/examples/jars/spark-examples.jar
</code>```

Body:
Hello I'm very new to cloud computing so I apologize for (maybe) the stupid question. I need help to know if what i do is actually computing on the cluster or just on the master (useless thing).

WHAT I CAN DO:
Well I can set up a cluster of a certain number of nodes with Spark installed on all of them using the AWS console. I can connect to the master node via SSH. What is it required then it to run my jar with Spark code on the cluster.

WHAT I'D DO:
I'd call spark-submit to run my code:

spark-submit --class cc.Main /home/ubuntu/MySparkCode.jar 3 [arguments]

MY DOUBTS:

Is it needed to specify the master with --master and the
"spark://" reference of the master? Where could I find that
reference? Should I run the script in sbin/start-master.sh to start
a Standalone cluster manager or is it already set? If I run the code
above I imagine that code would run only locally on the master,
right?

Can I keep my input files only on the master node? Suppose i want
    to count the words of a huge text file, can I keep it only on the
    disk of the master? Or to maintain the parallelism I need a
    distributed memory like HDFS? I don't understand this, I'd keep it
    on the master node disk if it fits.

So thanks for the reply.

UPDATE1:
I tried to run the Pi example on the cluster and I can't get the result.

$ sudo spark-submit   --class org.apache.spark.examples.SparkPi   --master yarn   --deploy-mode cluster   /usr/lib/spark/examples/jars/spark-examples.jar   10

I would expect to get a line with printed Pi is roughly 3.14... instead I get:

17/04/15 13:16:01 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/04/15 13:16:03 INFO RMProxy: Connecting to ResourceManager at ip-172-31-37-222.us-west-2.compute.internal/172.31.37.222:8032
17/04/15 13:16:03 INFO Client: Requesting a new application from cluster with 2 NodeManagers
17/04/15 13:16:03 INFO Client: Verifying our application has not requested more than the maximum memory capability of the cluster (5120 MB per container)
17/04/15 13:16:03 INFO Client: Will allocate AM container, with 5120 MB memory including 465 MB overhead
17/04/15 13:16:03 INFO Client: Setting up container launch context for our AM
17/04/15 13:16:03 INFO Client: Setting up the launch environment for our AM container
17/04/15 13:16:03 INFO Client: Preparing resources for our AM container
17/04/15 13:16:06 WARN Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.
17/04/15 13:16:10 INFO Client: Uploading resource file:/mnt/tmp/spark-aa757ca0-4ff7-460c-8bee-27bc8c8dada9/__spark_libs__5838015067814081789.zip -> hdfs://ip-172-31-37-222.us-west-2.compute.internal:8020/user/root/.sparkStaging/application_1492261407069_0007/__spark_libs__5838015067814081789.zip
17/04/15 13:16:12 INFO Client: Uploading resource file:/usr/lib/spark/examples/jars/spark-examples.jar -> hdfs://ip-172-31-37-222.us-west-2.compute.internal:8020/user/root/.sparkStaging/application_1492261407069_0007/spark-examples.jar
17/04/15 13:16:12 INFO Client: Uploading resource file:/mnt/tmp/spark-aa757ca0-4ff7-460c-8bee-27bc8c8dada9/__spark_conf__1370316719712336297.zip -> hdfs://ip-172-31-37-222.us-west-2.compute.internal:8020/user/root/.sparkStaging/application_1492261407069_0007/__spark_conf__.zip
17/04/15 13:16:13 INFO SecurityManager: Changing view acls to: root
17/04/15 13:16:13 INFO SecurityManager: Changing modify acls to: root
17/04/15 13:16:13 INFO SecurityManager: Changing view acls groups to:
17/04/15 13:16:13 INFO SecurityManager: Changing modify acls groups to:
17/04/15 13:16:13 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(root); groups with view permissions: Set(); users  with modify permissions: Set(root); groups with modify permissions: Set()

17/04/15 13:16:13 INFO Client: Submitting application application_1492261407069_0007 to ResourceManager
17/04/15 13:16:13 INFO YarnClientImpl: Submitted application application_1492261407069_0007
17/04/15 13:16:14 INFO Client: Application report for application_1492261407069_0007 (state: ACCEPTED)
17/04/15 13:16:14 INFO Client:
     client token: N/A
     diagnostics: N/A
     ApplicationMaster host: N/A
     ApplicationMaster RPC port: -1
     queue: default
     start time: 1492262173096
     final status: UNDEFINED
     tracking URL: http://ip-172-31-37-222.us-west-2.compute.internal:20888/proxy/application_1492261407069_0007/
     user: root
17/04/15 13:16:15 INFO Client: Application report for application_1492261407069_0007 (state: ACCEPTED)
17/04/15 13:16:24 INFO Client: Application report for application_1492261407069_0007 (state: ACCEPTED)
17/04/15 13:16:25 INFO Client: Application report for application_1492261407069_0007 (state: RUNNING)
17/04/15 13:16:25 INFO Client:
     client token: N/A
     diagnostics: N/A
     ApplicationMaster host: 172.31.33.215
     ApplicationMaster RPC port: 0
     queue: default
     start time: 1492262173096
     final status: UNDEFINED
     tracking URL: http://ip-172-31-37-222.us-west-2.compute.internal:20888/proxy/application_1492261407069_0007/
     user: root
17/04/15 13:16:26 INFO Client: Application report for application_1492261407069_0007 (state: RUNNING)
17/04/15 13:16:55 INFO Client: Application report for application_1492261407069_0007 (state: RUNNING)
17/04/15 13:16:56 INFO Client: Application report for application_1492261407069_0007 (state: FINISHED)
17/04/15 13:16:56 INFO Client:
     client token: N/A
     diagnostics: N/A
     ApplicationMaster host: 172.31.33.215
     ApplicationMaster RPC port: 0
     queue: default
     start time: 1492262173096
     final status: SUCCEEDED
     tracking URL: http://ip-172-31-37-222.us-west-2.compute.internal:20888/proxy/application_1492261407069_0007/
     user: root
17/04/15 13:16:56 INFO ShutdownHookManager: Shutdown hook called
17/04/15 13:16:56 INFO ShutdownHookManager: Deleting directory /mnt/tmp/spark-aa757ca0-4ff7-460c-8bee-27bc8c8dada9

Body:
You can use this:

spark-submit --deploy-mode client --executor-memory 4g --class org.apache.spark.examples.SparkPi /usr/lib/spark/examples/jars/spark-examples.jar


问:
How to create directory and file inside the same directory in ansible using single task
Is there any way to create directory and file inside the same directory in ansible using a single task? Currently, in my task, I'm creating a directory using a file module, state= directory. How to touch a file inside that directory in the same task?</p>

答:
@Dom H has given it correctly i just wanted it to give it more convenient way in playbook.

the playbook will look like :

```<code>---
- name: Creating directory and files
  hosts: localhost
  become: yes
  become_user: root

  tasks:

  - name: Create a directory with a file inside
    file:
      path: "{{ item.path }}"
      state: "{{ item.state }}"
    loop:
      - { path: /tmp/foo, state: directory }
      - { path: /tmp/foo/bar.txt, state: touch }
</code>```

and we can actually test before run it using:

```<code> ansible-playbook -i localhost mkdir.yml --check
</code>```

Body:
@Dom H has given it correctly i just wanted it to give it more convenient way in playbook.

the playbook will look like :

---
- name: Creating directory and files
  hosts: localhost
  become: yes
  become_user: root

  tasks:

  - name: Create a directory with a file inside
    file:
      path: "{{ item.path }}"
      state: "{{ item.state }}"
    loop:
      - { path: /tmp/foo, state: directory }
      - { path: /tmp/foo/bar.txt, state: touch }

and we can actually test before run it using:

 ansible-playbook -i localhost mkdir.yml --check


问:
Attempt to delete row 2 from section 1 which only contains 2 rows before the update
I'm trying to delete a row in a UITableView using a swipe action but keep receiving the following error:

'NSInternalInconsistencyException', reason: 'attempt to delete row 2 from section 1 which only contains 2 rows before the update'

The tableview has multiple sections.

Code below:

```<code>override func numberOfSections(in tableView: UITableView) -> Int {
   return favouriteSubjectTitlesArray.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return favouriteCaseIDsBySubjectArray[section].count
}

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
 if orientation == .left {
    //Unfavourite the case
    let unfavouriteAction = SwipeAction(style: .destructive, title: "Unfavourite") { action, indexPath in

    self.favouriteCaseIDsBySubjectArray[self.selectedSubjectID].remove(at: indexPath.row)
    DispatchQueue.main.async {
       self.tableView.deleteRows(at: [indexPath], with: .automatic)
      }
    }
return [unfavouriteAction]
  }
return nil
}
</code>```

Any ideas where I'm going wrong?

答:
Eventually found the solution: after updating the datasource with a struct, I found that you need to add action.fulfill(with: .delete) for SwipeCellKit.

Working code is therefore:

```<code>func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
 if orientation == .left {
    //Unfavourite the case
    let unfavouriteAction = SwipeAction(style: .destructive, title: "Unfavourite") { action, indexPath in

        self.favouriteCases.remove(at: indexPath)

        self.tableView.beginUpdates()
        self.tableView.deleteRows(at: [indexPath], with: .right)
        action.fulfill(with: .delete)
        self.tableView.endUpdates()

   return [unfavouriteAction]
  }
return nil
}
</code>```

Body:
I'm trying to delete a row in a UITableView using a swipe action but keep receiving the following error:

'NSInternalInconsistencyException', reason: 'attempt to delete row 2 from section 1 which only contains 2 rows before the update'

The tableview has multiple sections.

Code below:

override func numberOfSections(in tableView: UITableView) -> Int {
   return favouriteSubjectTitlesArray.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return favouriteCaseIDsBySubjectArray[section].count
}

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
 if orientation == .left {
    //Unfavourite the case
    let unfavouriteAction = SwipeAction(style: .destructive, title: "Unfavourite") { action, indexPath in

    self.favouriteCaseIDsBySubjectArray[self.selectedSubjectID].remove(at: indexPath.row)
    DispatchQueue.main.async {
       self.tableView.deleteRows(at: [indexPath], with: .automatic)
      }
    }
return [unfavouriteAction]
  }
return nil
}

Any ideas where I'm going wrong?

Body:
Eventually found the solution: after updating the datasource with a struct, I found that you need to add action.fulfill(with: .delete) for SwipeCellKit.

Working code is therefore:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
 if orientation == .left {
    //Unfavourite the case
    let unfavouriteAction = SwipeAction(style: .destructive, title: "Unfavourite") { action, indexPath in

        self.favouriteCases.remove(at: indexPath)

        self.tableView.beginUpdates()
        self.tableView.deleteRows(at: [indexPath], with: .right)
        action.fulfill(with: .delete)
        self.tableView.endUpdates()

   return [unfavouriteAction]
  }
return nil
}


问:
How to copy text generated by JavaScript?
I have a jsfiddle code to record the time and location of a click on an image. It works fine on any desktop platforms but scrolling and highlighting chunks of the text don’t work on iPad in chrome or safari. So as a workaround, I'd like to be able to copy the list of clicks and times that the javascript generates but not sure how. Any thoughts would be much appreciated.

https://jsfiddle.net/369z8Lxu

```<code><!-- Image Map Generated by http://www.image-map.net/ -->
<img src="https://hecoira.leeds.ac.uk/wp-content/uploads/sites/164/2019/08/0D174AF3-1221-42A4-878E-305FD6D829BF-e1564773811882.jpeg" usemap="#image-map">

<map name="image-map">
    <area target="" alt="IVStand" title="IVStand" href="javascript:ClickOnImageMap('IVStand');" coords="147,258,186,208" shape="rect">
    <area target="" alt="Chair" title="Chair" href="javascript:ClickOnImageMap('chair');" coords="68,262,163,343" shape="rect">
    <area target="" alt="DoorHandle" title="DoorHandle" href="javascript:ClickOnImageMap('DoorHandle');" coords="17,237,62,371" shape="rect">
    <area target="" alt="Bed" title="Bed" href="javascript:ClickOnImageMap('Bed');" coords="176,154,327,224" shape="rect">
    <area target="" alt="Window" title="Window" href="javascript:ClickOnImageMap('Window');" coords="159,119,43,8" shape="rect">
    <area target="" alt="Trolley" title="Trolley" href="javascript:ClickOnImageMap('Trolley');" coords="53,129,138,162" shape="rect">
    <area target="" alt="Sink" title="Sink" href="javascript:ClickOnImageMap('Sink');" coords="503,328,410,284" shape="rect">
    <area target="" alt="ClinicalWaste" title="ClinicalWaste" href="javascript:ClickOnImageMap('ClinicalWaste');" coords="297,327,406,374" shape="rect">
    <area target="" alt="AlcoholGel" title="AlcoholGel" href="javascript:ClickOnImageMap('AlcoholGel');" coords="399,258,504,158,504,241" shape="rect">
</map>

<p id="clicks">
Clicks:<br>
</p>
</code>```

Jscript

```<code>ClickOnImageMap = function(area){
    var oldHtml = document.getElementById("clicks").innerHTML;
  var now  = new Date();
  document.getElementById("clicks").innerHTML = oldHtml + area + ' ' + now.toLocaleString() + '<br>';
}
</code>```

答:
I was able to have it working using CSS user-select, I added the value all to demonstrate the selection, if you are testing it on Chrome Mac, use double click and hold for 2 seconds and it will select the text and right click menu will appear (that how Mac imitate touch select on Mac OS).

Update: I tested this on my machine iPad/iPhone simulator safari browser and worked for me! anyway maybe there is something wrong:

and

    <meta name="viewport" content="width=device-width, initial-scale=1">

<map name="image-map">
    <area target="" alt="IVStand" title="IVStand" href="javascript:ClickOnImageMap('IVStand');" coords="147,258,186,208" shape="rect">
    <area target="" alt="Chair" title="Chair" href="javascript:ClickOnImageMap('chair');" coords="68,262,163,343" shape="rect">
    <area target="" alt="DoorHandle" title="DoorHandle" href="javascript:ClickOnImageMap('DoorHandle');" coords="17,237,62,371" shape="rect">
    <area target="" alt="Bed" title="Bed" href="javascript:ClickOnImageMap('Bed');" coords="176,154,327,224" shape="rect">
    <area target="" alt="Window" title="Window" href="javascript:ClickOnImageMap('Window');" coords="159,119,43,8" shape="rect">
    <area target="" alt="Trolley" title="Trolley" href="javascript:ClickOnImageMap('Trolley');" coords="53,129,138,162" shape="rect">
    <area target="" alt="Sink" title="Sink" href="javascript:ClickOnImageMap('Sink');" coords="503,328,410,284" shape="rect">
    <area target="" alt="ClinicalWaste" title="ClinicalWaste" href="javascript:ClickOnImageMap('ClinicalWaste');" coords="297,327,406,374" shape="rect">
    <area target="" alt="AlcoholGel" title="AlcoholGel" href="javascript:ClickOnImageMap('AlcoholGel');" coords="399,258,504,158,504,241" shape="rect">
</map>

Clicks

```

Body:
I have a jsfiddle code to record the time and location of a click on an image. It works fine on any desktop platforms but scrolling and highlighting chunks of the text don’t work on iPad in chrome or safari. So as a workaround, I'd like to be able to copy the list of clicks and times that the javascript generates but not sure how. Any thoughts would be much appreciated.

https://jsfiddle.net/369z8Lxu

<map name="image-map">
    <area target="" alt="IVStand" title="IVStand" href="javascript:ClickOnImageMap('IVStand');" coords="147,258,186,208" shape="rect">
    <area target="" alt="Chair" title="Chair" href="javascript:ClickOnImageMap('chair');" coords="68,262,163,343" shape="rect">
    <area target="" alt="DoorHandle" title="DoorHandle" href="javascript:ClickOnImageMap('DoorHandle');" coords="17,237,62,371" shape="rect">
    <area target="" alt="Bed" title="Bed" href="javascript:ClickOnImageMap('Bed');" coords="176,154,327,224" shape="rect">
    <area target="" alt="Window" title="Window" href="javascript:ClickOnImageMap('Window');" coords="159,119,43,8" shape="rect">
    <area target="" alt="Trolley" title="Trolley" href="javascript:ClickOnImageMap('Trolley');" coords="53,129,138,162" shape="rect">
    <area target="" alt="Sink" title="Sink" href="javascript:ClickOnImageMap('Sink');" coords="503,328,410,284" shape="rect">
    <area target="" alt="ClinicalWaste" title="ClinicalWaste" href="javascript:ClickOnImageMap('ClinicalWaste');" coords="297,327,406,374" shape="rect">
    <area target="" alt="AlcoholGel" title="AlcoholGel" href="javascript:ClickOnImageMap('AlcoholGel');" coords="399,258,504,158,504,241" shape="rect">
</map>

Clicks:

Jscript

ClickOnImageMap = function(area){
    var oldHtml = document.getElementById("clicks").innerHTML;
  var now  = new Date();
  document.getElementById("clicks").innerHTML = oldHtml + area + ' ' + now.toLocaleString() + '
';
}

Body:
I was able to have it working using CSS user-select, I added the value all to demonstrate the selection, if you are testing it on Chrome Mac, use double click and hold for 2 seconds and it will select the text and right click menu will appear (that how Mac imitate touch select on Mac OS).

Update: I tested this on my machine iPad/iPhone simulator safari browser and worked for me! anyway maybe there is something wrong:

and

<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    p {
      zoom: 1;
      user-select: all;
      cursor: text
    }

    </style>
  </head>
  <body>
  <!-- Image Map Generated by http://www.image-map.net/ -->
<img src="https://hecoira.leeds.ac.uk/wp-content/uploads/sites/164/2019/08/0D174AF3-1221-42A4-878E-305FD6D829BF-e1564773811882.jpeg" usemap="#image-map">

<map name="image-map">
    <area target="" alt="IVStand" title="IVStand" href="javascript:ClickOnImageMap('IVStand');" coords="147,258,186,208" shape="rect">
    <area target="" alt="Chair" title="Chair" href="javascript:ClickOnImageMap('chair');" coords="68,262,163,343" shape="rect">
    <area target="" alt="DoorHandle" title="DoorHandle" href="javascript:ClickOnImageMap('DoorHandle');" coords="17,237,62,371" shape="rect">
    <area target="" alt="Bed" title="Bed" href="javascript:ClickOnImageMap('Bed');" coords="176,154,327,224" shape="rect">
    <area target="" alt="Window" title="Window" href="javascript:ClickOnImageMap('Window');" coords="159,119,43,8" shape="rect">
    <area target="" alt="Trolley" title="Trolley" href="javascript:ClickOnImageMap('Trolley');" coords="53,129,138,162" shape="rect">
    <area target="" alt="Sink" title="Sink" href="javascript:ClickOnImageMap('Sink');" coords="503,328,410,284" shape="rect">
    <area target="" alt="ClinicalWaste" title="ClinicalWaste" href="javascript:ClickOnImageMap('ClinicalWaste');" coords="297,327,406,374" shape="rect">
    <area target="" alt="AlcoholGel" title="AlcoholGel" href="javascript:ClickOnImageMap('AlcoholGel');" coords="399,258,504,158,504,241" shape="rect">
</map>

<p id="clicks">
Clicks
</p>

<script>

ClickOnImageMap = function(area){
 var oldHtml = document.getElementById("clicks").innerHTML;
  var now  = new Date();
  document.getElementById("clicks").innerHTML = oldHtml + area + ' ' + now.toLocaleString() + '<br>';
}

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


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

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

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

答:
Using the Hamcrest CoreMatcher (included in JUnit 4.4 and later) and assertThat():

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

Body:
Using the Hamcrest CoreMatcher (included in JUnit 4.4 and later) and assertThat():

assertThat(myString, anyOf(is("value1"), is("value2")));


问:
GatsbyJs update provider value from onRouteUpdate
I'm using a provider for holding global location using gatsby's browser API for accessing location by consumer in other components. The problem is i can't change the global location from onRouteUpdate, Here is my code:

gatsby-browser.js:

```<code>import React, {useContext} from 'react';

import Provider,{ appContext } from './provider';

export const onRouteUpdate = ({ location, prevLocation }) => {

    console.log('new pathname', location.pathname)
    console.log('old pathname', prevLocation ? prevLocation.pathname : null)

    // wanna set the new location for provider to use in other pages
    // this code does not work
    return(
        <appContext.Consumer>
        {context => {
            context.changeLocation(location.pathname)
        }})
        </appContext.Consumer>
    )

}
</code>```

Provider.js:

```<code>
import React, { useState } from 'react';
import { globalHistory as history } from '@reach/router'

export const appContext = React.createContext();

const Provider = props => {
  const [location, setLocation] = useState(history.location);

  return (
    <appContext.Provider value={{
      location,
      changeLocation: (newLocation)=> {setLocation({location:newLocation}); console.log('changing')}
    }}>
      {props.children}
    </appContext.Provider>
  )
};

export default Provider;

</code>```

Thanks.

答:
onRouteUpdate isn’t expected to return React nodes, and so the React element you’re returning isn't going to be evaluated like you’d expect.

Since you’re only looking to store the current page, you don’t actually need to do anything manually onRouteUpdate because this functionality is available out-of-the-box with Gatsby.

```<code>// gatsby-browser.js
import React from "react"
import { appContext } from "src/provider"

export const wrapPageElement = ({ element, props }) => (
  <AppContext.Provider value={{ location: props.location }}>
    {React.createElement(element, props)}
  </AppContext.Provider>
)
</code>```

Body:
I'm using a provider for holding global location using gatsby's browser API for accessing location by consumer in other components. The problem is i can't change the global location from onRouteUpdate, Here is my code:

gatsby-browser.js:

import React, {useContext} from 'react';

import Provider,{ appContext } from './provider';

export const onRouteUpdate = ({ location, prevLocation }) => {

    console.log('new pathname', location.pathname)
    console.log('old pathname', prevLocation ? prevLocation.pathname : null)

    // wanna set the new location for provider to use in other pages
    // this code does not work
    return(
        <appContext.Consumer>
        {context => {
            context.changeLocation(location.pathname)
        }})
        </appContext.Consumer>
    )

}

Provider.js:

import React, { useState } from 'react';
import { globalHistory as history } from '@reach/router'

export const appContext = React.createContext();

const Provider = props => {
  const [location, setLocation] = useState(history.location);

  return (
    <appContext.Provider value={{
      location,
      changeLocation: (newLocation)=> {setLocation({location:newLocation}); console.log('changing')}
    }}>
      {props.children}
    </appContext.Provider>
  )
};

export default Provider;

Thanks.

Body:
onRouteUpdate isn’t expected to return React nodes, and so the React element you’re returning isn't going to be evaluated like you’d expect.

Since you’re only looking to store the current page, you don’t actually need to do anything manually onRouteUpdate because this functionality is available out-of-the-box with Gatsby.

// gatsby-browser.js
import React from "react"
import { appContext } from "src/provider"

export const wrapPageElement = ({ element, props }) => (
  <AppContext.Provider value={{ location: props.location }}>
    {React.createElement(element, props)}
  </AppContext.Provider>
)


问:
Unable to dequeue single cell in collection view
I have come across a very disturbing issue in which I am not able to dequeue only a single cell in collectionView. When there are more than one item in collectionView, it works fine but soon as I have an array with a single item, it doesn't show any cell. I am not able to figure it out what’s wrong with my code.

```<code>extension collectionview: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UICollectionViewCell
        return cell
    }
}
</code>```

答: The number returned for numberOfItemsInSection should be the total number of objects you want to show, so if you have an array of objects for example, you would want to return the count of that array. Since it's currently set to one, only one item will be shown. If you change that to match the number of items you're displaying, then the collectionView should cooperate.</p>

Body:
I have come across a very disturbing issue in which I am not able to dequeue only a single cell in collectionView. When there are more than one item in collectionView, it works fine but soon as I have an array with a single item, it doesn't show any cell. I am not able to figure it out what’s wrong with my code.

extension collectionview: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UICollectionViewCell
        return cell
    }
}


问:
Is there a keyboard shortcut to maximize the Game window in Unity in Play Mode?
Ctrl + Space maximizes most windows in unity 2018 when in edit mode. Is there a keyboard shortcut to maximize the Game window when you're playing your game?

Can't find anything in the docs.

答:
Created a script to do the job that doesn't need to be attached to a gameobject:</p>

```<code>using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
static class FullscreenShortcut
{
    static FullscreenShortcut()
    {
        EditorApplication.update += Update;
    }

    static void Update()
    {
#if UNITY_EDITOR
        if (EditorApplication.isPlaying && ShouldToggleMaximize())
        {
            EditorWindow.focusedWindow.maximized = !EditorWindow.focusedWindow.maximized;
        }
#endif
    }

    private static bool ShouldToggleMaximize()
    {
        return Input.GetKey(KeyCode.Space) && Input.GetKey(KeyCode.LeftShift);
    }
}
</code>```

Body:
Created a script to do the job that doesn't need to be attached to a gameobject:

using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
static class FullscreenShortcut
{
    static FullscreenShortcut()
    {
        EditorApplication.update += Update;
    }

    static void Update()
    {
#if UNITY_EDITOR
        if (EditorApplication.isPlaying && ShouldToggleMaximize())
        {
            EditorWindow.focusedWindow.maximized = !EditorWindow.focusedWindow.maximized;
        }
#endif
    }

    private static bool ShouldToggleMaximize()
    {
        return Input.GetKey(KeyCode.Space) && Input.GetKey(KeyCode.LeftShift);
    }
}


问:
Correcting HEX values in Excel by appending additional zero
I did find a solution to previous asked problem on multi-row concatenation (https://stackoverflow.com/questions/60143273/openpyxl-concatenation-of-several-columns-into-one-cell-per-row-multi-row), but I found out that the HEX code is not displayed correctly in Excel. I found out that there are two cases, that I need to correct (Import of .csv/.txt after formatting columns/sheet did not work) the values that have a single digit in the columns F to M before concatenating them.
Excel changes "00" to "0" as well as "02" (or any other number instead of 2) to "2". This is important to me as the bits are going to be lost and all the data is going to be useless.

Desired Input:

```<code>A  B  C D  E            F            G   H  .. M
.. 2E .... 0000000000000AA4..
...4A ...  0002478304..
</code>```

Current Input:

```<code>A  B  C D  E            F            G   H  .. M
.. 2E .... 0000000AA4..
...4A ...  0247834..
</code>```

Organized:

```<code>A  B  C D  E            F            G   H  .. M
.. 2E .... 00 00 00 00 00 00 0A A4..
...4A ...  00  02 47 83 04..
</code>```

Code that I worked on up until now:

```<code>def concat_f_to_m():
    for row_value in range(1, sheet.max_row+1):
        values=[]
        del values[:]
        for row in sheet.iter_rows(min_col=6, max_col=14, min_row=row_value, max_row=row_value):
            for cell in row:
                if cell.value != None:
                    if cell.value == '0':
                        values.append("00")
                        print("zeros", values)
                    else:
                        values.append(str(cell.value))
                        print("non-zeros", values)
                    sheet[f'E{row_value}'].value= ''.join(values)
                else:
                    del values[:]
                    break
</code>```

I only worked on the one zero instead of two zero's issue before going over to solve the digit issue. Somehow the program does not even go into the if cell.value == '0' part. I do not know what the issue is. Could you explain to me why I am on the wrong track? Thank you!

答:
You can add a .zfill(x) to your string values so it is AT LEAST x length. Since you want 2 characters, you'll .zfill(2).

def concat_f_to_m():
    for row_value in range(1, sheet.max_row+1):
        values=[]
        del values[:]
        for row in sheet.iter_rows(min_col=6, max_col=14, min_row=row_value, max_row=row_value):
            for cell in row:
                if cell.value != None:
                    values.append(str(cell.value).zfill(2))
                    sheet[f'E{row_value}'].value= ''.join(values)
                else:
                    del values[:]
                    break
```

Body:
I did find a solution to previous asked problem on multi-row concatenation (https://stackoverflow.com/questions/60143273/openpyxl-concatenation-of-several-columns-into-one-cell-per-row-multi-row), but I found out that the HEX code is not displayed correctly in Excel. I found out that there are two cases, that I need to correct (Import of .csv/.txt after formatting columns/sheet did not work) the values that have a single digit in the columns F to M before concatenating them.
Excel changes "00" to "0" as well as "02" (or any other number instead of 2) to "2". This is important to me as the bits are going to be lost and all the data is going to be useless.

Desired Input:

A  B  C D  E            F            G   H  .. M
.. 2E .... 0000000000000AA4..
...4A ...  0002478304..

Current Input:

A  B  C D  E            F            G   H  .. M
.. 2E .... 0000000AA4..
...4A ...  0247834..

Organized:

A  B  C D  E            F            G   H  .. M
.. 2E .... 00 00 00 00 00 00 0A A4..
...4A ...  00  02 47 83 04..

Code that I worked on up until now:

def concat_f_to_m():
    for row_value in range(1, sheet.max_row+1):
        values=[]
        del values[:]
        for row in sheet.iter_rows(min_col=6, max_col=14, min_row=row_value, max_row=row_value):
            for cell in row:
                if cell.value != None:
                    if cell.value == '0':
                        values.append("00")
                        print("zeros", values)
                    else:
                        values.append(str(cell.value))
                        print("non-zeros", values)
                    sheet[f'E{row_value}'].value= ''.join(values)
                else:
                    del values[:]
                    break

I only worked on the one zero instead of two zero's issue before going over to solve the digit issue. Somehow the program does not even go into the if cell.value == '0' part. I do not know what the issue is. Could you explain to me why I am on the wrong track? Thank you!


问:
console input C
I am a beginner in C and would like to know what's the problem about my code here :

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

int main(void)
{
    int a;

    printf("Please input an integer value: ");
    scanf("%d", &a);
    printf("You entered: %d\n", a);

    return 0;
}
</code>```

My problem is that I have to type a value before having any consol output, for example if I type 7, I get this console output : Please input an integer value: You entered: 7

I tried the exact same code in another computer and it worked pretty well, I guess it's a buffer problem ? but I have no idea how to fix it.. Any ideas please ?

答:
As other already mentioned, to guarantee that that line is going to be printed at that point in your code you can flush the standard output like this,

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

int main(void)
{
    int a;

    printf("Please input an integer value: ");
    fflush(stdout);
    scanf("%d", &a);
    printf("You entered: %d\n", a);

    return 0;
}
</code>```

you can read this for more details, Why does printf not flush after the call unless a newline is in the format string?

updated thanks to @Osiris comments

Title: console input C

Body:
I am a beginner in C and would like to know what's the problem about my code here :

#include "stdio.h"

int main(void)
{
    int a;

    printf("Please input an integer value: ");
    scanf("%d", &a);
    printf("You entered: %d\n", a);

    return 0;
}

My problem is that I have to type a value before having any consol output, for example if I type 7, I get this console output : Please input an integer value: You entered: 7

I tried the exact same code in another computer and it worked pretty well, I guess it's a buffer problem ? but I have no idea how to fix it.. Any ideas please ?

Body:
As other already mentioned, to guarantee that that line is going to be printed at that point in your code you can flush the standard output like this,

#include "stdio.h"

int main(void)
{
    int a;

    printf("Please input an integer value: ");
    fflush(stdout);
    scanf("%d", &a);
    printf("You entered: %d\n", a);

    return 0;
}

you can read this for more details, Why does printf not flush after the call unless a newline is in the format string?

updated thanks to @Osiris comments


问:
Call CreateProcess() and get return value of a string
I have a C++ application that calls an EXE written in C# which grabs some information, and I want to pass it back as a string to the calling C++ application.

So my question is, "is it possible to get a return value of string data from an EXE called with CreateProcess()?

I hope I didn't violate any "question" etiquette here.

答: If the C# app outputs its data to STDOUT or STDERR, the C++ app can capture it by redirecting STDOUT/STDERR when it calls CreateProcess().  See Creating a Child Process with Redirected Input and Output on MSDN for details and examples.


问:
axis.text does not change angle
I understand that in order to change the angle of x-axis we should use theme() and axis.text.x=element_text(size=1, angle=90)

For the plot, I used geom_col because my x-axis is not a continuous variable, just categories. Could anyone let me know what I did wrong or missed? Something must be obvious for R and ggplot savvy users! Thank you!

```<code>data("diamonds")
example_df <- diamonds[unique(diamonds$clarity), ]

ggplot(example_df, aes(reorder(clarity, -carat, sum), carat)) +
  geom_col() +
  xlab("clarity")+
  ylab("carat") +
  theme(axis.text.x=element_text(size=1, angle=45)) +
  geom_hline(yintercept=0.2, linetype="dashed", color = "red") +
  ggtitle("test") +
  theme_bw()
</code>```

答:
Calling theme_bw() at the end resets all the theme changes you previously added in. Only the last value survives. Just change the order in which you set the values

```<code>ggplot(example_df, aes(reorder(clarity, -carat, sum), carat)) +
  geom_col() +
  xlab("clarity")+
  ylab("carat") +
  geom_hline(yintercept=0.2, linetype="dashed", color = "red") +
  ggtitle("test") +
  theme_bw() +
  theme(axis.text.x=element_text(size=1, angle=45))
</code>```

Title: axis.text does not change angle

Body:
I understand that in order to change the angle of x-axis we should use theme() and axis.text.x=element_text(size=1, angle=90)

For the plot, I used geom_col because my x-axis is not a continuous variable, just categories. Could anyone let me know what I did wrong or missed? Something must be obvious for R and ggplot savvy users! Thank you!

data("diamonds")
example_df <- diamonds[unique(diamonds$clarity), ]

ggplot(example_df, aes(reorder(clarity, -carat, sum), carat)) +
  geom_col() +
  xlab("clarity")+
  ylab("carat") +
  theme(axis.text.x=element_text(size=1, angle=45)) +
  geom_hline(yintercept=0.2, linetype="dashed", color = "red") +
  ggtitle("test") +
  theme_bw()

Body:
Calling theme_bw() at the end resets all the theme changes you previously added in. Only the last value survives. Just change the order in which you set the values

ggplot(example_df, aes(reorder(clarity, -carat, sum), carat)) +
  geom_col() +
  xlab("clarity")+
  ylab("carat") +
  geom_hline(yintercept=0.2, linetype="dashed", color = "red") +
  ggtitle("test") +
  theme_bw() +
  theme(axis.text.x=element_text(size=1, angle=45))