问:
I can't get any result or errors when i'm drawing signatures on expo app
i'm creating a small react native app using expo, I am trying to run the example given at https://www.npmjs.com/package/react-native-signature-canvas for drawing signatures, i'm getting an interface but i can't draw and i'm not getting any result.

My code:

```<code>import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import Signature from 'react-native-signature-canvas';

class SignatureScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = { signature: null };
  }

  handleSignature = signature => {
    this.setState({ signature });
  };

  render() {
    const style = `.m-signature-pad--footer
    .button {
      background-color: blue;
      color: #FFF;
    }`;
    return (
      <View style={{ flex: 1 }}>
        <View style={styles.preview}>
          {this.state.signature ? (
            <Image
              resizeMode={"contain"}
              style={{ width: 335, height: 114 }}
              source={{ uri: this.state.signature }}
            />
          ) : null}
        </View>
        <Signature
          onOK={this.handleSignature}
          descriptionText="Sign"
          clearText="Clear"
          confirmText="Save"
          webStyle={style}
        />
      </View>
    );
  }
}

export default SignatureScreen;

const styles = StyleSheet.create({
  preview: {
    width: 335,
    height: 114,
    backgroundColor: "#F8F8F8",
    justifyContent: "center",
    alignItems: "center",
    marginTop: 15
  },
  previewText: {
    color: "#FFF",
    fontSize: 14,
    height: 40,
    lineHeight: 40,
    paddingLeft: 10,
    paddingRight: 10,
    backgroundColor: "#69B2FF",
    width: 120,
    textAlign: "center",
    marginTop: 10
  }
});
</code>```

Am I missing something?

答:
could you try this code?

 handleSignature = signature => {
    console.log(signature);
    this.setState({ signature });
  };
...
  render() {
    return (
      <View style={{ flex: 1 }}>
        <View style={styles.preview}>
          {this.state.signature ? (
            <Image
              resizeMode={"contain"}
              style={{ width: 335, height: 114 }}
              source={{ uri: this.state.signature }}
            />
          ) : null}
        </View>
        <SignatureScreen onOK={this.handleSignature} />
      </View>
    );
  }
}
```

Body:
i'm creating a small react native app using expo, I am trying to run the example given at https://www.npmjs.com/package/react-native-signature-canvas for drawing signatures, i'm getting an interface but i can't draw and i'm not getting any result.

My code:

import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import Signature from 'react-native-signature-canvas';

class SignatureScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = { signature: null };
  }

  handleSignature = signature => {
    this.setState({ signature });
  };

  render() {
    const style = `.m-signature-pad--footer
    .button {
      background-color: blue;
      color: #FFF;
    }`;
    return (
      <View style={{ flex: 1 }}>
        <View style={styles.preview}>
          {this.state.signature ? (
            <Image
              resizeMode={"contain"}
              style={{ width: 335, height: 114 }}
              source={{ uri: this.state.signature }}
            />
          ) : null}
        </View>
        <Signature
          onOK={this.handleSignature}
          descriptionText="Sign"
          clearText="Clear"
          confirmText="Save"
          webStyle={style}
        />
      </View>
    );
  }
}

export default SignatureScreen;

const styles = StyleSheet.create({
  preview: {
    width: 335,
    height: 114,
    backgroundColor: "#F8F8F8",
    justifyContent: "center",
    alignItems: "center",
    marginTop: 15
  },
  previewText: {
    color: "#FFF",
    fontSize: 14,
    height: 40,
    lineHeight: 40,
    paddingLeft: 10,
    paddingRight: 10,
    backgroundColor: "#69B2FF",
    width: 120,
    textAlign: "center",
    marginTop: 10
  }
});

Am I missing something?


来源: stackexchange

问:
how to avoid memory wastage when storing UTF-8 characters (8 bit) in Java character (16 bit). two in one?
I'm afraid I have a question on a detail of a rather oversaturated topic, I searched aroudn a lot, but couldn't find a clear answer to that specific obvious -imho- important, problem:

When converting byte[] to String using UTF-8, each byte (8bit) becomes a 8 bit character encoded by UTF-8, but each UTF-8 character is saved as a 16 bit character in java. Is that correct?
If yes, this means, that each stupid java character only uses the first 8 bits, and consumes double the memory? Is that correct too? I wonder how this wasteful behaviour is acceptable..

Isn't there some trick to have a pseudo String that is 8 bit?  Would that actually result in less memory consumption?
Or maybe, is there a way to store >two< 8bit characters in one java 16bit character to avoid this memory waste?

thanks for any deconfusing answers...

EDIT:
hi, thanks everybody for answering. I was aware of the variable-length property of UTF-8. However, since my source is byte which is 8 bit, I understood (apparently wrongly) that it needs only 8-bit UTF-8 words. Is UTF-8 conversion actually saving the strange symbols that you see when on the CLI you do "cat somebinary" ? I thought UTF-8 was just somehow used to map each of the possible 8bit words of byte to one particular 8 bit word of UTF-8. Wrong? I thought about using Base64 but it's bad because it uses only 7 bit..

questions reformulated: is there a smarter way to convert byte to something String?
May favorite was to just cast byte[] to char[], but then I still have 16bit words.

additional use case info:

I'm adapting Jedis (java client for the NoSQL Redis) as the  "primitive storage layer" for hypergraphDB. So, jedis is a database for another "database".
My problem is that I have to feed jedis with byte[] data all the time, but internally, >Redis< (the actual server)  is dealing only with "binary safe" Strings. Since Redis is written in C, a char is 8 bit long, AFAIK not ASCIII which is 7 bit. In Jedis however, java world, every character is 16 bit long internally. I don't understand this code (yet), but I suppose jedis then converts this java 16 bit strings to a Redis conforming 8 bit string (([here][3]). It says it extends FilterOutputStream. My hope is to bypass the byte[] <-> string conversion altogether and use that Filteroutputstream...?  )

now I wonder: if I had to interconvert byte[] and String all the time, with datasizes ranging from very small to potentially very big, isn't there a huge waste of memory to have each 8 bit character passed around as 16bit within java?

答:
Java stores all it's "chars" internally as two bytes representations of the value. However, they aren't stored the same as UTF-8. For example, the max value supported is "\uFFFF" (hex FFFF, dec 65536), or 11111111 11111111 binary (two bytes) - but this would be a 3 byte Unicode character on disk.

The only possible wastage is for genuinely 'single' byte characters in memory (most ASCII 'language' characters actually fit in 7bits). When the characters are written to disk, they'll be in the specified encoding anyway (so UTF-8 single byte characters will only occupy one byte).

The only place it makes a difference is in the JVM heap. However, you'd have to have thousands and thousands of 8-bit characters to notice any real difference in Java heap usage - which would be far outweighed by all the extra (hacky) processing you've done.

A million-odd 8-bit characters in RAM is only 'wasting' about 1 MiB anyway...

ContentLicense: CC BY-SA 3.0


问:
Forcing MathJax to Wrap in Shiny div
I have a long MathJax expression that I need to print in a Shiny app.  Because the expression's so long, it needs to wrap across lines.  However, it currently refuses to do so.

I strongly suspect it has to do with the equation not being rendered as conventional text (i.e., it's not being rendered as a string, but as a series of spans), which rules out the usual ways you'd make a div's content wrap.

I know that MathJax supports line wraps (here). I can also get UI equations to wrap using KaTeX (see second code block below), but would prefer to keep everything in MathJax, with how complex the overall app is.

What I've tried:

Via CSS, variants of the following for the "MathJax" class (.MathJax)

word-break: break-all;

word-wrap: break-word;

display: flex;

flex-wrap: wrap;

Setting white-space: nowrap; to white-space: normal; for .MathJax (which shouldn't matter at all, I recognize)

Putting the equation in a wrapper div, and then trying to set that wrapper div's CSS properties as in the two bullets above (plus a variant where I also hardcoded the div's width)

Declaring the following as the first line within the UI function:

```<code>tags$script(type="text/x-mathjax-config", "
    MathJax.Hub.Config({
        \"HTML-CSS\": { linebreaks: { automatic: true;} },
    });
"),
</code>```

Another variant of the above:

```<code>tags$script(type="text/x-mathjax-config", "
    MathJax.Hub.Config({
        \"HTML-CSS\": { linebreaks: { automatic: true;} },
        tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
    });
"),
</code>```

The above '),
    HTML('<script defer src="https://cdn.jsdelivr.net/npm/katex@0.10.1/dist/contrib/auto-render.min.js" integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI" crossorigin="anonymous"></script>'),
    HTML('
    <script>
      document.addEventListener("DOMContentLoaded", function(){
        renderMathInElement(document.body, {
          delimiters: [{left: "$", right: "$", display: false}]
        });
      })
    </script>')
    ),
    h2("UI"),
    withMathJax(),

    # something arbitrary and long
    p(" $ f\\left( \\alpha, \\beta_1 | x_i\\right) =  \\left(3.5-0.75*-1.414\\right)+ \\left(3.5-0.75*0.189\\right)+ \\left(3.5-0.75*0.026\\right)+ \\left(3.5-0.75*-0.779\\right)+ \\left(3.5-0.75*0.683\\right)+ \\left(3.5-0.75*-0.503\\right)+ \\left(3.5-0.75*-1.18\\right)+ \\left(3.5-0.75*-1.736\\right)+ \\left(3.5-0.75*-1.497\\right)+ \\left(3.5-0.75*-1.12\\right)+ \\left(3.5-0.75*1.263\\right)+ \\left(3.5-0.75*0.512\\right)+ \\left(3.5-0.75*-0.143\\right)+ \\left(3.5-0.75*-0.464\\right)+ \\left(3.5-0.75*-0.016\\right)+ \\left(3.5-0.75*-0.835\\right)+ \\left(3.5-0.75*0.611\\right)+ \\left(3.5-0.75*0\\right)+ \\left(3.5-0.75*-0.117\\right)+ \\left(3.5-0.75*-1.645\\right)+ \\left(3.5-0.75*-1.929\\right)+ \\left(3.5-0.75*-0.026\\right)+ \\left(3.5-0.75*-1.121\\right)+ \\left(3.5-0.75*0.61\\right)+ \\left(3.5-0.75*-0.619\\right)+ \\left(3.5-0.75*0.806\\right)+ \\left(3.5-0.75*-0.123\\right)+ \\left(3.5-0.75*-1.617\\right)+ \\left(3.5-0.75*-0.683\\right)+ \\left(3.5-0.75*0.431\\right)+ \\left(3.5-0.75*2.705\\right)+ \\left(3.5-0.75*0.726\\right)+ \\left(3.5-0.75*-0.483\\right)+ \\left(3.5-0.75*2.135\\right)+ \\left(3.5-0.75*-0.399\\right)+ \\left(3.5-0.75*-0.087\\right)+ \\left(3.5-0.75*-1.004\\right)+ \\left(3.5-0.75*0.18\\right)+ \\left(3.5-0.75*0.229\\right)+ \\left(3.5-0.75*0.671\\right)+ \\left(3.5-0.75*0.234\\right)+ \\left(3.5-0.75*0.874\\right)+ \\left(3.5-0.75*-0.275\\right)+ \\left(3.5-0.75*-0.812\\right)+ \\left(3.5-0.75*0.363\\right)+ \\left(3.5-0.75*-0.549\\right)+ \\left(3.5-0.75*0.32\\right)+ \\left(3.5-0.75*0.667\\right)+ \\left(3.5-0.75*0.44\\right)+ \\left(3.5-0.75*-0.492\\right)+ \\left(3.5-0.75*0.879\\right)+ \\left(3.5-0.75*3.122\\right)+ \\left(3.5-0.75*-0.82\\right)+ \\left(3.5-0.75*-0.65\\right)+ \\left(3.5-0.75*-0.4\\right)+ \\left(3.5-0.75*-0.144\\right)+ \\left(3.5-0.75*1.132\\right)+ \\left(3.5-0.75*0.505\\right)+ \\left(3.5-0.75*0.452\\right)+ \\left(3.5-0.75*0.615\\right)+ \\left(3.5-0.75*-0.94\\right)+ \\left(3.5-0.75*-2.144\\right)+ \\left(3.5-0.75*-1.2\\right)+ \\left(3.5-0.75*-2.893\\right)+ \\left(3.5-0.75*-0.19\\right)+ \\left(3.5-0.75*0.433\\right)+ \\left(3.5-0.75*2.023\\right)+ \\left(3.5-0.75*0.046\\right)+ \\left(3.5-0.75*0.602\\right)+ \\left(3.5-0.75*-0.862\\right)+ \\left(3.5-0.75*-0.687\\right)+ \\left(3.5-0.75*0.907\\right)+ \\left(3.5-0.75*-0.966\\right)+ \\left(3.5-0.75*-1.694\\right)+ \\left(3.5-0.75*1.28\\right)+ \\left(3.5-0.75*1.178\\right)+ \\left(3.5-0.75*-1.077\\right)+ \\left(3.5-0.75*-0.433\\right)+ \\left(3.5-0.75*-0.274\\right)+ \\left(3.5-0.75*-0.725\\right)+ \\left(3.5-0.75*0.735\\right)+ \\left(3.5-0.75*-0.067\\right)+ \\left(3.5-0.75*0.176\\right)+ \\left(3.5-0.75*1.653\\right)+ \\left(3.5-0.75*0.212\\right)+ \\left(3.5-0.75*2.976\\right)+ \\left(3.5-0.75*-0.523\\right)+ \\left(3.5-0.75*-1.426\\right)+ \\left(3.5-0.75*0.673\\right)+ \\left(3.5-0.75*-1.079\\right)+ \\left(3.5-0.75*0.99\\right)+ \\left(3.5-0.75*0.628\\right)+ \\left(3.5-0.75*0.188\\right)+ \\left(3.5-0.75*0.992\\right)+ \\left(3.5-0.75*0.467\\right)+ \\left(3.5-0.75*-0.251\\right)+ \\left(3.5-0.75*1.403\\right)+ \\left(3.5-0.75*0.667\\right)+ \\left(3.5-0.75*1.23\\right)+ \\left(3.5-0.75*1.342\\right)+ \\left(3.5-0.75*1.713\\right)+ \\left(3.5-0.75*0.182\\right)+ \\left(3.5-0.75*0.758\\right)+ \\left(3.5-0.75*0.035\\right)+ \\left(3.5-0.75*0.932\\right)+ \\left(3.5-0.75*0.702\\right)+ \\left(3.5-0.75*0.436\\right)+ \\left(3.5-0.75*-1.355\\right)+ \\left(3.5-0.75*-1.318\\right)+ \\left(3.5-0.75*-0.109\\right)+ \\left(3.5-0.75*0.437\\right)+ \\left(3.5-0.75*-0.842\\right)+ \\left(3.5-0.75*0.977\\right)+ \\left(3.5-0.75*-1.503\\right)+ \\left(3.5-0.75*-0.253\\right)+ \\left(3.5-0.75*-1.166\\right)+ \\left(3.5-0.75*-0.274\\right)+ \\left(3.5-0.75*-1.083\\right)+ \\left(3.5-0.75*0.086\\right)+ \\left(3.5-0.75*0.807\\right)+ \\left(3.5-0.75*-0.068\\right)+ \\left(3.5-0.75*0.682\\right)+ \\left(3.5-0.75*0.26\\right)+ \\left(3.5-0.75*1.225\\right)+ \\left(3.5-0.75*1.82\\right)+ \\left(3.5-0.75*-1.444\\right)+ \\left(3.5-0.75*-0.579\\right)+ \\left(3.5-0.75*-0.945\\right)+ \\left(3.5-0.75*-0.743\\right)+ \\left(3.5-0.75*-0.423\\right)+ \\left(3.5-0.75*-0.086\\right)+ \\left(3.5-0.75*-0.105\\right)+ \\left(3.5-0.75*0.385\\right)+ \\left(3.5-0.75*0.733\\right)+ \\left(3.5-0.75*-1.131\\right)+ \\left(3.5-0.75*3.334\\right)+ \\left(3.5-0.75*-0.254\\right)+ \\left(3.5-0.75*0.304\\right)+ \\left(3.5-0.75*1.234\\right)+ \\left(3.5-0.75*1.144\\right)+ \\left(3.5-0.75*0.558\\right)+ \\left(3.5-0.75*-0.675\\right)+ \\left(3.5-0.75*-1.729\\right)+ \\left(3.5-0.75*-1.504\\right)+ \\left(3.5-0.75*-1.951\\right)+ \\left(3.5-0.75*0.203\\right)+ \\left(3.5-0.75*-0.154\\right)+ \\left(3.5-0.75*-0.545\\right)+ \\left(3.5-0.75*-0.913\\right)+ \\left(3.5-0.75*-1.11\\right)$  "
    ),

    h2("Server"),
    uiOutput("eqSrv")
)

# Define the server code
server <- function(input, output) {
    output$eqSrv<- renderUI({
        # something arbitrary and long
        withMathJax(
            "$$ f\\left( \\alpha, \\beta_1 | x_i\\right) =  \\left(3.5-0.75*-1.414\\right)+ \\left(3.5-0.75*0.189\\right)+ \\left(3.5-0.75*0.026\\right)+ \\left(3.5-0.75*-0.779\\right)+ \\left(3.5-0.75*0.683\\right)+ \\left(3.5-0.75*-0.503\\right)+ \\left(3.5-0.75*-1.18\\right)+ \\left(3.5-0.75*-1.736\\right)+ \\left(3.5-0.75*-1.497\\right)+ \\left(3.5-0.75*-1.12\\right)+ \\left(3.5-0.75*1.263\\right)+ \\left(3.5-0.75*0.512\\right)+ \\left(3.5-0.75*-0.143\\right)+ \\left(3.5-0.75*-0.464\\right)+ \\left(3.5-0.75*-0.016\\right)+ \\left(3.5-0.75*-0.835\\right)+ \\left(3.5-0.75*0.611\\right)+ \\left(3.5-0.75*0\\right)+ \\left(3.5-0.75*-0.117\\right)+ \\left(3.5-0.75*-1.645\\right)+ \\left(3.5-0.75*-1.929\\right)+ \\left(3.5-0.75*-0.026\\right)+ \\left(3.5-0.75*-1.121\\right)+ \\left(3.5-0.75*0.61\\right)+ \\left(3.5-0.75*-0.619\\right)+ \\left(3.5-0.75*0.806\\right)+ \\left(3.5-0.75*-0.123\\right)+ \\left(3.5-0.75*-1.617\\right)+ \\left(3.5-0.75*-0.683\\right)+ \\left(3.5-0.75*0.431\\right)+ \\left(3.5-0.75*2.705\\right)+ \\left(3.5-0.75*0.726\\right)+ \\left(3.5-0.75*-0.483\\right)+ \\left(3.5-0.75*2.135\\right)+ \\left(3.5-0.75*-0.399\\right)+ \\left(3.5-0.75*-0.087\\right)+ \\left(3.5-0.75*-1.004\\right)+ \\left(3.5-0.75*0.18\\right)+ \\left(3.5-0.75*0.229\\right)+ \\left(3.5-0.75*0.671\\right)+ \\left(3.5-0.75*0.234\\right)+ \\left(3.5-0.75*0.874\\right)+ \\left(3.5-0.75*-0.275\\right)+ \\left(3.5-0.75*-0.812\\right)+ \\left(3.5-0.75*0.363\\right)+ \\left(3.5-0.75*-0.549\\right)+ \\left(3.5-0.75*0.32\\right)+ \\left(3.5-0.75*0.667\\right)+ \\left(3.5-0.75*0.44\\right)+ \\left(3.5-0.75*-0.492\\right)+ \\left(3.5-0.75*0.879\\right)+ \\left(3.5-0.75*3.122\\right)+ \\left(3.5-0.75*-0.82\\right)+ \\left(3.5-0.75*-0.65\\right)+ \\left(3.5-0.75*-0.4\\right)+ \\left(3.5-0.75*-0.144\\right)+ \\left(3.5-0.75*1.132\\right)+ \\left(3.5-0.75*0.505\\right)+ \\left(3.5-0.75*0.452\\right)+ \\left(3.5-0.75*0.615\\right)+ \\left(3.5-0.75*-0.94\\right)+ \\left(3.5-0.75*-2.144\\right)+ \\left(3.5-0.75*-1.2\\right)+ \\left(3.5-0.75*-2.893\\right)+ \\left(3.5-0.75*-0.19\\right)+ \\left(3.5-0.75*0.433\\right)+ \\left(3.5-0.75*2.023\\right)+ \\left(3.5-0.75*0.046\\right)+ \\left(3.5-0.75*0.602\\right)+ \\left(3.5-0.75*-0.862\\right)+ \\left(3.5-0.75*-0.687\\right)+ \\left(3.5-0.75*0.907\\right)+ \\left(3.5-0.75*-0.966\\right)+ \\left(3.5-0.75*-1.694\\right)+ \\left(3.5-0.75*1.28\\right)+ \\left(3.5-0.75*1.178\\right)+ \\left(3.5-0.75*-1.077\\right)+ \\left(3.5-0.75*-0.433\\right)+ \\left(3.5-0.75*-0.274\\right)+ \\left(3.5-0.75*-0.725\\right)+ \\left(3.5-0.75*0.735\\right)+ \\left(3.5-0.75*-0.067\\right)+ \\left(3.5-0.75*0.176\\right)+ \\left(3.5-0.75*1.653\\right)+ \\left(3.5-0.75*0.212\\right)+ \\left(3.5-0.75*2.976\\right)+ \\left(3.5-0.75*-0.523\\right)+ \\left(3.5-0.75*-1.426\\right)+ \\left(3.5-0.75*0.673\\right)+ \\left(3.5-0.75*-1.079\\right)+ \\left(3.5-0.75*0.99\\right)+ \\left(3.5-0.75*0.628\\right)+ \\left(3.5-0.75*0.188\\right)+ \\left(3.5-0.75*0.992\\right)+ \\left(3.5-0.75*0.467\\right)+ \\left(3.5-0.75*-0.251\\right)+ \\left(3.5-0.75*1.403\\right)+ \\left(3.5-0.75*0.667\\right)+ \\left(3.5-0.75*1.23\\right)+ \\left(3.5-0.75*1.342\\right)+ \\left(3.5-0.75*1.713\\right)+ \\left(3.5-0.75*0.182\\right)+ \\left(3.5-0.75*0.758\\right)+ \\left(3.5-0.75*0.035\\right)+ \\left(3.5-0.75*0.932\\right)+ \\left(3.5-0.75*0.702\\right)+ \\left(3.5-0.75*0.436\\right)+ \\left(3.5-0.75*-1.355\\right)+ \\left(3.5-0.75*-1.318\\right)+ \\left(3.5-0.75*-0.109\\right)+ \\left(3.5-0.75*0.437\\right)+ \\left(3.5-0.75*-0.842\\right)+ \\left(3.5-0.75*0.977\\right)+ \\left(3.5-0.75*-1.503\\right)+ \\left(3.5-0.75*-0.253\\right)+ \\left(3.5-0.75*-1.166\\right)+ \\left(3.5-0.75*-0.274\\right)+ \\left(3.5-0.75*-1.083\\right)+ \\left(3.5-0.75*0.086\\right)+ \\left(3.5-0.75*0.807\\right)+ \\left(3.5-0.75*-0.068\\right)+ \\left(3.5-0.75*0.682\\right)+ \\left(3.5-0.75*0.26\\right)+ \\left(3.5-0.75*1.225\\right)+ \\left(3.5-0.75*1.82\\right)+ \\left(3.5-0.75*-1.444\\right)+ \\left(3.5-0.75*-0.579\\right)+ \\left(3.5-0.75*-0.945\\right)+ \\left(3.5-0.75*-0.743\\right)+ \\left(3.5-0.75*-0.423\\right)+ \\left(3.5-0.75*-0.086\\right)+ \\left(3.5-0.75*-0.105\\right)+ \\left(3.5-0.75*0.385\\right)+ \\left(3.5-0.75*0.733\\right)+ \\left(3.5-0.75*-1.131\\right)+ \\left(3.5-0.75*3.334\\right)+ \\left(3.5-0.75*-0.254\\right)+ \\left(3.5-0.75*0.304\\right)+ \\left(3.5-0.75*1.234\\right)+ \\left(3.5-0.75*1.144\\right)+ \\left(3.5-0.75*0.558\\right)+ \\left(3.5-0.75*-0.675\\right)+ \\left(3.5-0.75*-1.729\\right)+ \\left(3.5-0.75*-1.504\\right)+ \\left(3.5-0.75*-1.951\\right)+ \\left(3.5-0.75*0.203\\right)+ \\left(3.5-0.75*-0.154\\right)+ \\left(3.5-0.75*-0.545\\right)+ \\left(3.5-0.75*-0.913\\right)+ \\left(3.5-0.75*-1.11\\right) $$"
        )

    })
}

# Return a Shiny app object
shinyApp(ui = ui, server = server)
```

答:
The MathJax config works if you put it in tags$head:

```<code>  tags$head(tags$script(type = "text/x-mathjax-config",
                        'MathJax.Hub.Config({
  "HTML-CSS": { linebreaks: { automatic: true } },
         SVG: { linebreaks: { automatic: true } }
});')),
</code>```

ContentLicense: CC BY-SA 4.0

Title: Forcing MathJax to Wrap in Shiny div

Body:
I have a long MathJax expression that I need to print in a Shiny app.  Because the expression's so long, it needs to wrap across lines.  However, it currently refuses to do so.

I strongly suspect it has to do with the equation not being rendered as conventional text (i.e., it's not being rendered as a string, but as a series of spans), which rules out the usual ways you'd make a div's content wrap.

I know that MathJax supports line wraps (here). I can also get UI equations to wrap using KaTeX (see second code block below), but would prefer to keep everything in MathJax, with how complex the overall app is.

What I've tried:

Via CSS, variants of the following for the "MathJax" class (.MathJax)

word-break: break-all;

word-wrap: break-word;

display: flex;

flex-wrap: wrap;

Setting white-space: nowrap; to white-space: normal; for .MathJax (which shouldn't matter at all, I recognize)

Putting the equation in a wrapper div, and then trying to set that wrapper div's CSS properties as in the two bullets above (plus a variant where I also hardcoded the div's width)

Declaring the following as the first line within the UI function:

tags$script(type="text/x-mathjax-config", "
    MathJax.Hub.Config({
        \"HTML-CSS\": { linebreaks: { automatic: true;} },
    });
"),

Another variant of the above:

tags$script(type="text/x-mathjax-config", "
    MathJax.Hub.Config({
        \"HTML-CSS\": { linebreaks: { automatic: true;} },
        tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
    });
"),

The above '),
    HTML(''),
    HTML('
    ')
    ),
    h2("UI"),
    withMathJax(),

    # something arbitrary and long
    p(" $ f\\left( \\alpha, \\beta_1 | x_i\\right) =  \\left(3.5-0.75*-1.414\\right)+ \\left(3.5-0.75*0.189\\right)+ \\left(3.5-0.75*0.026\\right)+ \\left(3.5-0.75*-0.779\\right)+ \\left(3.5-0.75*0.683\\right)+ \\left(3.5-0.75*-0.503\\right)+ \\left(3.5-0.75*-1.18\\right)+ \\left(3.5-0.75*-1.736\\right)+ \\left(3.5-0.75*-1.497\\right)+ \\left(3.5-0.75*-1.12\\right)+ \\left(3.5-0.75*1.263\\right)+ \\left(3.5-0.75*0.512\\right)+ \\left(3.5-0.75*-0.143\\right)+ \\left(3.5-0.75*-0.464\\right)+ \\left(3.5-0.75*-0.016\\right)+ \\left(3.5-0.75*-0.835\\right)+ \\left(3.5-0.75*0.611\\right)+ \\left(3.5-0.75*0\\right)+ \\left(3.5-0.75*-0.117\\right)+ \\left(3.5-0.75*-1.645\\right)+ \\left(3.5-0.75*-1.929\\right)+ \\left(3.5-0.75*-0.026\\right)+ \\left(3.5-0.75*-1.121\\right)+ \\left(3.5-0.75*0.61\\right)+ \\left(3.5-0.75*-0.619\\right)+ \\left(3.5-0.75*0.806\\right)+ \\left(3.5-0.75*-0.123\\right)+ \\left(3.5-0.75*-1.617\\right)+ \\left(3.5-0.75*-0.683\\right)+ \\left(3.5-0.75*0.431\\right)+ \\left(3.5-0.75*2.705\\right)+ \\left(3.5-0.75*0.726\\right)+ \\left(3.5-0.75*-0.483\\right)+ \\left(3.5-0.75*2.135\\right)+ \\left(3.5-0.75*-0.399\\right)+ \\left(3.5-0.75*-0.087\\right)+ \\left(3.5-0.75*-1.004\\right)+ \\left(3.5-0.75*0.18\\right)+ \\left(3.5-0.75*0.229\\right)+ \\left(3.5-0.75*0.671\\right)+ \\left(3.5-0.75*0.234\\right)+ \\left(3.5-0.75*0.874\\right)+ \\left(3.5-0.75*-0.275\\right)+ \\left(3.5-0.75*-0.812\\right)+ \\left(3.5-0.75*0.363\\right)+ \\left(3.5-0.75*-0.549\\right)+ \\left(3.5-0.75*0.32\\right)+ \\left(3.5-0.75*0.667\\right)+ \\left(3.5-0.75*0.44\\right)+ \\left(3.5-0.75*-0.492\\right)+ \\left(3.5-0.75*0.879\\right)+ \\left(3.5-0.75*3.122\\right)+ \\left(3.5-0.75*-0.82\\right)+ \\left(3.5-0.75*-0.65\\right)+ \\left(3.5-0.75*-0.4\\right)+ \\left(3.5-0.75*-0.144\\right)+ \\left(3.5-0.75*1.132\\right)+ \\left(3.5-0.75*0.505\\right)+ \\left(3.5-0.75*0.452\\right)+ \\left(3.5-0.75*0.615\\right)+ \\left(3.5-0.75*-0.94\\right)+ \\left(3.5-0.75*-2.144\\right)+ \\left(3.5-0.75*-1.2\\right)+ \\left(3.5-0.75*-2.893\\right)+ \\left(3.5-0.75*-0.19\\right)+ \\left(3.5-0.75*0.433\\right)+ \\left(3.5-0.75*2.023\\right)+ \\left(3.5-0.75*0.046\\right)+ \\left(3.5-0.75*0.602\\right)+ \\left(3.5-0.75*-0.862\\right)+ \\left(3.5-0.75*-0.687\\right)+ \\left(3.5-0.75*0.907\\right)+ \\left(3.5-0.75*-0.966\\right)+ \\left(3.5-0.75*-1.694\\right)+ \\left(3.5-0.75*1.28\\right)+ \\left(3.5-0.75*1.178\\right)+ \\left(3.5-0.75*-1.077\\right)+ \\left(3.5-0.75*-0.433\\right)+ \\left(3.5-0.75*-0.274\\right)+ \\left(3.5-0.75*-0.725\\right)+ \\left(3.5-0.75*0.735\\right)+ \\left(3.5-0.75*-0.067\\right)+ \\left(3.5-0.75*0.176\\right)+ \\left(3.5-0.75*1.653\\right)+ \\left(3.5-0.75*0.212\\right)+ \\left(3.5-0.75*2.976\\right)+ \\left(3.5-0.75*-0.523\\right)+ \\left(3.5-0.75*-1.426\\right)+ \\left(3.5-0.75*0.673\\right)+ \\left(3.5-0.75*-1.079\\right)+ \\left(3.5-0.75*0.99\\right)+ \\left(3.5-0.75*0.628\\right)+ \\left(3.5-0.75*0.188\\right)+ \\left(3.5-0.75*0.992\\right)+ \\left(3.5-0.75*0.467\\right)+ \\left(3.5-0.75*-0.251\\right)+ \\left(3.5-0.75*1.403\\right)+ \\left(3.5-0.75*0.667\\right)+ \\left(3.5-0.75*1.23\\right)+ \\left(3.5-0.75*1.342\\right)+ \\left(3.5-0.75*1.713\\right)+ \\left(3.5-0.75*0.182\\right)+ \\left(3.5-0.75*0.758\\right)+ \\left(3.5-0.75*0.035\\right)+ \\left(3.5-0.75*0.932\\right)+ \\left(3.5-0.75*0.702\\right)+ \\left(3.5-0.75*0.436\\right)+ \\left(3.5-0.75*-1.355\\right)+ \\left(3.5-0.75*-1.318\\right)+ \\left(3.5-0.75*-0.109\\right)+ \\left(3.5-0.75*0.437\\right)+ \\left(3.5-0.75*-0.842\\right)+ \\left(3.5-0.75*0.977\\right)+ \\left(3.5-0.75*-1.503\\right)+ \\left(3.5-0.75*-0.253\\right)+ \\left(3.5-0.75*-1.166\\right)+ \\left(3.5-0.75*-0.274\\right)+ \\left(3.5-0.75*-1.083\\right)+ \\left(3.5-0.75*0.086\\right)+ \\left(3.5-0.75*0.807\\right)+ \\left(3.5-0.75*-0.068\\right)+ \\left(3.5-0.75*0.682\\right)+ \\left(3.5-0.75*0.26\\right)+ \\left(3.5-0.75*1.225\\right)+ \\left(3.5-0.75*1.82\\right)+ \\left(3.5-0.75*-1.444\\right)+ \\left(3.5-0.75*-0.579\\right)+ \\left(3.5-0.75*-0.945\\right)+ \\left(3.5-0.75*-0.743\\right)+ \\left(3.5-0.75*-0.423\\right)+ \\left(3.5-0.75*-0.086\\right)+ \\left(3.5-0.75*-0.105\\right)+ \\left(3.5-0.75*0.385\\right)+ \\left(3.5-0.75*0.733\\right)+ \\left(3.5-0.75*-1.131\\right)+ \\left(3.5-0.75*3.334\\right)+ \\left(3.5-0.75*-0.254\\right)+ \\left(3.5-0.75*0.304\\right)+ \\left(3.5-0.75*1.234\\right)+ \\left(3.5-0.75*1.144\\right)+ \\left(3.5-0.75*0.558\\right)+ \\left(3.5-0.75*-0.675\\right)+ \\left(3.5-0.75*-1.729\\right)+ \\left(3.5-0.75*-1.504\\right)+ \\left(3.5-0.75*-1.951\\right)+ \\left(3.5-0.75*0.203\\right)+ \\left(3.5-0.75*-0.154\\right)+ \\left(3.5-0.75*-0.545\\right)+ \\left(3.5-0.75*-0.913\\right)+ \\left(3.5-0.75*-1.11\\right)$  "
    ),

    h2("Server"),
    uiOutput("eqSrv")
)

# Define the server code
server <- function(input, output) {
    output$eqSrv<- renderUI({
        # something arbitrary and long
        withMathJax(
            "$$ f\\left( \\alpha, \\beta_1 | x_i\\right) =  \\left(3.5-0.75*-1.414\\right)+ \\left(3.5-0.75*0.189\\right)+ \\left(3.5-0.75*0.026\\right)+ \\left(3.5-0.75*-0.779\\right)+ \\left(3.5-0.75*0.683\\right)+ \\left(3.5-0.75*-0.503\\right)+ \\left(3.5-0.75*-1.18\\right)+ \\left(3.5-0.75*-1.736\\right)+ \\left(3.5-0.75*-1.497\\right)+ \\left(3.5-0.75*-1.12\\right)+ \\left(3.5-0.75*1.263\\right)+ \\left(3.5-0.75*0.512\\right)+ \\left(3.5-0.75*-0.143\\right)+ \\left(3.5-0.75*-0.464\\right)+ \\left(3.5-0.75*-0.016\\right)+ \\left(3.5-0.75*-0.835\\right)+ \\left(3.5-0.75*0.611\\right)+ \\left(3.5-0.75*0\\right)+ \\left(3.5-0.75*-0.117\\right)+ \\left(3.5-0.75*-1.645\\right)+ \\left(3.5-0.75*-1.929\\right)+ \\left(3.5-0.75*-0.026\\right)+ \\left(3.5-0.75*-1.121\\right)+ \\left(3.5-0.75*0.61\\right)+ \\left(3.5-0.75*-0.619\\right)+ \\left(3.5-0.75*0.806\\right)+ \\left(3.5-0.75*-0.123\\right)+ \\left(3.5-0.75*-1.617\\right)+ \\left(3.5-0.75*-0.683\\right)+ \\left(3.5-0.75*0.431\\right)+ \\left(3.5-0.75*2.705\\right)+ \\left(3.5-0.75*0.726\\right)+ \\left(3.5-0.75*-0.483\\right)+ \\left(3.5-0.75*2.135\\right)+ \\left(3.5-0.75*-0.399\\right)+ \\left(3.5-0.75*-0.087\\right)+ \\left(3.5-0.75*-1.004\\right)+ \\left(3.5-0.75*0.18\\right)+ \\left(3.5-0.75*0.229\\right)+ \\left(3.5-0.75*0.671\\right)+ \\left(3.5-0.75*0.234\\right)+ \\left(3.5-0.75*0.874\\right)+ \\left(3.5-0.75*-0.275\\right)+ \\left(3.5-0.75*-0.812\\right)+ \\left(3.5-0.75*0.363\\right)+ \\left(3.5-0.75*-0.549\\right)+ \\left(3.5-0.75*0.32\\right)+ \\left(3.5-0.75*0.667\\right)+ \\left(3.5-0.75*0.44\\right)+ \\left(3.5-0.75*-0.492\\right)+ \\left(3.5-0.75*0.879\\right)+ \\left(3.5-0.75*3.122\\right)+ \\left(3.5-0.75*-0.82\\right)+ \\left(3.5-0.75*-0.65\\right)+ \\left(3.5-0.75*-0.4\\right)+ \\left(3.5-0.75*-0.144\\right)+ \\left(3.5-0.75*1.132\\right)+ \\left(3.5-0.75*0.505\\right)+ \\left(3.5-0.75*0.452\\right)+ \\left(3.5-0.75*0.615\\right)+ \\left(3.5-0.75*-0.94\\right)+ \\left(3.5-0.75*-2.144\\right)+ \\left(3.5-0.75*-1.2\\right)+ \\left(3.5-0.75*-2.893\\right)+ \\left(3.5-0.75*-0.19\\right)+ \\left(3.5-0.75*0.433\\right)+ \\left(3.5-0.75*2.023\\right)+ \\left(3.5-0.75*0.046\\right)+ \\left(3.5-0.75*0.602\\right)+ \\left(3.5-0.75*-0.862\\right)+ \\left(3.5-0.75*-0.687\\right)+ \\left(3.5-0.75*0.907\\right)+ \\left(3.5-0.75*-0.966\\right)+ \\left(3.5-0.75*-1.694\\right)+ \\left(3.5-0.75*1.28\\right)+ \\left(3.5-0.75*1.178\\right)+ \\left(3.5-0.75*-1.077\\right)+ \\left(3.5-0.75*-0.433\\right)+ \\left(3.5-0.75*-0.274\\right)+ \\left(3.5-0.75*-0.725\\right)+ \\left(3.5-0.75*0.735\\right)+ \\left(3.5-0.75*-0.067\\right)+ \\left(3.5-0.75*0.176\\right)+ \\left(3.5-0.75*1.653\\right)+ \\left(3.5-0.75*0.212\\right)+ \\left(3.5-0.75*2.976\\right)+ \\left(3.5-0.75*-0.523\\right)+ \\left(3.5-0.75*-1.426\\right)+ \\left(3.5-0.75*0.673\\right)+ \\left(3.5-0.75*-1.079\\right)+ \\left(3.5-0.75*0.99\\right)+ \\left(3.5-0.75*0.628\\right)+ \\left(3.5-0.75*0.188\\right)+ \\left(3.5-0.75*0.992\\right)+ \\left(3.5-0.75*0.467\\right)+ \\left(3.5-0.75*-0.251\\right)+ \\left(3.5-0.75*1.403\\right)+ \\left(3.5-0.75*0.667\\right)+ \\left(3.5-0.75*1.23\\right)+ \\left(3.5-0.75*1.342\\right)+ \\left(3.5-0.75*1.713\\right)+ \\left(3.5-0.75*0.182\\right)+ \\left(3.5-0.75*0.758\\right)+ \\left(3.5-0.75*0.035\\right)+ \\left(3.5-0.75*0.932\\right)+ \\left(3.5-0.75*0.702\\right)+ \\left(3.5-0.75*0.436\\right)+ \\left(3.5-0.75*-1.355\\right)+ \\left(3.5-0.75*-1.318\\right)+ \\left(3.5-0.75*-0.109\\right)+ \\left(3.5-0.75*0.437\\right)+ \\left(3.5-0.75*-0.842\\right)+ \\left(3.5-0.75*0.977\\right)+ \\left(3.5-0.75*-1.503\\right)+ \\left(3.5-0.75*-0.253\\right)+ \\left(3.5-0.75*-1.166\\right)+ \\left(3.5-0.75*-0.274\\right)+ \\left(3.5-0.75*-1.083\\right)+ \\left(3.5-0.75*0.086\\right)+ \\left(3.5-0.75*0.807\\right)+ \\left(3.5-0.75*-0.068\\right)+ \\left(3.5-0.75*0.682\\right)+ \\left(3.5-0.75*0.26\\right)+ \\left(3.5-0.75*1.225\\right)+ \\left(3.5-0.75*1.82\\right)+ \\left(3.5-0.75*-1.444\\right)+ \\left(3.5-0.75*-0.579\\right)+ \\left(3.5-0.75*-0.945\\right)+ \\left(3.5-0.75*-0.743\\right)+ \\left(3.5-0.75*-0.423\\right)+ \\left(3.5-0.75*-0.086\\right)+ \\left(3.5-0.75*-0.105\\right)+ \\left(3.5-0.75*0.385\\right)+ \\left(3.5-0.75*0.733\\right)+ \\left(3.5-0.75*-1.131\\right)+ \\left(3.5-0.75*3.334\\right)+ \\left(3.5-0.75*-0.254\\right)+ \\left(3.5-0.75*0.304\\right)+ \\left(3.5-0.75*1.234\\right)+ \\left(3.5-0.75*1.144\\right)+ \\left(3.5-0.75*0.558\\right)+ \\left(3.5-0.75*-0.675\\right)+ \\left(3.5-0.75*-1.729\\right)+ \\left(3.5-0.75*-1.504\\right)+ \\left(3.5-0.75*-1.951\\right)+ \\left(3.5-0.75*0.203\\right)+ \\left(3.5-0.75*-0.154\\right)+ \\left(3.5-0.75*-0.545\\right)+ \\left(3.5-0.75*-0.913\\right)+ \\left(3.5-0.75*-1.11\\right) $$"
        )

    })
}

# Return a Shiny app object
shinyApp(ui = ui, server = server)

Body:
The MathJax config works if you put it in tags$head:

  tags$head(tags$script(type = "text/x-mathjax-config",
                        'MathJax.Hub.Config({
  "HTML-CSS": { linebreaks: { automatic: true } },
         SVG: { linebreaks: { automatic: true } }
});')),


问:
Background thread executed event after foreground thread exited?
I was going through Microsoft docs for ThreadPool and they explained that ThreadPool threads are background threads which do not keep the application running if all foreground threads have terminated.

Here is the code snippet:

```<code>public static void Main()
{
    ThreadPool.QueueUserWorkItem(ThreadProc);
    Console.WriteLine("From main foreground thread");
    //Thread.Sleep(1000);

    Console.WriteLine("Exiting from main");
}

static void ThreadProc(object stateInfo) {
    Console.WriteLine("From the thread pool");
}
</code>```

With Thread.Sleep(1000) uncommented it is sure that the background thread will complete before the main foreground thread exits. But when we comment the sleep part then also I get an output of sort:

```<code>From main foreground thread
Exiting from main
From the thread pool
</code>```

It means that the background thread is still executed even when the main foreground thread has exited. Why so?

答:
The end of the Main method doesn't mean the "foreground" thread has exited.  Even if it has, it doesn't mean your process has terminated.

Normally, a process stops when all threads that run in the process (including the ones from the thread-pool, which have queued work) terminate.  However, if you exit a process using ExitProcess.   The CLR works in a slighly more complicated way (see here), which does quite some clean-up before really existing the application.

As a result, before all working threads get killed, there is pretty some time when work can get done.

Body:
I was going through Microsoft docs for ThreadPool and they explained that ThreadPool threads are background threads which do not keep the application running if all foreground threads have terminated.

Here is the code snippet:

public static void Main()
{
    ThreadPool.QueueUserWorkItem(ThreadProc);
    Console.WriteLine("From main foreground thread");
    //Thread.Sleep(1000);

    Console.WriteLine("Exiting from main");
}

static void ThreadProc(object stateInfo) {
    Console.WriteLine("From the thread pool");
}

With Thread.Sleep(1000) uncommented it is sure that the background thread will complete before the main foreground thread exits. But when we comment the sleep part then also I get an output of sort:

From main foreground thread
Exiting from main
From the thread pool

It means that the background thread is still executed even when the main foreground thread has exited. Why so?


问:
How to read in .json file in python?
I want to read in only "text" part of the json file below. That is: HAPPY NEW YEAR!
....Senator Schumer, more than a year longer than any other Administration in history. These are people who have been approved by committees and all others, yet Schumer continues to hold them back from serving their Country! Very Unfair!

then train the words in my RNN model, what should I do to get text and delete the others?

json file:

```<code>[{"source": "Twitter for iPhone", "id_str": "1079888205351145472", "text": "HAPPY NEW YEAR! ", "created_at": "Mon Dec 31 23:53:06 +0000 2018", "retweet_count": 33548, "in reply to user id str": null, "favorite_count": 136012, "is_retweet": false},
 {"source": "Twitter for iPhone", "id_str": "1079830268708556800", "text": "....Senator Schumer, more than a year longer than any other Administration in history. These are people who have been approved by committees and all others, yet Schumer continues to hold them back from serving their Country! Very Unfair!", "created_at": "Mon Dec 31 20:02:52 +0000 2018", "retweet_count": 17456, "in reply to user id str": "25073877", "favorite_count": 65069, "is_retweet": false}]
</code>```

答:
You can use a list comprehension:

```<code>[element['text'] for element in data]
</code>```

You can also use map in conjunction with operator.itemgetter:

```<code>from operator import itemgetter

list(map(itemgetter('text'), data))
</code>```

Title: How to read in .json file in python?

Body:
I want to read in only "text" part of the json file below. That is: HAPPY NEW YEAR!
....Senator Schumer, more than a year longer than any other Administration in history. These are people who have been approved by committees and all others, yet Schumer continues to hold them back from serving their Country! Very Unfair!

then train the words in my RNN model, what should I do to get text and delete the others?

json file:

[{"source": "Twitter for iPhone", "id_str": "1079888205351145472", "text": "HAPPY NEW YEAR! ", "created_at": "Mon Dec 31 23:53:06 +0000 2018", "retweet_count": 33548, "in reply to user id str": null, "favorite_count": 136012, "is_retweet": false},
 {"source": "Twitter for iPhone", "id_str": "1079830268708556800", "text": "....Senator Schumer, more than a year longer than any other Administration in history. These are people who have been approved by committees and all others, yet Schumer continues to hold them back from serving their Country! Very Unfair!", "created_at": "Mon Dec 31 20:02:52 +0000 2018", "retweet_count": 17456, "in reply to user id str": "25073877", "favorite_count": 65069, "is_retweet": false}]

Body:
You can use a list comprehension:

[element['text'] for element in data]

You can also use map in conjunction with operator.itemgetter:

from operator import itemgetter

list(map(itemgetter('text'), data))


问:
Store byte contents in S3
I need to save binary (byte[]) contents (PDF file) to S3.

I don't want to have a hard copy existing in HDD, pdf is being generated in the fly and then it needs to be sent to S3.

Java AWS SDK AmazonS3.putObject() requires File type in method signature, how can I pass my binary contents directly without saving it to hard drive?

答:
The SDK offers method that take InputStream and ObjectMetadata instead of File. For example there is putObject(String bucketName, String key, InputStream input, ObjectMetadata metadata).

Use one of the provided methods and supply ByteArrayInputStream if you don't want to create files.

Title: Store byte contents in S3


问:
make highlight with pdfIum pdfSearchManager
I need to programmatically search pdf with pdfSearchManager and highlight the text. The code can make the search but with no highlight.
Plese see my code and correct me.</p>

```<code>PdfSearchManager a = new PdfSearchManager(pdfRenderer1);
a.Reset();
a.MatchWholeWord = true;
a.HighlightAllMatches = true;
MessageBox.Show(a.Search(textBox1.Text).ToString());
</code>```

答:
As we can see on GitHub (if that is the right PdfSearchManager you're using)

Search() is a boolean so its only return true or false so it won't show you any text with .ToString()

Search() :

```<code>/// <summary>
/// Searches for the specified text.
/// </summary>
/// <param name="text">The text to search.</param>
/// <returns>Whether any matches were found.</returns>
</code>```

It returns: Whether any matches were found

and not : Matches that were found

If you're trying to highlight the matches and not display them as I thought at the beginning then you should try using a.UpdateHighlights() ( I never used PdfSearchManager before but it might work)

Body:
I need to programmatically search pdf with pdfSearchManager and highlight the text. The code can make the search but with no highlight.
Plese see my code and correct me.

PdfSearchManager a = new PdfSearchManager(pdfRenderer1);
a.Reset();
a.MatchWholeWord = true;
a.HighlightAllMatches = true;
MessageBox.Show(a.Search(textBox1.Text).ToString());

Body:
As we can see on GitHub (if that is the right PdfSearchManager you're using)

Search() is a boolean so its only return true or false so it won't show you any text with .ToString()

Search() :

/// <summary>
/// Searches for the specified text.
/// </summary>
/// <param name="text">The text to search.</param>
/// <returns>Whether any matches were found.</returns>

It returns: Whether any matches were found

and not : Matches that were found

If you're trying to highlight the matches and not display them as I thought at the beginning then you should try using a.UpdateHighlights() ( I never used PdfSearchManager before but it might work)


问:
Highchart: Bubble heading is not showing if two bubbles intersect or comes near one another in Bubble chart
In Highcharts Bubblechart if i two bubbles comes near one another or intersect one another, the name on top of one bubble is not displaying.

Is there a way to display both the bubble names.

In this the notice the two bubbles in top right enter code herehttp://jsfiddle.net/htb38096/

答:
You can enable the allowOverlap property for data labels:

```<code>plotOptions: {
    series: {
        dataLabels: {
            allowOverlap: true,
            ...
        }
    }
}
</code>```

Live demo: http://jsfiddle.net/BlackLabel/k23xLjmn/

API Reference: https://api.highcharts.com/highcharts/series.bubble.dataLabels.enabled

Body:
You can enable the allowOverlap property for data labels:

plotOptions: {
    series: {
        dataLabels: {
            allowOverlap: true,
            ...
        }
    }
}

Live demo: http://jsfiddle.net/BlackLabel/k23xLjmn/

API Reference: https://api.highcharts.com/highcharts/series.bubble.dataLabels.enabled


问:
Why can't I get my Red Ball to Stop on the Blue Box using robot.getPixelColor?
Title. GUI looks like the following: Ball Puzzle GUI

The code below is for my Timer Task responsible for controlling the downwards movement of the ball, called by:

timer.scheduleAtFixedRate(moveDown, 0, 20);

Whenever an arrow key is pressed, the ball is supposed to continuously move in that direction until it encounters a square. I know I'm using .cancel() right now but I intend to fix that with a temporary pause of the TimerTask.

While not adding anything to the X or Y values, the ball never stops. (I should mention when it reaches the bottom it is looped back to the top)
The outputted colors seem to change when not change X or Y values. For instance, at (0,360) the first time around, the outputted color is (208,208,208) while the next time around at (0,360) the outputted color is (240,240,240).

When adding what I thought would stop it right on the edge of the box, Y + 51, it still doesn't stop. The only color detected is (208,208,208) which is a grey color.

If I added both Y + 51 and X + 25, the ball still never stops, and only grey is outputted. Note I've changed the velocity to 1 and it makes no difference.

Now, by some stroke of luck I've found that if I add 80 to the Y and 25 to the X, it will stop right on the edge of the box.

I also found that if I add 25 to the Y and 25 to the X for the TimerTask responsible for moving the ball upwards (velocity is negative) the ball will stop 1 pixel away from the edge of the box.

```<code>   public void run() {
      try {
            Robot robot = new Robot();
            int y = ball.positionY + 80;
            int x = ball.positionX + 25;

            System.out.println(ball.positionX);
            System.out.println(ball.positionY);

            color = robot.getPixelColor(x, y);

            System.out.println("Red   = " + color.getRed());
            System.out.println("Green = " + color.getGreen());
            System.out.println("Blue  = " + color.getBlue());

        } catch (AWTException e) {

            e.printStackTrace();

        }

        if((color.getRed() == 0) && (color.getGreen() == 0) && (color.getBlue() == 255)){

            moveDown.cancel();
            moving = false;

        }

        else{

        ball.positionY += 5;

        if (ball.positionY > 670) {

            ball.positionY = 0;

        }
        }

        ball.repaint();
    }
</code>```

Does anyone know what the heck is actually going on? I haven't been able to figure out the right/left directions yet as there doesn't seem to be a pattern.

答:
Robot is not a reliable way to detect your squares.  Double buffering may mean that your pixels are not actually showing.

Since your own code is drawing the squares, keep the coordinates of those squares in a private field, and use them to check for collision instead of checking pixel colors:

```<code>private final Collection<Rectangle> squares = new ArrayList<>();

// ...

    if (squares.stream().anyMatch(sq -> sq.contains(x, y))) {
        moveDown.cancel();
        moving = false;
    } else {
        ball.positionY += 5;
        if (ball.positionY > 670) {
            ball.positionY = 0;
        }
    }
</code>```

Also be aware that Swing is not safe for use by multiple threads.  You should be using javax.swing.Timer instead of java.util.Timer, since it properly executes its tasks in the AWT event dispatch thread.

Body:
Title. GUI looks like the following: Ball Puzzle GUI

The code below is for my Timer Task responsible for controlling the downwards movement of the ball, called by:

timer.scheduleAtFixedRate(moveDown, 0, 20);

Whenever an arrow key is pressed, the ball is supposed to continuously move in that direction until it encounters a square. I know I'm using .cancel() right now but I intend to fix that with a temporary pause of the TimerTask.

While not adding anything to the X or Y values, the ball never stops. (I should mention when it reaches the bottom it is looped back to the top)
The outputted colors seem to change when not change X or Y values. For instance, at (0,360) the first time around, the outputted color is (208,208,208) while the next time around at (0,360) the outputted color is (240,240,240).

When adding what I thought would stop it right on the edge of the box, Y + 51, it still doesn't stop. The only color detected is (208,208,208) which is a grey color.

If I added both Y + 51 and X + 25, the ball still never stops, and only grey is outputted. Note I've changed the velocity to 1 and it makes no difference.

Now, by some stroke of luck I've found that if I add 80 to the Y and 25 to the X, it will stop right on the edge of the box.

I also found that if I add 25 to the Y and 25 to the X for the TimerTask responsible for moving the ball upwards (velocity is negative) the ball will stop 1 pixel away from the edge of the box.

   public void run() {
      try {
            Robot robot = new Robot();
            int y = ball.positionY + 80;
            int x = ball.positionX + 25;

            System.out.println(ball.positionX);
            System.out.println(ball.positionY);

            color = robot.getPixelColor(x, y);

            System.out.println("Red   = " + color.getRed());
            System.out.println("Green = " + color.getGreen());
            System.out.println("Blue  = " + color.getBlue());

        } catch (AWTException e) {

            e.printStackTrace();

        }

        if((color.getRed() == 0) && (color.getGreen() == 0) && (color.getBlue() == 255)){

            moveDown.cancel();
            moving = false;

        }

        else{

        ball.positionY += 5;

        if (ball.positionY > 670) {

            ball.positionY = 0;

        }
        }

        ball.repaint();
    }

Does anyone know what the heck is actually going on? I haven't been able to figure out the right/left directions yet as there doesn't seem to be a pattern.

Body:
Robot is not a reliable way to detect your squares.  Double buffering may mean that your pixels are not actually showing.

Since your own code is drawing the squares, keep the coordinates of those squares in a private field, and use them to check for collision instead of checking pixel colors:

private final Collection<Rectangle> squares = new ArrayList<>();

// ...

    if (squares.stream().anyMatch(sq -> sq.contains(x, y))) {
        moveDown.cancel();
        moving = false;
    } else {
        ball.positionY += 5;
        if (ball.positionY > 670) {
            ball.positionY = 0;
        }
    }

Also be aware that Swing is not safe for use by multiple threads.  You should be using javax.swing.Timer instead of java.util.Timer, since it properly executes its tasks in the AWT event dispatch thread.


问:
How to get Excel to recognise dates without a manual find and replace "/" for "/"?
How do I get excel to recognize timestamps as timestamps rather than strings?

If I do a find and replace on "/" with "/" it fixes it on most files:

```<code>Cells.Replace What:="/", Replacement:="/", LookAt:=xlPart, SearchOrder :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
</code>```

I have a chunk of code that checks if it's still in the wrong format by converting to "Comma" format and checking if the cell contains any "/" characters, then a break line that triggers in that instance to alert me that I need to manually do the find and replace on this file. If I stop the Macro when it fails and run it manually (Crtl+h, Enter), then it works and I can restart the macro to finish the standardisation. I need a way of automating this.

I have >2000 .csv files of a similar but not identical format. Each one contains ~350 variables, each with it's own timestamp and data column. I've written some code that formats it into a usable format. The original csv has the timestamps in "DD/MM/YYYY hh:mm:ss" format as is my computer and Excel default.

Excel seemingly randomly decides it can't recognise around a quarter of the files timestamps and instead interprets them as strings. This can be corrected by clicking into the cell and then clicking out of the cell, then excel recognises it as a timestamp. I need the timestamps recognised so that I can interpolate values into a standard sampling frequency as Excel can't interpolate using values it interprets as strings.

There are often well over 100k timestamps per file, so doing this manually isn't an option.

I've tried using SendKeys. The problem with that seems to be that it opens the find and replace dialogue for the VBA script editor, not for the excel sheet.
I've tried shifting focus before by calling:

```<code>Windows(windowname).Activate
ActiveWorkbook.Application.SendKeys("^h")
</code>```

I've also tried:

```<code>Windows(windowname).Application.SendKeys("^h")
</code>```

Which both result in the find and replace being called on the VBA script editor.

I have no shortcut to start the Macro.

I've tried Matlab, but it can't deal with the header on the file or the columns populated with text. I'd like to retain all the data.

I have used the Macro recorder to record me doing the find and replace which results in:

```<code>Sub Fixer()
'
' Fixer Macro
'

'
    Selection.Replace What:="/", Replacement:="/", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
End Sub
</code>```

But this doesn't work when you run it on the same file.

I expect it to convert the string "DD/MM/YYYY hh:mm:ss" format into a date-time format that I can then convert into decimal format which I can then use for interpolating the values into a usable format. Instead I get no error message, and nothing happens.

An example line of date timestamps from the raw CSV is:
"31/03/2019 14:55:57,1.0000000149,31/03/2019 14:55:57,14.6,31/03/2019 14:55:57,57.86,31/03/2019 14:55:57,0.175000000000068"

So the timestamp "31/03/2019 14:55:57" I want converting into "43555.62218750000"

I could use a script to deconstruct the string, calculate the decimal equivalent, and overwrite the cell, but this will take a prohibitively long time.

答:
First import the date/time field into Excel as Text.  In my demo case I use column A.  Then run:

```<code>Sub TextToValue()
    Dim Kolumn As String, N As Long, i As Long
    Dim d As Double, dt As Date, tm As Date
    Dim v As Variant

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

    For i = 1 To N
        v = Cells(i, Kolumn).Text
        If InStr(1, v, "/") > 0 Then
            arr = Split(v, " ")
            brr = Split(arr(0), "/")
            dt = DateSerial(brr(2), brr(1), brr(0))
            tm = TimeValue(arr(1))
            d = CDbl(dt + tm)
            Cells(i, Kolumn).Clear
            Cells(i, Kolumn).Value = d
        End If
    Next i
End Sub
</code>```

Before:

And after:

Body:
How do I get excel to recognize timestamps as timestamps rather than strings?

If I do a find and replace on "/" with "/" it fixes it on most files:

Cells.Replace What:="/", Replacement:="/", LookAt:=xlPart, SearchOrder :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

I have a chunk of code that checks if it's still in the wrong format by converting to "Comma" format and checking if the cell contains any "/" characters, then a break line that triggers in that instance to alert me that I need to manually do the find and replace on this file. If I stop the Macro when it fails and run it manually (Crtl+h, Enter), then it works and I can restart the macro to finish the standardisation. I need a way of automating this.

I have >2000 .csv files of a similar but not identical format. Each one contains ~350 variables, each with it's own timestamp and data column. I've written some code that formats it into a usable format. The original csv has the timestamps in "DD/MM/YYYY hh:mm:ss" format as is my computer and Excel default.

Excel seemingly randomly decides it can't recognise around a quarter of the files timestamps and instead interprets them as strings. This can be corrected by clicking into the cell and then clicking out of the cell, then excel recognises it as a timestamp. I need the timestamps recognised so that I can interpolate values into a standard sampling frequency as Excel can't interpolate using values it interprets as strings.

There are often well over 100k timestamps per file, so doing this manually isn't an option.

I've tried using SendKeys. The problem with that seems to be that it opens the find and replace dialogue for the VBA script editor, not for the excel sheet.
I've tried shifting focus before by calling:

Windows(windowname).Activate
ActiveWorkbook.Application.SendKeys("^h")

I've also tried:

Windows(windowname).Application.SendKeys("^h")

Which both result in the find and replace being called on the VBA script editor.

I have no shortcut to start the Macro.

I've tried Matlab, but it can't deal with the header on the file or the columns populated with text. I'd like to retain all the data.

I have used the Macro recorder to record me doing the find and replace which results in:

Sub Fixer()
'
' Fixer Macro
'

'
    Selection.Replace What:="/", Replacement:="/", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
End Sub

But this doesn't work when you run it on the same file.

I expect it to convert the string "DD/MM/YYYY hh:mm:ss" format into a date-time format that I can then convert into decimal format which I can then use for interpolating the values into a usable format. Instead I get no error message, and nothing happens.

An example line of date timestamps from the raw CSV is:
"31/03/2019 14:55:57,1.0000000149,31/03/2019 14:55:57,14.6,31/03/2019 14:55:57,57.86,31/03/2019 14:55:57,0.175000000000068"

So the timestamp "31/03/2019 14:55:57" I want converting into "43555.62218750000"

I could use a script to deconstruct the string, calculate the decimal equivalent, and overwrite the cell, but this will take a prohibitively long time.

Body:
First import the date/time field into Excel as Text.  In my demo case I use column A.  Then run:

Sub TextToValue()
    Dim Kolumn As String, N As Long, i As Long
    Dim d As Double, dt As Date, tm As Date
    Dim v As Variant

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

    For i = 1 To N
        v = Cells(i, Kolumn).Text
        If InStr(1, v, "/") > 0 Then
            arr = Split(v, " ")
            brr = Split(arr(0), "/")
            dt = DateSerial(brr(2), brr(1), brr(0))
            tm = TimeValue(arr(1))
            d = CDbl(dt + tm)
            Cells(i, Kolumn).Clear
            Cells(i, Kolumn).Value = d
        End If
    Next i
End Sub

Before:

And after:


答:
You can try:</p>

```<code>text_data = ""

with open(file_path) as file_obj:
    json_data = json.load(file_obj)
    for single_json in json_data:
        print(single_json["text"])
        text_data += single_json["text"]

print(text_data)
</code>```

Title: How to read in .json file in python?

Body:
You can try:

text_data = ""

with open(file_path) as file_obj:
    json_data = json.load(file_obj)
    for single_json in json_data:
        print(single_json["text"])
        text_data += single_json["text"]

print(text_data)


问:
I am learning django, when I use Pinax Likes, there is a 405 error
Django 2.2.1

When I use Pinax Likes(https://github.com/pinax/pinax-likes), there is a 405 error.

The steps are as follows:

pip3 install pinax-likes

Added 'pinax.likes', to the project's settings.py file,
then added:

```<code>PINAX_LIKES_LIKABLE_MODELS = {
    "app.Post": {}
}
</code>```

Added

```<code>re_path(r'^likes/', include(('pinax.likes.urls', 'pinax_likes'), namespace='pinax_likes')),
</code>```

to the project's urls.py file,

Download the files in the https://github.com/pinax/pinax-templates/tree/master/pinax/templates/templates/pinax/likes,

put these html files in  /home/www/venv/templates/pinax/likes/,

Added

```<code>{% load pinax_likes_tags %}
{% likes_widget request.user post %}
</code>```

to the post.html file,

python manage.py makemigrations app && python manage.py migrate && python manage.py runserver 0.0.0.0:8000

Open http://127.0.0.1:8000/post/13/, like icon appears, when clicked the icon(url: http://127.0.0.1:8000/like/14:13/), show the following:
HTTP ERROR 405,

The console displays the following information:

Method Not Allowed (GET): /likes/like/14:13/
  Method Not Allowed: /likes/like/14:13/
  [29/May/2019 10:00:00] "GET /likes/like/14:13/ HTTP/1.1" 405 0

Then i added  in base.html,

After clicked the icon, the console displays the following information:

Forbidden (CSRF token missing or incorrect.): /likes/like/14:13/
  [29/May/2019 10:01:31] "POST /likes/like/14:13/ HTTP/1.1" 403 2513

What are the steps wrong? Thank you!

答:
I don't see how pinax-likes widget can actually work with the current code. It's broken. I see you opened an issue, if someone is still actively maintaining it they might fix it. Or you could fix it and propose a pull request.

There are two problems with the {% likes_widget %}:

It cannot work without ajax, because it's just an  link, i.e. it will send a GET request to your view. But the view expects a POST request, which is logical, since liking makes a change to the database and so it should be a POST. Therefore, without ajax, the view throws a 405 error.

It uses eldarion-ajax to make the ajax POST request, but since again it's just a a.click event, it won't post any data, i.e. it doesn't post the CSRF token. The view won't allow the missing token (it doesn't have the @csrf_exempt decorator), so it throws a 403 error.

Now the only way I see around this is to write your own HTML and/or ajax and not use the likes_widget.

You can wrap the like button in a form and replace the like button with a <button> that submits the form (instead of an  tag). This way, you can include the {% csrf_token %} tag in the form and the post will work. This will refresh the page.

You can write your own ajax call to handle a click on the like button and post to the same view and include the csrftoken in the data posted.

This is fairly simple to implement, you can use the existing pinax like view, so it's only a change in your HTML template.

Body:
Django 2.2.1

When I use Pinax Likes(https://github.com/pinax/pinax-likes), there is a 405 error.

The steps are as follows:

pip3 install pinax-likes

Added 'pinax.likes', to the project's settings.py file,
then added:

PINAX_LIKES_LIKABLE_MODELS = {
    "app.Post": {}
}

Added

re_path(r'^likes/', include(('pinax.likes.urls', 'pinax_likes'), namespace='pinax_likes')),

to the project's urls.py file,

Download the files in the https://github.com/pinax/pinax-templates/tree/master/pinax/templates/templates/pinax/likes,

put these html files in  /home/www/venv/templates/pinax/likes/,

Added

{% load pinax_likes_tags %}
{% likes_widget request.user post %}

to the post.html file,

python manage.py makemigrations app && python manage.py migrate && python manage.py runserver 0.0.0.0:8000

Open http://127.0.0.1:8000/post/13/, like icon appears, when clicked the icon(url: http://127.0.0.1:8000/like/14:13/), show the following:
HTTP ERROR 405,

The console displays the following information:

Method Not Allowed (GET): /likes/like/14:13/
  Method Not Allowed: /likes/like/14:13/
  [29/May/2019 10:00:00] "GET /likes/like/14:13/ HTTP/1.1" 405 0

Then i added  in base.html,

After clicked the icon, the console displays the following information:

Forbidden (CSRF token missing or incorrect.): /likes/like/14:13/
  [29/May/2019 10:01:31] "POST /likes/like/14:13/ HTTP/1.1" 403 2513

What are the steps wrong? Thank you!

Body:
I don't see how pinax-likes widget can actually work with the current code. It's broken. I see you opened an issue, if someone is still actively maintaining it they might fix it. Or you could fix it and propose a pull request.

There are two problems with the {% likes_widget %}:

It cannot work without ajax, because it's just an  link, i.e. it will send a GET request to your view. But the view expects a POST request, which is logical, since liking makes a change to the database and so it should be a POST. Therefore, without ajax, the view throws a 405 error.

It uses eldarion-ajax to make the ajax POST request, but since again it's just a a.click event, it won't post any data, i.e. it doesn't post the CSRF token. The view won't allow the missing token (it doesn't have the @csrf_exempt decorator), so it throws a 403 error.

Now the only way I see around this is to write your own HTML and/or ajax and not use the likes_widget.

You can wrap the like button in a form and replace the like button with a <button> that submits the form (instead of an <a> tag). This way, you can include the {% csrf_token %} tag in the form and the post will work. This will refresh the page.

You can write your own ajax call to handle a click on the like button and post to the same view and include the csrftoken in the data posted.

This is fairly simple to implement, you can use the existing pinax like view, so it's only a change in your HTML template.


问:
Optional parameters on delegates doesn't work properly
Why this piece of code does not compile? </p>

```<code>delegate int xxx(bool x = true);

xxx test = f;

int f()
{
   return 4;
}
</code>```

答: What will happen test(false)? It will corrupt the stack, because signatures must match.

Body:
Why this piece of code does not compile?

delegate int xxx(bool x = true);

xxx test = f;

int f()
{
   return 4;
}


问:
ValueError("unknown url type: %r" % self.full_url)
I try to pass a string to a website which check if there is any curse words.

I tried passing url to urlopen() and just like to document of urllib.request.urlopen(url, data), I tried passing the query string to data as well but couldn't achieve the result

```<code>import urllib.request, urllib.parse

def read_text():
    quotes = open(r"D:\Courses\Udacity Full Stack Web Developer\Python
Section\movie-quotes.txt")
    content_of_files = quotes.read()
    char_count = len(content_of_files)
    print(content_of_files)
    print(f"Total character count is {char_count}")
    quotes.close()
    check_profanity(content_of_files)

def check_profanity(text_to_check):
    url = "www.wdylike.appspot.com/?q="
    connection = urllib.request.urlopen(url+text_to_check)
    print(connection.read())
    connection.close()

read_text()
</code>```

```<code>ValueError("unknown url type: %r" % self.full_url)
ValueError: unknown url type: 'www.wdylike.appspot.com/?q=Houston, we have a problem. (Apollo 13)\n\nMama always said, life is like a box of chocolates. You never know what you are going to get. (Forrest Gump)\n\nYou cant handle the truth. (A Few Good Men)\n\nI believe everything and I believe nothing. (A Shot in the Dark)'
</code>```

答:
Add the protocol part to the url.

Replace:

```<code>url = "www.wdylike.appspot.com/?q="
</code>```

with:

```<code>url = "http://www.wdylike.appspot.com/?q="
</code>```

Body:
I try to pass a string to a website which check if there is any curse words.

I tried passing url to urlopen() and just like to document of urllib.request.urlopen(url, data), I tried passing the query string to data as well but couldn't achieve the result

import urllib.request, urllib.parse

def read_text():
    quotes = open(r"D:\Courses\Udacity Full Stack Web Developer\Python
Section\movie-quotes.txt")
    content_of_files = quotes.read()
    char_count = len(content_of_files)
    print(content_of_files)
    print(f"Total character count is {char_count}")
    quotes.close()
    check_profanity(content_of_files)

def check_profanity(text_to_check):
    url = "www.wdylike.appspot.com/?q="
    connection = urllib.request.urlopen(url+text_to_check)
    print(connection.read())
    connection.close()

read_text()

ValueError("unknown url type: %r" % self.full_url)
ValueError: unknown url type: 'www.wdylike.appspot.com/?q=Houston, we have a problem. (Apollo 13)\n\nMama always said, life is like a box of chocolates. You never know what you are going to get. (Forrest Gump)\n\nYou cant handle the truth. (A Few Good Men)\n\nI believe everything and I believe nothing. (A Shot in the Dark)'

Body:
Add the protocol part to the url.

Replace:

url = "www.wdylike.appspot.com/?q="

with:

url = "http://www.wdylike.appspot.com/?q="


问:
Highlighting missing unique pairs when compared to master list - Excel
On Sheet 1, I have a master list of data, with corresponding attributes. Some data has more than one attribute, some has only one, and there is a possibility of blanks. Attributes can be repeated when assigned to a different name.

I've posted some example data below, so we can all talk about the same cells/names etc.

On Sheet 2, there is much more freeform data input/analysis going on. Users are able to select a 'Name' from a dropdown menu using Data Validation, and are then able to select from the available attributes corresponding to that name, again using a dropdown menu. Names and attributes can appear in any order on Sheet 2.

It is important that all pairings are considered in the second worksheet.

Is it possible to use conditional formatting to highlight the 'Name' field (on Sheet 2) until at least one row exists with all possible pairings? In the example below, you can see that we have forgotten to put any info relating to the fact that Sally is Happy, and consequently 'Sally' has been highlighted to draw attention to the fact that there is some missing information.

Current thoughts:
I already have a list of the attributes that match the corresponding name- this is what drives the dropdown menu on Sheet 2, and is generated in a background sheet when a name is picked on Sheet 2. I can count the non-blank cells in this range to find out the total number of pairs that are required.

I would like to then count the number of non-duplicate attributes that are on rows that have the same Name as the current row, and compare this value.

I'm expecting this to get into the realms of array formulae, but may be wrong...
I'm also expecting array formulae to not work directly with conditional formatting, and to require the use of a 'helper column' to drive the formatting. Let me know if this is incorrect?

Something along the lines of the below (formatted as pseudo-code for readability, but this should be read as a high level description, not actual code)

```<code>{Count the 1s in the array(AND(
'Check if it's a name match'
If($D$1:$D$10=[$ACurrent],[set flag to 1],[set flag to 0])
'Check if it's a unique value'
[somehow check array values set at 1 to see if there is a duplicate value in column E, and then set the array value to zero if so])
}
</code>```

Does this approach make sense, and how would I go about constructing this actual formula?

I don't mind using VBA if required, but would prefer to avoid it if possible (company policy, sorry).

答:
Well, you want to highlight value Sally, Happy if that value does not appear in Sheet2, so you just need a COUNTIFS

COUNTIFS function

I've got this:

I've used a Conditional Formatin Rule based on my own formula. The formula I've used is:

```<code>=IF($B2="";IF(COUNTIFS($F$2:$F$12;$A2;$G$2:$G$12;"")=0;TRUE;FALSE);IF(COUNTIFS($F$2:$F$12;$A2;$G$2:$G$12;$B2)=0;TRUE;FALSE))
</code>```

There are 2 COUNTIFS, because blank values are possible:

IF(COUNTIFS($F$2:$F$12;$A2;$G$2:$G$12;"")=0;TRUE;FALSE) will count how many rows got same name and non blank attributes in Sheet2. If 0, then it will return True and highlight row.

IF(COUNTIFS($F$2:$F$12;$A2;$G$2:$G$12;$B2)=0;TRUE;FALSE) will count how many rows got same name and blank attributes. If 0, then it will return True and will highlight

With the initial IF you can blanks or non blanks attributes, just to make sure you count all posibilities of values.

I've uploaded a sample to mi Gdrive in case you want to download and get the formulas autotranslated opening at your PC.

https://drive.google.com/open?id=1Im4LoaK4EIvINBj7tfyEcYk9juWUp7zr

Hope you can adapt this to your needs.

Body:
On Sheet 1, I have a master list of data, with corresponding attributes. Some data has more than one attribute, some has only one, and there is a possibility of blanks. Attributes can be repeated when assigned to a different name.

I've posted some example data below, so we can all talk about the same cells/names etc.

On Sheet 2, there is much more freeform data input/analysis going on. Users are able to select a 'Name' from a dropdown menu using Data Validation, and are then able to select from the available attributes corresponding to that name, again using a dropdown menu. Names and attributes can appear in any order on Sheet 2.

It is important that all pairings are considered in the second worksheet.

Is it possible to use conditional formatting to highlight the 'Name' field (on Sheet 2) until at least one row exists with all possible pairings? In the example below, you can see that we have forgotten to put any info relating to the fact that Sally is Happy, and consequently 'Sally' has been highlighted to draw attention to the fact that there is some missing information.

Current thoughts:
I already have a list of the attributes that match the corresponding name- this is what drives the dropdown menu on Sheet 2, and is generated in a background sheet when a name is picked on Sheet 2. I can count the non-blank cells in this range to find out the total number of pairs that are required.

I would like to then count the number of non-duplicate attributes that are on rows that have the same Name as the current row, and compare this value.

I'm expecting this to get into the realms of array formulae, but may be wrong...
I'm also expecting array formulae to not work directly with conditional formatting, and to require the use of a 'helper column' to drive the formatting. Let me know if this is incorrect?

Something along the lines of the below (formatted as pseudo-code for readability, but this should be read as a high level description, not actual code)

{Count the 1s in the array(AND(
'Check if it's a name match'
If($D$1:$D$10=[$ACurrent],[set flag to 1],[set flag to 0])
'Check if it's a unique value'
[somehow check array values set at 1 to see if there is a duplicate value in column E, and then set the array value to zero if so])
}

Does this approach make sense, and how would I go about constructing this actual formula?

I don't mind using VBA if required, but would prefer to avoid it if possible (company policy, sorry).

Body:
Well, you want to highlight value Sally, Happy if that value does not appear in Sheet2, so you just need a COUNTIFS

COUNTIFS function

I've got this:

I've used a Conditional Formatin Rule based on my own formula. The formula I've used is:

=IF($B2="";IF(COUNTIFS($F$2:$F$12;$A2;$G$2:$G$12;"")=0;TRUE;FALSE);IF(COUNTIFS($F$2:$F$12;$A2;$G$2:$G$12;$B2)=0;TRUE;FALSE))

There are 2 COUNTIFS, because blank values are possible:

IF(COUNTIFS($F$2:$F$12;$A2;$G$2:$G$12;"")=0;TRUE;FALSE) will count how many rows got same name and non blank attributes in Sheet2. If 0, then it will return True and highlight row.

IF(COUNTIFS($F$2:$F$12;$A2;$G$2:$G$12;$B2)=0;TRUE;FALSE) will count how many rows got same name and blank attributes. If 0, then it will return True and will highlight

With the initial IF you can blanks or non blanks attributes, just to make sure you count all posibilities of values.

I've uploaded a sample to mi Gdrive in case you want to download and get the formulas autotranslated opening at your PC.

https://drive.google.com/open?id=1Im4LoaK4EIvINBj7tfyEcYk9juWUp7zr

Hope you can adapt this to your needs.


问:
Access multiple devices in Docker container without --privileged flag
I have an arbitrary number of devices (/dev/abc0, /dev/abc1, ...) to use within a Docker container. If I pass them individually to the container with docker run --device /dev/abc0 --device /dev/abc1 they are accessible. The complication here is that, as far as I know, there is no way to pass all devices /dev/abc* into the container.

If I instead mount /dev with docker run -v /dev I need the --privileged flag. I have not found a specific capability to use with --cap-add which enables the devices without --privileged. Can this be done?

答:
A little more experimentation yielded a potential solution. Provided the /dev/abc* devices have major device number 123, access to these devices (only) can be provided with:

```<code>docker run -v /dev --device-cgroup-rule='c 123:* rmw'
</code>```

Body:
A little more experimentation yielded a potential solution. Provided the /dev/abc* devices have major device number 123, access to these devices (only) can be provided with:

docker run -v /dev --device-cgroup-rule='c 123:* rmw'


问:
Flask: Unknown error although 200 response code is returned
I have created a simple Flask RESTful API with a single function used to service GET requests and which expects several URL parameters:

import logging

from flask import Flask
from flask_restful import Api, Resource
from webargs import fields
from webargs.flaskparser import abort, parser, use_args

# initialize the Flask application and API
app = Flask(__name__)
api = Api(app)

# ------------------------------------------------------------------------------
# set up a basic, global logger object which will write to the console
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s %(levelname)s  %(message)s",
                    datefmt="%Y-%m-%d  %H:%M:%S")
_logger = logging.getLogger(__name__)

# ------------------------------------------------------------------------------
class Abc(Resource):

    abc_args = {"rtsp": fields.Url(required=True),
                "start": fields.Integer(required=True),
                "duration": fields.Integer(required=True),
                "bucket": fields.String(required=True),
                "prefix": fields.String(missing="")}

    @use_args(abc_args)
    def get(self, args) -> (str, int):

        _logger.info("Recording video clip with the following parameters:\n"
                     f"\tRTSP URL: {args['rtsp']}"
                     f"\tStart seconds: {args['start']}"
                     f"\tDuration seconds: {args['duration']}"
                     f"\tS3 bucket: {args['bucket']}"
                     f"\tS3 key prefix: {args['prefix']}")

        return "OK", 200

# ------------------------------------------------------------------------------
# This error handler is necessary for usage with Flask-RESTful
@parser.error_handler
def handle_request_parsing_error(err, req, schema, error_status_code, error_headers):
    """
    webargs error handler that uses Flask-RESTful's abort function to return
    a JSON error response to the client.
    """
    abort(error_status_code, errors=err.messages)

# ------------------------------------------------------------------------------
if __name__ == '__main__':
    api.add_resource(Abc, "/abc", endpoint="abc")
    app.run(debug=True)
```

<p>When I send a GET request to the endpoint with or without parameters I get none of the expected behavior -- if good parameters are included in the GET request then I expect to see a log message in the console, and if none of the required parameters are present then I expect to get some sort of error as a result. Instead, I get what appear to be 200 response codes in the console and simply the phrase "Unknown Error" in the main browser window.</p>

<p>For example, if I enter the following URL without the expected parameters into my Chrome browser's address bar: <code>http://127.0.0.1:5000/abc</code>
I then see this in the console:</p>

```2019-05-28  17:42:14 INFO  127.0.0.1 - - [28/May/2019 17:42:14] "GET /abc HTTP/1.1" 200 -
```

<p>My assumption is that the above should throw an error of some sort indicating the missing URL parameters.</p>

<p>If I enter the following URL with the expected parameters into my Chrome browser's address bar: <code>http://127.0.0.1:5000/abc?rtsp=rtsp://user:passwd@171.25.14.15:554&start=1559076593&duration=10&bucket=testbucket&prefix=test.</code>
I then see this in the console:</p>

```2019-05-28  17:45:31 INFO  127.0.0.1 - - [28/May/2019 17:45:31] "GET /abc?rtsp=rtsp://user:passwd@171.25.14.15:554&start=1559076593&duration=10&bucket=testbucket&prefix=test. HTTP/1.1" 200 -
```

<p>My assumption is that the above should cause the logger to print the information message to the console as is defined in the <code>Abc.get</code> function.</p>

<p>If I use <code>curl</code> at the command line then I get the following result:</p>

<pre class="lang-sh prettyprint-override"><code>$ curl "http://127.0.0.1:5000/abc?rtsp=rtsp://user:passwd@171.25.14.15:554&start=1559076593&duration=10&bucket=testbucket&prefix=test."
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>None Unknown Error</title>
<h1>Unknown Error</h1>
<p></p>
</code>```

Whi is this going amiss, and how I can achieve the expected behavior? (My intention is to use this approach to pass arguments to a more realistic GET handler that will launch a video recording function when the request is received, the above has been simplified as much as possible for clarity.)

I am using Flask 1.0.3, Flask-Restful 0.3.6, and Webargs 5.3.1 in an Anaconda environment (Python 3.7) on Ubuntu 18.04.

答:
I have managed to get the expected behavior using a simpler code that does not rely upon flask_restful. See below:

import logging

from flask import Flask, request

# initialize the Flask application
app = Flask(__name__)

# ------------------------------------------------------------------------------
# set up a basic, global logger object which will write to the console
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s %(levelname)s  %(message)s",
                    datefmt="%Y-%m-%d  %H:%M:%S")
_logger = logging.getLogger(__name__)

# ------------------------------------------------------------------------------
@app.route('/clip', methods=['GET'])
def record_and_store_clip():

    message = "Recording video clip with the following parameters:\n" + \
              f"\tRTSP URL: {request.args.get('rtsp')}\n" + \
              f"\tStart seconds: {request.args.get('start')}\n" + \
              f"\tDuration seconds: {request.args.get('duration')}\n" + \
              f"\tS3 bucket: {request.args.get('bucket')}\n" + \
              f"\tS3 key prefix: {request.args.get('prefix')}\n"

    _logger.info(message)

    return message

# ------------------------------------------------------------------------------
if __name__ == '__main__':
    app.run(debug=True)
```

Body:
I have created a simple Flask RESTful API with a single function used to service GET requests and which expects several URL parameters:

import logging

from flask import Flask
from flask_restful import Api, Resource
from webargs import fields
from webargs.flaskparser import abort, parser, use_args

# initialize the Flask application and API
app = Flask(__name__)
api = Api(app)

# ------------------------------------------------------------------------------
# set up a basic, global logger object which will write to the console
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s %(levelname)s  %(message)s",
                    datefmt="%Y-%m-%d  %H:%M:%S")
_logger = logging.getLogger(__name__)

# ------------------------------------------------------------------------------
class Abc(Resource):

    abc_args = {"rtsp": fields.Url(required=True),
                "start": fields.Integer(required=True),
                "duration": fields.Integer(required=True),
                "bucket": fields.String(required=True),
                "prefix": fields.String(missing="")}

    @use_args(abc_args)
    def get(self, args) -> (str, int):

        _logger.info("Recording video clip with the following parameters:\n"
                     f"\tRTSP URL: {args['rtsp']}"
                     f"\tStart seconds: {args['start']}"
                     f"\tDuration seconds: {args['duration']}"
                     f"\tS3 bucket: {args['bucket']}"
                     f"\tS3 key prefix: {args['prefix']}")

        return "OK", 200

# ------------------------------------------------------------------------------
# This error handler is necessary for usage with Flask-RESTful
@parser.error_handler
def handle_request_parsing_error(err, req, schema, error_status_code, error_headers):
    """
    webargs error handler that uses Flask-RESTful's abort function to return
    a JSON error response to the client.
    """
    abort(error_status_code, errors=err.messages)

# ------------------------------------------------------------------------------
if __name__ == '__main__':
    api.add_resource(Abc, "/abc", endpoint="abc")
    app.run(debug=True)

When I send a GET request to the endpoint with or without parameters I get none of the expected behavior -- if good parameters are included in the GET request then I expect to see a log message in the console, and if none of the required parameters are present then I expect to get some sort of error as a result. Instead, I get what appear to be 200 response codes in the console and simply the phrase "Unknown Error" in the main browser window.

For example, if I enter the following URL without the expected parameters into my Chrome browser's address bar: http://127.0.0.1:5000/abc
I then see this in the console:

2019-05-28  17:42:14 INFO  127.0.0.1 - - [28/May/2019 17:42:14] "GET /abc HTTP/1.1" 200 -

My assumption is that the above should throw an error of some sort indicating the missing URL parameters.

If I enter the following URL with the expected parameters into my Chrome browser's address bar: http://127.0.0.1:5000/abc?rtsp=rtsp://user:passwd@171.25.14.15:554&start=1559076593&duration=10&bucket=testbucket&prefix=test.
I then see this in the console:

2019-05-28  17:45:31 INFO  127.0.0.1 - - [28/May/2019 17:45:31] "GET /abc?rtsp=rtsp://user:passwd@171.25.14.15:554&start=1559076593&duration=10&bucket=testbucket&prefix=test. HTTP/1.1" 200 -

My assumption is that the above should cause the logger to print the information message to the console as is defined in the Abc.get function.

If I use curl at the command line then I get the following result:

$ curl "http://127.0.0.1:5000/abc?rtsp=rtsp://user:passwd@171.25.14.15:554&start=1559076593&duration=10&bucket=testbucket&prefix=test."
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>None Unknown Error</title>

Unknown Error

Whi is this going amiss, and how I can achieve the expected behavior? (My intention is to use this approach to pass arguments to a more realistic GET handler that will launch a video recording function when the request is received, the above has been simplified as much as possible for clarity.)

I am using Flask 1.0.3, Flask-Restful 0.3.6, and Webargs 5.3.1 in an Anaconda environment (Python 3.7) on Ubuntu 18.04.


问:
Why comparing Strings in MySQL query is not working
I am running a very simple SELECT query in MySQL and it's not working.

```<code>SELECT string_name FROM table_name;
</code>```

This is giving me required output. Like

This is string one.

This is string two.

This is string three.

and so on...

But if I am running a query like this

```<code>SELECT * FROM table_name WHERE string_name='This is string one'
</code>```

It's not giving any output. I even tried TRIM function.

```<code>SELECT * FROM table_name WHERE TRIM(string_name)=TRIM('This is string one')
</code>```

But it's still not giving any output.

Please suggest what I am missing here. Is it because of some formatting or am I doing any silly mistake. By the way, Strings are saved as VARCHAR in the database.

答:
First of all, I must acknowledge the points made by @Uueerdo were actually the the main cause of this issue. Even I was somewhat sure that there are some hidden characters in the string causing all the issue but I was not sure how to find and fix that offending character.

Also, the approach suggested by @Uueerdo to check and replace the offending character using the ASCII code seems quite legit but as he himself mentioned that this process will take lot's of time and one have to manually check every string for that one offending character and then replace it.

Luckily after spending couple of hours on it, I came up with a much faster approach to fix the issue. For that, first of all I would like to share my use case.

My first query was for selecting all the strings from a database and printing the result on page.

```<code>$result = mysqli_query($conn, "SELECT * from table_name");
while($row = mysqli_fetch_array($result)){
   $string_var = $row["string_name"];
   echo $string_var;
   echo "<br>";
}
</code>```

The above code was working as expected and printing all the string_name from the table. Now, if I wanted to use the variable $string_var for another SELECT query in the same table, it was giving me 0 results.

```<code>$result = mysqli_query($conn, "SELECT * FROM table_name");
while($row = mysqli_fetch_array($result)){
    $string_var = $row["string_name"];
    echo "String Name : ".$string_var."";
    $sec_result = ($conn, "SELECT * FROM table_name WHERE string_var='$string_name'");
    if(mysqli_num_rows($sec_result) > 0){
        echo "Has Results";
    } else {
        echo "No Results";
    }
}
</code>```

In this snippet, my second query $sec_result was always giving me No Results as output.

What I simply did to fix this issue.

```<code>$result = mysqli_query($conn, "SELECT * FROM table_name";
while ($row = mysqli_fetch_array($result)){
    $string_var = $row["string_name"];
    $row_id = $row["id"];

    $update_row = mysqli_query($conn, "UPDATE table_name SET string_name='$string_var' WHERE id=$row_id");
}
</code>```

This step updated all the strings from the table without any hidden/problem causing character.

I am not generalising this approach and I am not sure if this will work in every use case but it helped me fix my issue in less than a minute.

I request @Uueerdo and others with better understanding on this to post a more generic approach so that it can help others because I think many people who can't find a right approach in such conditions, end up using LIKE in place of = but that completely changes the core idea of the query.

Body:
I am running a very simple SELECT query in MySQL and it's not working.

SELECT string_name FROM table_name;

This is giving me required output. Like

This is string one.

This is string two.

This is string three.

and so on...

But if I am running a query like this

SELECT * FROM table_name WHERE string_name='This is string one'

It's not giving any output. I even tried TRIM function.

SELECT * FROM table_name WHERE TRIM(string_name)=TRIM('This is string one')

But it's still not giving any output.

Please suggest what I am missing here. Is it because of some formatting or am I doing any silly mistake. By the way, Strings are saved as VARCHAR in the database.

Body:
First of all, I must acknowledge the points made by @Uueerdo were actually the the main cause of this issue. Even I was somewhat sure that there are some hidden characters in the string causing all the issue but I was not sure how to find and fix that offending character.

Also, the approach suggested by @Uueerdo to check and replace the offending character using the ASCII code seems quite legit but as he himself mentioned that this process will take lot's of time and one have to manually check every string for that one offending character and then replace it.

Luckily after spending couple of hours on it, I came up with a much faster approach to fix the issue. For that, first of all I would like to share my use case.

My first query was for selecting all the strings from a database and printing the result on page.

$result = mysqli_query($conn, "SELECT * from table_name");
while($row = mysqli_fetch_array($result)){
   $string_var = $row["string_name"];
   echo $string_var;
   echo "<br>";
}

The above code was working as expected and printing all the string_name from the table. Now, if I wanted to use the variable $string_var for another SELECT query in the same table, it was giving me 0 results.

$result = mysqli_query($conn, "SELECT * FROM table_name");
while($row = mysqli_fetch_array($result)){
    $string_var = $row["string_name"];
    echo "String Name : ".$string_var."";
    $sec_result = ($conn, "SELECT * FROM table_name WHERE string_var='$string_name'");
    if(mysqli_num_rows($sec_result) > 0){
        echo "Has Results";
    } else {
        echo "No Results";
    }
}

In this snippet, my second query $sec_result was always giving me No Results as output.

What I simply did to fix this issue.

$result = mysqli_query($conn, "SELECT * FROM table_name";
while ($row = mysqli_fetch_array($result)){
    $string_var = $row["string_name"];
    $row_id = $row["id"];

    $update_row = mysqli_query($conn, "UPDATE table_name SET string_name='$string_var' WHERE id=$row_id");
}

This step updated all the strings from the table without any hidden/problem causing character.

I am not generalising this approach and I am not sure if this will work in every use case but it helped me fix my issue in less than a minute.

I request @Uueerdo and others with better understanding on this to post a more generic approach so that it can help others because I think many people who can't find a right approach in such conditions, end up using LIKE in place of = but that completely changes the core idea of the query.


问:
How to mock a function called in Class "A" and defined in class "B"?
I'm writing a unit test code to test a function "a" defined in Class A that calls a function "b" defined in Class "B". How can I make "a" calls the b-mocking function?

#-------------------------------------------------
class B :

    def __init__(self):
        print('hello B')

    def b(self):
        return False

#------------------------------------------------
class A :
    def __init__(self):
        print('hello A')

    def a(self,a,b):
        ret = B().b()
        if ret == True:
            return 0
        else :
            return a+b
#-----------------------------------------------
class TestA(unittest.TestCase):

    def setUp(self):
        pass

    def return_true(self):
        return True

    @patch('__main__.B')
    def test_a_in_A(self,mocked_B):
        mocked_B.b.return_value = True
        assert A().a(2,3) == 0

#---------------------------------------------
if __name__ == '__main__':
    unittest.main()

```

i expected output of assert A().a(2,3) == 0 to be test OK
but the actual output is AssertionError

Note: when I ran assert A().a(2,3) == 5, the test returns test OK which means that the mock is not working correctly.

答:
Okay, long version: Mocking is when you replace something with a simplified form. However, you can't mock something that was not used. It doesn't make any sense.

Let's look at your code here:

```<code>def a(self,a,b):
    ret = B().b()
    if ret == True:
        return 0
    else :
        return a+b
</code>```

You are constructing a new B() inside this function, so it doesn't have the return_value you set elsewhere in the test on mocked_B. The whole point of having a mock object is that you pass the mock in, and you get its predictable behavior. You can't mock an object that is entirely encapsulated inside the function being tested.

Here I have modified your code to take a (possibly mocked) B object. I renamed the integer arguments from a, b to x, y because it was too confusing. They have nothing to do with A or B.

Also you forgot some imports.

```<code>import unittest
from unittest.mock import patch

class B :
    def __init__(self):
        print('hello B')

    def b(self):
        return False

class A :
    def __init__(self):
        print('hello A')

    def a(self, x, y, b):
        if b.b():
            return 0
        else:
            return x + y

class TestA(unittest.TestCase):
    def setUp(self):
        pass

    def return_true(self):
        return True

    @patch('__main__.B')
    def test_a_in_A(self,mocked_B):
        mocked_B.b.return_value = True
        assert A().a(2,3, mocked_B) == 0

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

As requested, here is a revised version with less impact on existing code:

```<code>class A :
    def __init__(self, b=None):
        # this instance can use a member instance of B
        self.b = b if b else B()
        print('hello A')

    def a(self, x, y):
        if self.b.b() is True:
            return 0
        else:
            return x + y
</code>```

I changed the test to "self.b.b() is True" to avoid running into a MagicMock object with no return_value initialized nevertheless evaluating to true because ... it is an instance, and that's how bool(object) works.

Here you still have to pass in the mock instance which has the return_value set to what you want, so the test would be

```<code>assert A(mocked_B).a(2,3) == 0
</code>```

You have to have something to replace, if you want the mock object to replace something. It might help to look up "dependency injection" which is another name for the same basic idea.

Body:
I'm writing a unit test code to test a function "a" defined in Class A that calls a function "b" defined in Class "B". How can I make "a" calls the b-mocking function?

#-------------------------------------------------
class B :

    def __init__(self):
        print('hello B')

    def b(self):
        return False

#------------------------------------------------
class A :
    def __init__(self):
        print('hello A')

    def a(self,a,b):
        ret = B().b()
        if ret == True:
            return 0
        else :
            return a+b
#-----------------------------------------------
class TestA(unittest.TestCase):

    def setUp(self):
        pass

    def return_true(self):
        return True

    @patch('__main__.B')
    def test_a_in_A(self,mocked_B):
        mocked_B.b.return_value = True
        assert A().a(2,3) == 0

#---------------------------------------------
if __name__ == '__main__':
    unittest.main()

i expected output of assert A().a(2,3) == 0 to be test OK
but the actual output is AssertionError

Note: when I ran assert A().a(2,3) == 5, the test returns test OK which means that the mock is not working correctly.

Body:
Okay, long version: Mocking is when you replace something with a simplified form. However, you can't mock something that was not used. It doesn't make any sense.

Let's look at your code here:

def a(self,a,b):
    ret = B().b()
    if ret == True:
        return 0
    else :
        return a+b

You are constructing a new B() inside this function, so it doesn't have the return_value you set elsewhere in the test on mocked_B. The whole point of having a mock object is that you pass the mock in, and you get its predictable behavior. You can't mock an object that is entirely encapsulated inside the function being tested.

Here I have modified your code to take a (possibly mocked) B object. I renamed the integer arguments from a, b to x, y because it was too confusing. They have nothing to do with A or B.

Also you forgot some imports.

import unittest
from unittest.mock import patch

class B :
    def __init__(self):
        print('hello B')

    def b(self):
        return False

class A :
    def __init__(self):
        print('hello A')

    def a(self, x, y, b):
        if b.b():
            return 0
        else:
            return x + y

class TestA(unittest.TestCase):
    def setUp(self):
        pass

    def return_true(self):
        return True

    @patch('__main__.B')
    def test_a_in_A(self,mocked_B):
        mocked_B.b.return_value = True
        assert A().a(2,3, mocked_B) == 0

if __name__ == '__main__':
    unittest.main()

As requested, here is a revised version with less impact on existing code:

class A :
    def __init__(self, b=None):
        # this instance can use a member instance of B
        self.b = b if b else B()
        print('hello A')

    def a(self, x, y):
        if self.b.b() is True:
            return 0
        else:
            return x + y

I changed the test to "self.b.b() is True" to avoid running into a MagicMock object with no return_value initialized nevertheless evaluating to true because ... it is an instance, and that's how bool(object) works.

Here you still have to pass in the mock instance which has the return_value set to what you want, so the test would be

assert A(mocked_B).a(2,3) == 0

You have to have something to replace, if you want the mock object to replace something. It might help to look up "dependency injection" which is another name for the same basic idea.