问:
React.js - Value of checkbox not reflecting initial state
I'm rendering checkboxes with the following code:

```<code>export default class Day extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            startTime: this.props.startTime,
            endTime: this.props.endTime,
            available: this.props.available
        }
        console.log(this.state.available)
    }

    return (
        <div className='day'>
            <label className='name'>
                {day.name}
                <input
                    type='checkbox'
                    checked={this.state.available}
                    onChange={this.handleAvailableChange}
                    />
            </label>
            {this.state.available}

        </div>
    );
}
</code>```

This Day component is rendered from a parent component like so:

```<code>export default class Schedule extends React.Component {

    render () {
        const dayComponents = this.props.days.map( (day) =>
            <Day key={day.id}
                startTime={this.state[day.name].start}
                endTime={this.state[day.name].end}
                available={this.state[day.name].available}
                day={day}
                handleDayChange={(day, startOrEnd, time, available) => this.handleDayChange(day, startOrEnd, time, available) }
            />

        return (
            <div>
                {dayComponents}
            </div>
        );
    }
}
</code>```

... where this.props.days is an array of day objects that look like so:

```<code>#<Day id: 14, name: "Saturday">
</code>```

And a state that looks like so:

```<code>{"Sunday": {"start": 0, "end": 0, "available": true},
"Monday": {"start": 0, "end": 0, "available": true},
etc...}
</code>```

The value of my checkbox should be initialized based on the value of this.state.available, but every checkbox is checked when the component is rendered.

I'm looking at the value of this.state.available in two different places, and in both places, I get 5 trues and 2 falses.

Is there some aspect of the component life cycle that I'm missing here? Do I need to utilize something like getInitialState() (didn't change anything when I tried)?

Hoping this is something simple and stupid I overlooked since it seems like such basic functionality...

Edit:

I've removed state from the Day component and rendering the checkboxes as follows:

```<code><label className='name'>
    {day.name}
    <input
        type='checkbox'
        checked={this.props.available}
        onChange={this.handleAvailableChange}
        />
</label>
{this.props.available}
</code>```

However, this is still the output I get:

It is also worth noting that if I assign a static false to the value of checked, an unchecked checkbox is returned.

Edit 2 (Solution):

Turns out that when I was saving the schedule to my database (which is where I pull the available values from), I was saving the booleans to strings because the parameters in the AJAX request were getting automatically cast to a different data type.

So I was trying to set the value of checked to "false", which always returns true since it's an existent string.

答:
Since you are managing the state by the parent component, i will suggest you to not store the values again in child component, directly use this.props.keyName. You are passing a change function also, use that method to update the parent state value, once you update the parent state, updated values will get passed to child component automatically. On re-render it will reflect all the changes in ui also.

Check this working snippet:

let days = [
    {name:"Sunday"},
    {name:"Monday"},
    {name:"Tuesday"},
    {name:"Wednesday"},
    {name:"Thursday"},
    {name:"Friday"},
    {name:"Saturday"},
];

class Schedule extends React.Component {
    constructor(){
        super();
        this.state={
            "Sunday": {"start": 0, "end": 0, "available": true},
            "Monday": {"start": 0, "end": 0, "available": true},
            "Tuesday": {"start": 0, "end": 0, "available": true},
            "Wednesday": {"start": 0, "end": 0, "available": true},
            "Thursday": {"start": 0, "end": 0, "available": true},
            "Friday": {"start": 0, "end": 0, "available": false},
            "Saturday": {"start": 0, "end": 0, "available": false},
        }
    }

    handleDayChange(value, dayName){
       let obj = {...this.state[dayName]};
       obj.available = value;
       this.setState({[dayName]: obj});
    }

    render () {
        const dayComponents = this.props.days.map(day =>
            <Day
                key={day.name}
                startTime={this.state[day.name].start}
                endTime={this.state[day.name].end}
                available={this.state[day.name].available}
                name={day.name}
                handleDayChange={(value, dayName) => this.handleDayChange(value, dayName) }
            />
        )
        return (

                {dayComponents}

        );
    }
}

class Day extends React.Component {
    constructor(props){
        super(props)
        this.state = {
        }
        this.handleAvailableChange = this.handleAvailableChange.bind(this);
    }

    handleAvailableChange(e){
        this.props.handleDayChange(e.target.checked, this.props.name);
    }

    render(){
        let values = this.props;
        return (

                    {values.name}
                    <input
                        type='checkbox'
                        checked={values.available}
                        onChange={this.handleAvailableChange}
                    />

                {values.available + ""}

        );
    }
}

ReactDOM.render(<Schedule days={days}/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/></code>```

Body:
I'm rendering checkboxes with the following code:

export default class Day extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            startTime: this.props.startTime,
            endTime: this.props.endTime,
            available: this.props.available
        }
        console.log(this.state.available)
    }

    return (

                {day.name}
                <input
                    type='checkbox'
                    checked={this.state.available}
                    onChange={this.handleAvailableChange}
                    />

            {this.state.available}

    );
}

This Day component is rendered from a parent component like so:

export default class Schedule extends React.Component {

    render () {
        const dayComponents = this.props.days.map( (day) =>
            <Day key={day.id}
                startTime={this.state[day.name].start}
                endTime={this.state[day.name].end}
                available={this.state[day.name].available}
                day={day}
                handleDayChange={(day, startOrEnd, time, available) => this.handleDayChange(day, startOrEnd, time, available) }
            />

        return (

                {dayComponents}

        );
    }
}

... where this.props.days is an array of day objects that look like so:

#<Day id: 14, name: "Saturday">

And a state that looks like so:

{"Sunday": {"start": 0, "end": 0, "available": true},
"Monday": {"start": 0, "end": 0, "available": true},
etc...}

The value of my checkbox should be initialized based on the value of this.state.available, but every checkbox is checked when the component is rendered.

I'm looking at the value of this.state.available in two different places, and in both places, I get 5 trues and 2 falses.

Is there some aspect of the component life cycle that I'm missing here? Do I need to utilize something like getInitialState() (didn't change anything when I tried)?

Hoping this is something simple and stupid I overlooked since it seems like such basic functionality...

Edit:

I've removed state from the Day component and rendering the checkboxes as follows:

    {day.name}
    <input
        type='checkbox'
        checked={this.props.available}
        onChange={this.handleAvailableChange}
        />

{this.props.available}

However, this is still the output I get:

It is also worth noting that if I assign a static false to the value of checked, an unchecked checkbox is returned.

Edit 2 (Solution):

Turns out that when I was saving the schedule to my database (which is where I pull the available values from), I was saving the booleans to strings because the parameters in the AJAX request were getting automatically cast to a different data type.

So I was trying to set the value of checked to "false", which always returns true since it's an existent string.

Body:
Since you are managing the state by the parent component, i will suggest you to not store the values again in child component, directly use this.props.keyName. You are passing a change function also, use that method to update the parent state value, once you update the parent state, updated values will get passed to child component automatically. On re-render it will reflect all the changes in ui also.

Check this working snippet:

let days = [
    {name:"Sunday"},
    {name:"Monday"},
    {name:"Tuesday"},
    {name:"Wednesday"},
    {name:"Thursday"},
    {name:"Friday"},
    {name:"Saturday"},
];

class Schedule extends React.Component {
    constructor(){
        super();
        this.state={
            "Sunday": {"start": 0, "end": 0, "available": true},
            "Monday": {"start": 0, "end": 0, "available": true},
            "Tuesday": {"start": 0, "end": 0, "available": true},
            "Wednesday": {"start": 0, "end": 0, "available": true},
            "Thursday": {"start": 0, "end": 0, "available": true},
            "Friday": {"start": 0, "end": 0, "available": false},
            "Saturday": {"start": 0, "end": 0, "available": false},
        }
    }

    handleDayChange(value, dayName){
       let obj = {...this.state[dayName]};
       obj.available = value;
       this.setState({[dayName]: obj});
    }

    render () {
        const dayComponents = this.props.days.map(day =>
            <Day
                key={day.name}
                startTime={this.state[day.name].start}
                endTime={this.state[day.name].end}
                available={this.state[day.name].available}
                name={day.name}
                handleDayChange={(value, dayName) => this.handleDayChange(value, dayName) }
            />
        )
        return (
            <div>
                {dayComponents}
            </div>
        );
    }
}

class Day extends React.Component {
    constructor(props){
        super(props)
        this.state = {
        }
        this.handleAvailableChange = this.handleAvailableChange.bind(this);
    }

    handleAvailableChange(e){
        this.props.handleDayChange(e.target.checked, this.props.name);
    }

    render(){
        let values = this.props;
        return (
            <div className='day'>
                <label className='name'>
                    {values.name}
                    <input
                        type='checkbox'
                        checked={values.available}
                        onChange={this.handleAvailableChange}
                    />
                </label>
                {values.available + ""}
            </div>
        );
    }
}

ReactDOM.render(<Schedule days={days}/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>


来源: stackexchange

问:
NoClassDefFoundError after renaming a package
I am writing a simple application using Netbeans; on creating a new Java project I renamed the automatically created package from oldpackage to newpackage using Netbeans' rename function (ie using Refactor > Rename...)

When I run the program I get this exception:

```<code>    java.lang.NoClassDefFoundError: oldpackage/Main
Caused by: java.lang.ClassNotFoundException: oldpackage.Main
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: oldpackage.Main.  Program will exit.
Exception in thread "main" Java Result: 1
</code>```

I've done some Googling but couldn't find an obvious fix - can anyone help?

答: Change the package name applicationId in the gradle file. Clean and Reopen your Project

ContentLicense: CC BY-SA 3.0

Body:
I am writing a simple application using Netbeans; on creating a new Java project I renamed the automatically created package from oldpackage to newpackage using Netbeans' rename function (ie using Refactor > Rename...)

When I run the program I get this exception:

    java.lang.NoClassDefFoundError: oldpackage/Main
Caused by: java.lang.ClassNotFoundException: oldpackage.Main
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: oldpackage.Main.  Program will exit.
Exception in thread "main" Java Result: 1

I've done some Googling but couldn't find an obvious fix - can anyone help?


问:
Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition
This is the query I'm using:

```<code> DELETE TB1.*, TB2.*
   FROM TB1
        INNER JOIN TB2 ON TB1.PersonID = TB2.PersonID
  WHERE (TB1.PersonID)='2'
</code>```

It's working fine in MS Access but getting error (Incorrect syntax near ','.) in SQL Server Express 2005.

How to solve it? Please help.

答:
Try this query</p>

```<code>DELETE TB1, TB2 FROM TB1 INNER JOIN TB2
WHERE TB1.PersonID = TB2.PersonID and TB1.PersonID = '2'
</code>```

Body:
This is the query I'm using:

 DELETE TB1.*, TB2.*
   FROM TB1
        INNER JOIN TB2 ON TB1.PersonID = TB2.PersonID
  WHERE (TB1.PersonID)='2'

It's working fine in MS Access but getting error (Incorrect syntax near ','.) in SQL Server Express 2005.

How to solve it? Please help.

Body:
Try this query

DELETE TB1, TB2 FROM TB1 INNER JOIN TB2
WHERE TB1.PersonID = TB2.PersonID and TB1.PersonID = '2'


问:
Adding a slider to html
I want to add a slider as in input on a web page I am designing. I don't even know if it is called a slider.

答:
A "slider" is written like this but within <> tags:

```<code><input type="range" min="5" max="10" step="0.01">
</code>```

You can set step to 1 and set the minimum and maximum values however you want.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range

If you're looking for two sliders, you can build it out of two sliders like this:

```<code><input value="500" min="500" max="50000" step="500" type="range">
<input value="50000" min="500" max="50000" step="500" type="range">
</code>```

https://codepen.io/rendykstan/pen/VLqZGO

Title: Adding a slider to html

Body:
A "slider" is written like this but within <> tags:

<input type="range" min="5" max="10" step="0.01">

You can set step to 1 and set the minimum and maximum values however you want.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range

If you're looking for two sliders, you can build it out of two sliders like this:

<input value="500" min="500" max="50000" step="500" type="range">
<input value="50000" min="500" max="50000" step="500" type="range">

https://codepen.io/rendykstan/pen/VLqZGO


问:
How to create boxplot with large amount of continuous x-variables and continuous y-variables with R (not ggplot)
How to create boxplot with large amount of continuous x-variables and continuous y-variableswith R
don't use ggplot.
Just like the following figure, the x-axis and y-axis are all continuous numerical variable.
example boxplot</p>

答:
You can plot by boxplot() function. From this tutorial :

https://www.r-bloggers.com/box-plot-with-r-tutorial/

r-blogger is good for your start learning R. Good luck.


问:
cp --archive / -a in Ruby
Ruby have FileUtils with cp, cp_r, having options like verbose, noop etc. Is there any way to do cp -a in a clean way like that? I want to preserve attributes, especially dates.

答:
Try using it with the preserve option set:

```<code>FileUtils.cp_r(source, dest, preserve: true)
</code>```

Title: cp --archive / -a in Ruby

Body:
Try using it with the preserve option set:

FileUtils.cp_r(source, dest, preserve: true)


问:
Central Directory Entry not found (ZipException)
I am trying download zip file to SD card. I download it correctly, but when I open downloaded file (with ZipFile) I get this ZipException ("Central Directory Entry not found").

Internet-file is okay, SD-copy-file is okay (from PC opened and show files correctly), but for some reason don't work in Android.

Code for download:

```<code>BufferedInputStream stream = null;
try {
  stream = new BufferedInputStream(is, 8192);
}
....</p>

<p>try {
  ByteArrayBuffer baf = new ByteArrayBuffer(50);
  int current = 0;
  while ((current = stream.read()) != -1 )
    baf.append((byte) current);   </p>

<p>BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(path));
  fos.write(baf.toByteArray());
  fos.close();
}
...```

I supossed that the problem is in the ZIP file headers, which was not properly written, but I do not know for what reason. The source code ZipEntry class shows me this:

```<code>long sig = (hdrBuf[0] & 0xff) | ((hdrBuf[1] & 0xff) < <  8) |
           ((hdrBuf[2] & 0xff) < <  16) | ((hdrBuf[3] < <  24) & 0xffffffffL);
if (sig != CENSIG) {
     throw new ZipException("Central Directory Entry not found");
}
```

Thanks,

答:
Auto-answer: The problem was that HTTP request use Accept-Encoding: gzip.

The server returned an already compressed file and download it, decompress it, removing part of the header.

Unfortunately, 7zip opened correctly (probably, not check headers), but Android not open file (probably, check headers).

In short: Be careful, and check correctly file-encoding with some files.

ContentLicense: CC BY-SA 2.5

Body:
I am trying download zip file to SD card. I download it correctly, but when I open downloaded file (with ZipFile) I get this ZipException ("Central Directory Entry not found").

Internet-file is okay, SD-copy-file is okay (from PC opened and show files correctly), but for some reason don't work in Android.

Code for download:

BufferedInputStream stream = null;
try {
  stream = new BufferedInputStream(is, 8192);
}
....

try {
  ByteArrayBuffer baf = new ByteArrayBuffer(50);
  int current = 0;
  while ((current = stream.read()) != -1 )
    baf.append((byte) current);

BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(path));
  fos.write(baf.toByteArray());
  fos.close();
}
...

I supossed that the problem is in the ZIP file headers, which was not properly written, but I do not know for what reason. The source code ZipEntry class shows me this:

long sig = (hdrBuf[0] & 0xff) | ((hdrBuf[1] & 0xff) < <  8) |
           ((hdrBuf[2] & 0xff) < <  16) | ((hdrBuf[3] < <  24) & 0xffffffffL);
if (sig != CENSIG) {
     throw new ZipException("Central Directory Entry not found");
}

Thanks,


问:
Mono async exception handling
I'm just trying to figure out how exception handling works in reactor library.

Consider the following example:

```<code>public class FluxTest {

@Test
public void testIt() throws InterruptedException {
    Scheduler single = Schedulers.single();

    CountDownLatch latch = new CountDownLatch(1);

    Mono.just("hey")
            .subscribeOn(single)
            .doOnError(e -> System.out.println("ERROR1: " + e.getMessage()))
            .doOnTerminate((r, e) -> {
                if (e != null) System.out.println("ERROR3: " + e.getMessage());
                latch.countDown();
            })
            .subscribe(
                    it -> { throw new RuntimeException("Error for " + it); },
                    ex -> { System.out.println("ERROR2: " + ex.getMessage());}
                    );

    latch.await();
}

}
</code>```

Actually, I can't see any of error handling code block executes.
Test terminates without any message. Also, I tried to remove doOnError, doOnTerminate processors with no luck.

答:
And it's correct behavior in your case.
You're creating mono from single string "hey" that has no errors. If you try to debug you can see that doOnTerminate method gets called with e = null parameter and according to documentation it gets called in any case success or error.

To test some error handling you can do next thing:

```<code>public class FluxTest {
    @Test
    public void testIt() throws InterruptedException {
        Scheduler single = Schedulers.single();

        CountDownLatch latch = new CountDownLatch(1);

        Mono.just("hey")
                .map(this::mapWithException)
                .subscribeOn(single)
                .doOnError(e -> System.out.println("ERROR1: " + e.getMessage()))
                .doOnTerminate((r, e) -> {
                    if (e != null) System.out.println("ERROR3: " + e.getMessage());
                    latch.countDown();
                })
                .subscribe(
                        it -> { throw new RuntimeException("Error for " + it); },
                        ex -> { System.out.println("ERROR2: " + ex.getMessage());}
                        );

        latch.await();
    }

    private String mapWithException(String s) {
        throw new RuntimeException();
    }
}
</code>```

After running test with code above you should three lines in you console

```<code>ERROR1: null
ERROR3: null
ERROR2: null
</code>```

So first callback is onError when mono failed, second will be onTerminate because mono is terminated with error and the third one errorConsumer from subscribe method.

Title: Mono async exception handling

Body:
I'm just trying to figure out how exception handling works in reactor library.

Consider the following example:

public class FluxTest {

@Test
public void testIt() throws InterruptedException {
    Scheduler single = Schedulers.single();

    CountDownLatch latch = new CountDownLatch(1);

    Mono.just("hey")
            .subscribeOn(single)
            .doOnError(e -> System.out.println("ERROR1: " + e.getMessage()))
            .doOnTerminate((r, e) -> {
                if (e != null) System.out.println("ERROR3: " + e.getMessage());
                latch.countDown();
            })
            .subscribe(
                    it -> { throw new RuntimeException("Error for " + it); },
                    ex -> { System.out.println("ERROR2: " + ex.getMessage());}
                    );

    latch.await();
}

}

Actually, I can't see any of error handling code block executes.
Test terminates without any message. Also, I tried to remove doOnError, doOnTerminate processors with no luck.

Body:
And it's correct behavior in your case.
You're creating mono from single string "hey" that has no errors. If you try to debug you can see that doOnTerminate method gets called with e = null parameter and according to documentation it gets called in any case success or error.

To test some error handling you can do next thing:

public class FluxTest {
    @Test
    public void testIt() throws InterruptedException {
        Scheduler single = Schedulers.single();

        CountDownLatch latch = new CountDownLatch(1);

        Mono.just("hey")
                .map(this::mapWithException)
                .subscribeOn(single)
                .doOnError(e -> System.out.println("ERROR1: " + e.getMessage()))
                .doOnTerminate((r, e) -> {
                    if (e != null) System.out.println("ERROR3: " + e.getMessage());
                    latch.countDown();
                })
                .subscribe(
                        it -> { throw new RuntimeException("Error for " + it); },
                        ex -> { System.out.println("ERROR2: " + ex.getMessage());}
                        );

        latch.await();
    }

    private String mapWithException(String s) {
        throw new RuntimeException();
    }
}

After running test with code above you should three lines in you console

ERROR1: null
ERROR3: null
ERROR2: null

So first callback is onError when mono failed, second will be onTerminate because mono is terminated with error and the third one errorConsumer from subscribe method.


问:
How to reshape a 3D numpy array?
I have a list of numpy arrays which are actually input images to my CNN. However size of each of my image is not cosistent, and my CNN takes only images which are of dimension 224X224. How do I reshape each of my image into the given dimension?
print(train_images[key].reshape(224, 224,3))

gives me an output

ValueError: total size of new array must be unchanged

I would be very grateful if anybody could help me with this.

答:
Here are a few ways I know to achieve this:

Since you're using python, you can use cv2.resize(), to resize the image to 224x224. The problem here is going to be distortions.

Scale the image to adjust to one of the required sizes (W=224 or H=224) and trim off whatever is extra. There is a loss of information here.

If you have the larger image, and a bounding box, use some delta to bounding box to maintain the aspect ratio and then resize down to the required size.

When you reshape a numpy array, the produce of the dimensions must match. If not, it'll throw a ValueError as you've got. There's no solution using reshape to solve your problem, AFAIK.

Title: How to reshape a 3D numpy array?


问:
How to show the particular div based on the selected option
When I select the option from the ddl ,the div of same class is not visible,so I want when I select the option from the ddl so the div of the particular option appear.

In my select, option value are coming from the  database (1.mobile,2.email), so I want when I select mobile then the div number 1 appear.

$(function() {
  $('#theme').change(function() {
    $('#number' + $(this).val('mobile')).show();
  }).change();
});
```

<pre class="lang-html prettyprint-override"><code><label for="mode">Communication Mode :</label>
<?php
      echo "<select name='ddlmode' id='theme' required >";
      echo "<option>-select-</option>";
      include "configpdo.php";
      $stmt = $conn->prepare( "select value from key_master where ems_key='k006' or ems_key='k007'" );
      $stmt->execute();
    $result = $stmt->fetchAll();
     foreach ( $result as $row ){
    echo "<option>" . $row[ "value" ] . "</option>";
                  }
      echo "</select>";
      ?>
  <div id="number1" class="box">
    <label for="sms">SMS text</label>
    <textarea rows="15" cols="80"></textarea>
  </div>
  <div id="number2" class="box">
    <label for="mail">Mail :/label>
      <label for="subject">Subject</label>
    <textarea rows="2" cols="80"></textarea>
    <label for="email" style="font-size: 20px;">Body</label>
    <textarea rows="15" cols="80"></textarea>
  </div>
</code>```

答:
Suppose your select html is like this

```<code><select>
   <option value="0">Select</option>
   <option value="1">Mobile</option>
   <option value="2">Email</option>
</select>
</code>```

then try this

```<code> $(function() {
    $('#theme').change(function() {
       $('.box').hide();
       $('#number' + $(this).val()).show();
    })
 });
</code>```

Body:
When I select the option from the ddl ,the div of same class is not visible,so I want when I select the option from the ddl so the div of the particular option appear.

In my select, option value are coming from the  database (1.mobile,2.email), so I want when I select mobile then the div number 1 appear.

$(function() {
  $('#theme').change(function() {
    $('#number' + $(this).val('mobile')).show();
  }).change();
});

Communication Mode :
<?php
      echo "<select name='ddlmode' id='theme' required >";
      echo "<option>-select-</option>";
      include "configpdo.php";
      $stmt = $conn->prepare( "select value from key_master where ems_key='k006' or ems_key='k007'" );
      $stmt->execute();
    $result = $stmt->fetchAll();
     foreach ( $result as $row ){
    echo "<option>" . $row[ "value" ] . "</option>";
                  }
      echo "</select>";
      ?>

    SMS text
    <textarea rows="15" cols="80"></textarea>

    Mail :/label>
      Subject
    <textarea rows="2" cols="80"></textarea>
    Body
    <textarea rows="15" cols="80"></textarea>

Body:
Suppose your select html is like this

<select>
   <option value="0">Select</option>
   <option value="1">Mobile</option>
   <option value="2">Email</option>
</select>

then try this

 $(function() {
    $('#theme').change(function() {
       $('.box').hide();
       $('#number' + $(this).val()).show();
    })
 });


答:
1st: you need to hide all div[id^=number] divs ids starts with number and show the section by using option:selected index() .. the next code should work with you

$(function() {
  $('#theme').change(function() {
    $('div[id^=number]').hide();
    var GetSectionNum = $(this).find('option:selected').index() == 0 ? 1 : $(this).find('option:selected').index(); // if the selected option is 0 mean 'select' change it to the next of it directly .. so in this code if you try to select 'select' it will select mobile
   $(this).find('option:eq('+GetSectionNum+')').prop('selected' , true);
    $('#number' + GetSectionNum).show();
  }).change();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="theme">
   <option>Select</option>
   <option>Mobile</option>
   <option>Email</option>
</select>
<div id="number1" class="box">
  <label for="sms">SMS text</label>
  <textarea rows="15" cols="80"></textarea>
</div>
<div id="number2" class="box">
  <label for="mail">Mail :/label>
    <label for="subject">Subject</label>
  <textarea rows="2" cols="80"></textarea>
  <label for="email" style="font-size: 20px;">Body</label>
  <textarea rows="15" cols="80"></textarea>
</div></code>```

Title: How to show the particular div based on the selected option

Body:
1st: you need to hide all div[id^=number] divs ids starts with number and show the section by using option:selected index() .. the next code should work with you

$(function() {
  $('#theme').change(function() {
    $('div[id^=number]').hide();
    var GetSectionNum = $(this).find('option:selected').index() == 0 ? 1 : $(this).find('option:selected').index(); // if the selected option is 0 mean 'select' change it to the next of it directly .. so in this code if you try to select 'select' it will select mobile
   $(this).find('option:eq('+GetSectionNum+')').prop('selected' , true);
    $('#number' + GetSectionNum).show();
  }).change();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="theme">
   <option>Select</option>
   <option>Mobile</option>
   <option>Email</option>
</select>
<div id="number1" class="box">
  <label for="sms">SMS text</label>
  <textarea rows="15" cols="80"></textarea>
</div>
<div id="number2" class="box">
  <label for="mail">Mail :/label>
    <label for="subject">Subject</label>
  <textarea rows="2" cols="80"></textarea>
  <label for="email" style="font-size: 20px;">Body</label>
  <textarea rows="15" cols="80"></textarea>
</div>


问:
Will it cause memory leak with in a swift class method
My problem is I'm not sure if a closure inside a class method can leads to memory leak.
Here is my code

```<code>class func SomeDownloadFun (pdfDirectory:String) {

      let destination : DownloadRequest.DownloadFileDestination = {
            _, response in

//----------HERE I Reference the item 'pdfDirectory'-----Will this cause leak?
            let fileURL = URL(fileURLWithPath: pdfDirectory)

            return (fileURL,[.removePreviousFile,.createIntermediateDirectories])
        }

        let downLoadRequest = Alamofire.download(urlStr!, to: destination)

 downLoadRequest.responseData(completionHandler: { (response) in

                switch response.result {
                case .success:

//----------HERE I Reference the item 'pdfDirectory'-----Will this cause leak?

                    print("pdfDirectory")

                    break

                case .failure:
                    print("down err")
                    break

                }

            })
</code>```

}

Aa I have comment  out where i think it will cause a leak ,can anybody tell me ,Thanks!

答:
A couple of observations:

Just because you reference an object in a closure doesn’t mean you have a strong reference cycle. You need circular references (e.g. A has strong reference to B and B has its own strong reference back to A), in order to have strong reference cycle, which doesn’t happen here.

The pdfDirectory isn’t even a reference type (String is a struct, a value type), so there can’t be a strong reference cycle, anyway. It’s only going to happen with reference types (e.g. class rather than struct).

Even when you introduced NSDictionary into the conversation (a reference type), that alone is not sufficient for there to be a strong reference cycle. Don't jump to conclusions about strong reference cycles on the basis of the existence of closure with some reference type. Figure out (or use "Debug memory graph" or Instruments) what objects to which a given object has strong references, and see determine if there are strong reference cycle at that point.

Body:
My problem is I'm not sure if a closure inside a class method can leads to memory leak.
Here is my code

class func SomeDownloadFun (pdfDirectory:String) {

      let destination : DownloadRequest.DownloadFileDestination = {
            _, response in

//----------HERE I Reference the item 'pdfDirectory'-----Will this cause leak?
            let fileURL = URL(fileURLWithPath: pdfDirectory)

            return (fileURL,[.removePreviousFile,.createIntermediateDirectories])
        }

        let downLoadRequest = Alamofire.download(urlStr!, to: destination)

 downLoadRequest.responseData(completionHandler: { (response) in

                switch response.result {
                case .success:

//----------HERE I Reference the item 'pdfDirectory'-----Will this cause leak?

                    print("pdfDirectory")

                    break

                case .failure:
                    print("down err")
                    break

                }

            })

}

Aa I have comment  out where i think it will cause a leak ,can anybody tell me ,Thanks!


问:
Animated image not moving during long Javascript method call
During a method that runs for 10 seconds to add some elements to the html, the animated gif don't move at all, giving the feel that the web page is stuck. Any way around this.

Example code:

```
    $('#button).click(function() {
        showAnimatedGif();
        longRunningMethod();
        hideAnimatedGif();
    });
```

One way around this is to breakup the long running method in multiple steps and animating this way, but then you have to write your code this way for each long running method.

Wondering if there is any otherway to do this ?

答:
The only way to ensure that the animation actually occurs is for longRunningMethod to yield to the browser periodically. It's not uncommon for the UI rendering thread to block on the JavaScript thread, so changes you make to the DOM aren't shown until the next time the JavaScript thread yields. You can yield by calling setTimeout with a timeout of 0 (which will be longer than 0ms — obviously — on most browser implementations; many clamp that value to at least 4ms and possibly as much as 10ms).

Example: Here's a script that adds 500 divs, but gives the browser no opportunity to show the work in progress or (usually) animate anything:

```<code>jQuery(function($) {

  $("#btnGo").click(function() {
    var n;

    display("Loading...");

    for (n = 0; n < 500; ++n) {
      $("<div/>").html("Div #" + n).appendTo(document.body);
    }

    display("Done loading");

    function display(msg) {
      $("<p/>").html(msg).appendTo(document.body);
    }
  });

});
</code>```

Live example * Example with spinner graphic

As you can see, it never yields, and so when you click the button, the page freezes for a moment, and then all 500 divs and the messages appear.

Contrast with this other end of the spectrum, which yields between every div:

```<code>jQuery(function($) {

  $("#btnGo").click(function() {
    display("Loading...");

    addDivs(0, 500, function() {
      display("Done loading");
    });

    function addDivs(current, max, callback) {
      if (current < max) {
        $("<div/>").html("Div #" + current).appendTo(document.body);
        setTimeout(function() {
          addDivs(current + 1, max, callback);
        }, 0);
      }
      else {
        callback();
      }
    }

    function display(msg) {
      $("<p/>").html(msg).appendTo(document.body);
    }
  });

});
</code>```

Live example * Example with spinner graphic

Since that yields, you can see the work in progress.

You might notice that the second script takes longer, possibly much longer, in real time to achieve the same result. This is because the yields take time, as does the browser updating the display. In practice, you'll want to find a balance between the first example and the second — something that yields often enough to show progress, but not so often that the process takes an unnecessarily long time to complete.

ContentLicense: CC BY-SA 4.0

Body:
During a method that runs for 10 seconds to add some elements to the html, the animated gif don't move at all, giving the feel that the web page is stuck. Any way around this.

Example code:

    $('#button).click(function() {
        showAnimatedGif();
        longRunningMethod();
        hideAnimatedGif();
    });

One way around this is to breakup the long running method in multiple steps and animating this way, but then you have to write your code this way for each long running method.

Wondering if there is any otherway to do this ?

Body:
The only way to ensure that the animation actually occurs is for longRunningMethod to yield to the browser periodically. It's not uncommon for the UI rendering thread to block on the JavaScript thread, so changes you make to the DOM aren't shown until the next time the JavaScript thread yields. You can yield by calling setTimeout with a timeout of 0 (which will be longer than 0ms — obviously — on most browser implementations; many clamp that value to at least 4ms and possibly as much as 10ms).

Example: Here's a script that adds 500 divs, but gives the browser no opportunity to show the work in progress or (usually) animate anything:

jQuery(function($) {

  $("#btnGo").click(function() {
    var n;

    display("Loading...");

    for (n = 0; n < 500; ++n) {
      $("<div/>").html("Div #" + n).appendTo(document.body);
    }

    display("Done loading");

    function display(msg) {
      $("<p/>").html(msg).appendTo(document.body);
    }
  });

});

Live example * Example with spinner graphic

As you can see, it never yields, and so when you click the button, the page freezes for a moment, and then all 500 divs and the messages appear.

Contrast with this other end of the spectrum, which yields between every div:

jQuery(function($) {

  $("#btnGo").click(function() {
    display("Loading...");

    addDivs(0, 500, function() {
      display("Done loading");
    });

    function addDivs(current, max, callback) {
      if (current < max) {
        $("<div/>").html("Div #" + current).appendTo(document.body);
        setTimeout(function() {
          addDivs(current + 1, max, callback);
        }, 0);
      }
      else {
        callback();
      }
    }

    function display(msg) {
      $("<p/>").html(msg).appendTo(document.body);
    }
  });

});

Live example * Example with spinner graphic

Since that yields, you can see the work in progress.

You might notice that the second script takes longer, possibly much longer, in real time to achieve the same result. This is because the yields take time, as does the browser updating the display. In practice, you'll want to find a balance between the first example and the second — something that yields often enough to show progress, but not so often that the process takes an unnecessarily long time to complete.


问:
C++ regex behavior
I have check this simple regex test in regexr or regexpal :
\"[a-zA-Z_0-9-]+\"[\s]:[\s]([0-9]1[0-9]|\"[a-zA-Z_0-9:\s-\,./\=;]1[a-zA-Z_0-9:\s-\,./\=;]\")

text :
"dataStoreMaxConns" : 100,
               "dataStoreName" : "cofax",
               "dataStorePassword" : "dataStoreTestQuery",
               "dataStoreTestQuery" : "SET NOCOUNT ON;select test='test';",
               "dataStoreUrl" : "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon"

Result : 2 matches

"dataStoreMaxConns" : 100

"jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon"

I have try with c++ any in https://wandbox.org/ and vs2010 standalone:

```<code> #include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <iterator>

//using namespace std;

int main()
{
    std::string format_1;
    std::string main,dig,phrase;
    std::ifstream infile("noname-2");
    if(infile.good()==false)
        return false;

    main="\\\"[a-zA-Z_0-9\\-]+\\\"[\\s]*:[\\s]*";
    dig="[0-9]*1[0-9]*";
    phrase="\\\"[a-zA-Z_0-9:\\s\\-\\,\\.\/\\=;]*1[a-zA-Z_0-9:\\s\\-\\,\\.\/\\=;]*\\\"";

    format_1=main+"("+dig+"|"+phrase+")";
    std::string str((std::istreambuf_iterator<char>(infile)),std::istreambuf_iterator<char>());
    std::regex f_1(format_1,std::regex_constants::icase);

    std::smatch m_1;
    for(auto it = std::sregex_iterator(str.begin(), str.end(), f_1);it != std::sregex_iterator();++it)
    {
         std::cout<<it->str()<<std::endl;
    }
   return 0;
}
</code>```

nonname-2 contains the text

Result is only one: "dataStoreMaxConns" : 100

Why?

答:
You need to remove unnecessary escape symbols and make sure the - symbol is placed at the start/end of the character class (when escaped, in C++ std::regex does not really handle it as a literal char).

Use

```<code>std::string main2="\"[a-zA-Z_0-9-]+\"\\s*:\\s*";
std::string dig="[0-9]*1[0-9]*";
std::string phrase="\"[a-zA-Z_0-9:\\s,./=;\\\\-]*1[a-zA-Z_0-9:\\s,./=;\\\\-]*\"";
</code>```

See the C++ demo:

```<code>#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::string main2="\"[a-zA-Z_0-9-]+\"\\s*:\\s*";
    std::string dig="[0-9]*1[0-9]*";
    std::string phrase="\"[a-zA-Z_0-9:\\s,./=;\\\\-]*1[a-zA-Z_0-9:\\s,./=;\\\\-]*\"";

    std::string format_1=main2+"("+dig+"|"+phrase+")";
    std::string str("\"dataStoreMaxConns\" : 100,\n\"dataStoreName\" : \"cofax\",\n\"dataStorePassword\" : \"dataStoreTestQuery\",\n\"dataStoreTestQuery\" : \"SET NOCOUNT ON;select test='test';\",\n\"dataStoreUrl\" : \"jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon\"");
    std::regex f_1(format_1,std::regex_constants::icase);

    std::smatch m_1;
    for(auto it = std::sregex_iterator(str.begin(), str.end(), f_1);it != std::sregex_iterator();++it)
    {
         std::cout<<it->str()<<std::endl;
    }
   return 0;
}
</code>```

Title: C++ regex behavior

Body:
I have check this simple regex test in regexr or regexpal :
\"[a-zA-Z_0-9-]+\"[\s]:[\s]([0-9]1[0-9]|\"[a-zA-Z_0-9:\s-\,./\=;]1[a-zA-Z_0-9:\s-\,./\=;]\")

text :
"dataStoreMaxConns" : 100,
               "dataStoreName" : "cofax",
               "dataStorePassword" : "dataStoreTestQuery",
               "dataStoreTestQuery" : "SET NOCOUNT ON;select test='test';",
               "dataStoreUrl" : "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon"

Result : 2 matches

"dataStoreMaxConns" : 100

"jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon"

I have try with c++ any in https://wandbox.org/ and vs2010 standalone:

 #include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <iterator>

//using namespace std;

int main()
{
    std::string format_1;
    std::string main,dig,phrase;
    std::ifstream infile("noname-2");
    if(infile.good()==false)
        return false;

    main="\\\"[a-zA-Z_0-9\\-]+\\\"[\\s]*:[\\s]*";
    dig="[0-9]*1[0-9]*";
    phrase="\\\"[a-zA-Z_0-9:\\s\\-\\,\\.\/\\=;]*1[a-zA-Z_0-9:\\s\\-\\,\\.\/\\=;]*\\\"";

    format_1=main+"("+dig+"|"+phrase+")";
    std::string str((std::istreambuf_iterator<char>(infile)),std::istreambuf_iterator<char>());
    std::regex f_1(format_1,std::regex_constants::icase);

    std::smatch m_1;
    for(auto it = std::sregex_iterator(str.begin(), str.end(), f_1);it != std::sregex_iterator();++it)
    {
         std::cout<<it->str()<<std::endl;
    }
   return 0;
}

nonname-2 contains the text

Result is only one: "dataStoreMaxConns" : 100

Why?

Body:
You need to remove unnecessary escape symbols and make sure the - symbol is placed at the start/end of the character class (when escaped, in C++ std::regex does not really handle it as a literal char).

Use

std::string main2="\"[a-zA-Z_0-9-]+\"\\s*:\\s*";
std::string dig="[0-9]*1[0-9]*";
std::string phrase="\"[a-zA-Z_0-9:\\s,./=;\\\\-]*1[a-zA-Z_0-9:\\s,./=;\\\\-]*\"";

See the C++ demo:

#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::string main2="\"[a-zA-Z_0-9-]+\"\\s*:\\s*";
    std::string dig="[0-9]*1[0-9]*";
    std::string phrase="\"[a-zA-Z_0-9:\\s,./=;\\\\-]*1[a-zA-Z_0-9:\\s,./=;\\\\-]*\"";

    std::string format_1=main2+"("+dig+"|"+phrase+")";
    std::string str("\"dataStoreMaxConns\" : 100,\n\"dataStoreName\" : \"cofax\",\n\"dataStorePassword\" : \"dataStoreTestQuery\",\n\"dataStoreTestQuery\" : \"SET NOCOUNT ON;select test='test';\",\n\"dataStoreUrl\" : \"jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon\"");
    std::regex f_1(format_1,std::regex_constants::icase);

    std::smatch m_1;
    for(auto it = std::sregex_iterator(str.begin(), str.end(), f_1);it != std::sregex_iterator();++it)
    {
         std::cout<<it->str()<<std::endl;
    }
   return 0;
}


问:
Can we create multiple HTML tables dynamically using for loop in jquery
I want to create html table dynamically and number of table will be depend upon the response I am getting in array. New table should be created after every 6 elements and table header will be array elements itself.
Expected output is-

```<code>-------------------------------------
| th1 | th2 | th3 | th4 | th5 | th6 |
-------------------------------------
|     |     |     |     |     |     |
-------------------------------------
</code>```

code for generating table is as below in which consoles are printing properly but elements are not getting create and not getting any error too.

```<code>'<div id="findingDiv">';

    for(var i=0;i<tables;i++){
         console.log('i-',i);
        '<table class="table table-bordered" style="margin-top: 10px; border:1px solid black; border-collapse : collapse;font-size: 30px;">'+
            '<thead>'+
                '<tr>';

                for(var k=0;k<6;k++){

                    '<th id="header" style="color:black; font-size: 12px; border:1px solid black; text-align:center;border-color: rgb(166, 166, 166);"> historyTable[k] </th>';
                    console.log('k-',k);
                }

       '</table> \n';
    }
</code>```

Can anybody help me??

I have checked previous solutions which did not worked.
How to clone() a element n times?
How to use loop in Jquery to add table multiple times into div
Create a table dynamically using for loop in .html()

答:
You can use jQuery .append() method to add HTML table to your DIV dynamicaly in for loop.

Working fiddle

You can use below code.

Below DIV in html:

```<code><div id="findingDiv">
</div>
</code>```

Code in jquery. I used jQuery .ready() method to create it on page load:

```<code>$(document).ready(function () {
    var tables = ['th1','th2','th3','th4','th5','th6']

    for(var i=0;i<tables.length;i++){
    var content = "<table><thead><tr>";
        for(var k=0;k<6;k++)
        {
            content += '<th id="header" style="color:black; font-size: 12px; border:1px solid black; text-align:center;border-color: rgb(166, 166, 166);">'+tables[k]+' </th>';
        }
        content += "</tr></thead></table><br/>";
        $('#findingDiv').append(content);
    }
 });
</code>```

I just added the th, same way you can add tr as well.

Body:
I want to create html table dynamically and number of table will be depend upon the response I am getting in array. New table should be created after every 6 elements and table header will be array elements itself.
Expected output is-

-------------------------------------
| th1 | th2 | th3 | th4 | th5 | th6 |
-------------------------------------
|     |     |     |     |     |     |
-------------------------------------

code for generating table is as below in which consoles are printing properly but elements are not getting create and not getting any error too.

'
';

    for(var i=0;i<tables;i++){
         console.log('i-',i);
        '
'+
            '
'+
                '
';

                for(var k=0;k<6;k++){

                    ' historyTable[k] 	';
                    console.log('k-',k);
                }

       '
 \n';
    }

Can anybody help me??

I have checked previous solutions which did not worked.
How to clone() a element n times?
How to use loop in Jquery to add table multiple times into div
Create a table dynamically using for loop in .html()

Body:
You can use jQuery .append() method to add HTML table to your DIV dynamicaly in for loop.

Working fiddle

You can use below code.

Below DIV in html:

<div id="findingDiv">
</div>

Code in jquery. I used jQuery .ready() method to create it on page load:

$(document).ready(function () {
    var tables = ['th1','th2','th3','th4','th5','th6']

    for(var i=0;i<tables.length;i++){
    var content = "<table><thead><tr>";
        for(var k=0;k<6;k++)
        {
            content += '<th id="header" style="color:black; font-size: 12px; border:1px solid black; text-align:center;border-color: rgb(166, 166, 166);">'+tables[k]+' </th>';
        }
        content += "</tr></thead></table><br/>";
        $('#findingDiv').append(content);
    }
 });

I just added the th, same way you can add tr as well.


问:
Modules vs Typings in Typescript?
I have tried researching everywhere .but i couldn't understand what is the actual difference between modules and typings in typescript?I'm new to typescript ,can someone explain it in a brief?   </p>

答:
Lets give it a try:

Modules are an actual piece of code that gets compiled down to javascript and can be executed. Typescript modules also contains all type information needed - and this a big plus as it helps to see many of the possible bugs at compile time + nice intellisence features in your IDE.

Typings are just description of some other javascript code. They are never compiled down to any javascript and serve only declarative purpose of providing missing type information for already existing javascript libraries.

Title: Modules vs Typings in Typescript?


问:
Reserved words as names or identifiers
Is there any tricky way to use Java reserved words as variable, method, class, interface, package, or enum constant names?</p>

答:
Strictly speaking you can't, unless you get your hands on a buggy compiler implementation that doesn't adhere to the Java language spec.

But where there's a will, there's a way. Copy the following code into your IDE, switch the source file encoding to UTF-16 and here we go:

```<code>public class HelloWorld {

    public static void main(String[] args) {

        HelloWorld.nеw();
    }

    public static void nеw () {
        System.out.println("Hello,World");
    }

}
</code>```

This code is a well-formed and valid Java class. However, as you have guessed there is a little trick: the 'е' character within "new" identifier does not belong to the ASCII character set, it is actually a cyrrilic 'е' (prounanced 'YE').

Current Java language spec explicitly permits, and this an important point to make, the use of Unicode for naming identifiers. That means that one has an ability to freely call her or his classes in French, Chinise or Russian if they wish. It is also possible to mix and match the alphabets within code. And historically, some letters within Latin and other alphabets are lookalikes.

As a result: no, you can't use the reserved words as identifiers, but you can use identifiers that look exactly like reserved words.

Whether anyone should be doing it is a totally different matter.

LastEditorDisplayName: Totophil

Title: Reserved words as names or identifiers

Body:
Strictly speaking you can't, unless you get your hands on a buggy compiler implementation that doesn't adhere to the Java language spec.

But where there's a will, there's a way. Copy the following code into your IDE, switch the source file encoding to UTF-16 and here we go:

public class HelloWorld {

    public static void main(String[] args) {

        HelloWorld.nеw();
    }

    public static void nеw () {
        System.out.println("Hello,World");
    }

}

This code is a well-formed and valid Java class. However, as you have guessed there is a little trick: the 'е' character within "new" identifier does not belong to the ASCII character set, it is actually a cyrrilic 'е' (prounanced 'YE').

Current Java language spec explicitly permits, and this an important point to make, the use of Unicode for naming identifiers. That means that one has an ability to freely call her or his classes in French, Chinise or Russian if they wish. It is also possible to mix and match the alphabets within code. And historically, some letters within Latin and other alphabets are lookalikes.

As a result: no, you can't use the reserved words as identifiers, but you can use identifiers that look exactly like reserved words.

Whether anyone should be doing it is a totally different matter.

OwnerDisplayName: Totophil


问:
Find the number of syllables through BeautifulSoup?
I'm pretty new to programming and is currently trying to learn python. My objective is to use web scraping, or more specifically BeautifulSoup to grab the syllables of a word on dictionary.com to use as part of a larger code. Here's what I have so far:

```<code>def count_syllables(keyword):
    url = 'http://dictionary.com/browse/{}'.format(keyword)
    web_object = requests.get(url)
    text = web_object.text
    text = text.encode('utf-8')
    soup = BeautifulSoup(text, 'html.parser')
    div = [div for div in soup.find_all('div', {'class':"waypoint-wrapper header-row header-first-row"})]
    span = [div.find(name='span') for div in div]

    return span

#output: [<span class="me" data-syllable="syl·la·ble">syllable</span>]
</code>```

This only returns the span tag in the html source but not the syllable itself. For example, I'm looking to scrape "syl·la·ble" from inputting the word "syllable" into the search bar on dictionary.com. However, my code is only returning the whole span tag. When I try other methods from watching youtube videos, I keep getting empty lists. So my question is: How would I go about just grabbing the syl·la·ble part in the span tag?

答:
You can extent your span tag and use data-syllable attribute :

```<code>>>> span[0]['data-syllable']
'syl·la·bus'
</code>```

Body:
I'm pretty new to programming and is currently trying to learn python. My objective is to use web scraping, or more specifically BeautifulSoup to grab the syllables of a word on dictionary.com to use as part of a larger code. Here's what I have so far:

def count_syllables(keyword):
    url = 'http://dictionary.com/browse/{}'.format(keyword)
    web_object = requests.get(url)
    text = web_object.text
    text = text.encode('utf-8')
    soup = BeautifulSoup(text, 'html.parser')
    div = [div for div in soup.find_all('div', {'class':"waypoint-wrapper header-row header-first-row"})]
    span = [div.find(name='span') for div in div]

    return span

#output: [syllable]

This only returns the span tag in the html source but not the syllable itself. For example, I'm looking to scrape "syl·la·ble" from inputting the word "syllable" into the search bar on dictionary.com. However, my code is only returning the whole span tag. When I try other methods from watching youtube videos, I keep getting empty lists. So my question is: How would I go about just grabbing the syl·la·ble part in the span tag?

Body:
You can extent your span tag and use data-syllable attribute :

>>> span[0]['data-syllable']
'syl·la·bus'


问:
NullPointerException in Kotlin
When I write this code in kotlin activity

```<code>var tv: TextView = findViewById(R.id.tv_kotlin) as TextView
</code>```

It always crashes with the following error:

```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
</code>```

And I find when I convert my Java codes to kotlin codes,the auto converter always does like this:

```<code>private var btn: Button? = null
</code>```

And when I use the reference, I have to put a !! behind it which make the codes really ugly.So what is the correct way binding UI in kotlin android?

The completed code:

```<code>class JavaToKotlinActivity : AppCompatActivity() {

    private var tv: TextView = findViewById(R.id.tv) as TextView
    private var btn: Button? = null
    private var et: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_java_to_kotlin)
        initView()
    }

    private fun initView() {
        btn = findViewById(R.id.btn) as Button
        et = findViewById(R.id.et) as EditText
        btn!!.setOnClickListener { tv.text = "haha" }
        et!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }
}
</code>```

And the error messages :

```<code>06-09 14:25:38.574 9770-9770/com.mimi E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: com.mimi, PID: 9770
                                                        java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mimi/com.mimi.Views.JavaToKotlinActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2488)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
                                                            at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
                                                            at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
                                                            at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
                                                            at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:199)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
                                                            at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
                                                            at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                                                            at com.mimi.Views.JavaToKotlinActivity.<init>(JavaToKotlinActivity.kt:20)
                                                            at java.lang.Class.newInstance(Native Method)
                                                            at android.app.Instrumentation.newActivity(Instrumentation.java:1072)
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2478)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
</code>```

答:
You must bind your views after setContentView(R.layout.activity_java_to_kotlin)

if you don't want use nullable type:

```<code>private lateinit var tv: TextView
</code>```

and in initView()

```<code>tv = findViewById(R.id.tv) as TextView
</code>```

And don't forget about screen rotation.

Title: NullPointerException in Kotlin

Body:
When I write this code in kotlin activity

var tv: TextView = findViewById(R.id.tv_kotlin) as TextView

It always crashes with the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

And I find when I convert my Java codes to kotlin codes,the auto converter always does like this:

private var btn: Button? = null

And when I use the reference, I have to put a !! behind it which make the codes really ugly.So what is the correct way binding UI in kotlin android?

The completed code:

class JavaToKotlinActivity : AppCompatActivity() {

    private var tv: TextView = findViewById(R.id.tv) as TextView
    private var btn: Button? = null
    private var et: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_java_to_kotlin)
        initView()
    }

    private fun initView() {
        btn = findViewById(R.id.btn) as Button
        et = findViewById(R.id.et) as EditText
        btn!!.setOnClickListener { tv.text = "haha" }
        et!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }
}

And the error messages :

06-09 14:25:38.574 9770-9770/com.mimi E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: com.mimi, PID: 9770
                                                        java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mimi/com.mimi.Views.JavaToKotlinActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2488)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
                                                            at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
                                                            at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
                                                            at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
                                                            at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:199)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
                                                            at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
                                                            at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                                                            at com.mimi.Views.JavaToKotlinActivity.<init>(JavaToKotlinActivity.kt:20)
                                                            at java.lang.Class.newInstance(Native Method)
                                                            at android.app.Instrumentation.newActivity(Instrumentation.java:1072)
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2478)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)

Body:
You must bind your views after setContentView(R.layout.activity_java_to_kotlin)

if you don't want use nullable type:

private lateinit var tv: TextView

and in initView()

tv = findViewById(R.id.tv) as TextView

And don't forget about screen rotation.


问:
using multiple es6 map and make it async
```<code>const eventBarData = data.map(obj => prepareEventBar(obj.calendar))

const mapToSpaceData = eventBarData.map(obj => ({
  space_name: obj.space.display.name,
  ...obj
}))
</code>```

Above code won't work because both run concurrently? how to ensure eventBarData done processing then run another map? must I wrap map within a map? I don't want to use callback in prepareEventBar function.

答:
Have prepareEventBar return a Promise. Then you can just use Promise.all:

```<code>const eventBarDataPromises = data.map(obj => prepareEventBar(obj.calendar))

Promise.all(eventBarDataPromises)
  .then(eventBarData => eventBarData.map(obj => ...))
  .then(mapToSpaceData => ...
</code>```

Alternatively, if your environment supports it or you're using a transpiler, an async function might be somewhat cleaner:

```<code>// this code must be wrapped in an async function
const eventBarData = await Promise.all(
  data.map(obj => prepareEventBar(obj.calendar))
);

const mapToSpaceData = eventBarData.map(obj => ...);
</code>```

Body:
const eventBarData = data.map(obj => prepareEventBar(obj.calendar))

const mapToSpaceData = eventBarData.map(obj => ({
  space_name: obj.space.display.name,
  ...obj
}))

Above code won't work because both run concurrently? how to ensure eventBarData done processing then run another map? must I wrap map within a map? I don't want to use callback in prepareEventBar function.

Body:
Have prepareEventBar return a Promise. Then you can just use Promise.all:

const eventBarDataPromises = data.map(obj => prepareEventBar(obj.calendar))

Promise.all(eventBarDataPromises)
  .then(eventBarData => eventBarData.map(obj => ...))
  .then(mapToSpaceData => ...

Alternatively, if your environment supports it or you're using a transpiler, an async function might be somewhat cleaner:

// this code must be wrapped in an async function
const eventBarData = await Promise.all(
  data.map(obj => prepareEventBar(obj.calendar))
);

const mapToSpaceData = eventBarData.map(obj => ...);


答:
you should put value on options like this

```<code>echo "<option value="'.$row[ "value" ].'">" . $row[ "value" ] . "</option>";
</code>```

hope it helps.

Body:
When I select the option from the ddl ,the div of same class is not visible,so I want when I select the option from the ddl so the div of the particular option appear.

In my select, option value are coming from the  database (1.mobile,2.email), so I want when I select mobile then the div number 1 appear.

$(function() {
  $('#theme').change(function() {
    $('#number' + $(this).val('mobile')).show();
  }).change();
});

Communication Mode :
<?php
      echo "<select name='ddlmode' id='theme' required >";
      echo "<option>-select-</option>";
      include "configpdo.php";
      $stmt = $conn->prepare( "select value from key_master where ems_key='k006' or ems_key='k007'" );
      $stmt->execute();
    $result = $stmt->fetchAll();
     foreach ( $result as $row ){
    echo "<option>" . $row[ "value" ] . "</option>";
                  }
      echo "</select>";
      ?>

    SMS text
    <textarea rows="15" cols="80"></textarea>

    Mail :/label>
      Subject
    <textarea rows="2" cols="80"></textarea>
    Body
    <textarea rows="15" cols="80"></textarea>

Body:
you should put value on options like this

echo "<option value="'.$row[ "value" ].'">" . $row[ "value" ] . "</option>";

hope it helps.


问:
how to create menu in statusbar in qt like PC start menu
In my qt application, i have designed status bar with few icons. On the left of my status bar i have added menu icon (QPixmap) when i click that icon i need to show a menu similar to PC start menu. I searched a lot but i did not found Qwidget for this.

This is my qt application window

As per my recent comment i added my edited code below since i cannot add the code in comment section, plz suggest a solution

```<code>//Menu Button
    menuBtn->setIcon(QPixmap(":/new/prefix1/ic_menu_black.png"));
    statusBar()->addWidget(menuBtn);
    connect(menuBtn,SIGNAL(clicked(bool)),this,SLOT(showPopupMenu()));

void MainWindow::showPopupMenu(){

    QMenu qMenuStart;

    QAction qCmdStart1(QString::fromUtf8("Product Details"), &qMenuStart);
    qMenuStart.addAction(&qCmdStart1);

    QAction qCmdStart2(QString::fromUtf8("Memory Status"), &qMenuStart);
    qMenuStart.addAction(&qCmdStart2);

    QObject::connect(&qCmdStart1, &QAction::triggered,[](bool){
        qDebug() << "Product Details triggered"; }
    );
    QObject::connect(&qCmdStart2, &QAction::triggered,[](bool){
        qDebug() << "Memory Status triggered"; }
    );

    qMenuStart.exec();

    menuBtn->setMenu(&qMenuStart);

    qMenuStart.show();
    qMenuStart.popup(mapToGlobal(pos() - QPoint(0, qMenuStart.height())));

    qDebug()<<"Menu Clicked!";

}
</code>```

popup menu on click of menu button

答:
Reading your question, I was not quite sure what your actual problem is. Unfortunately, due to the security policy of our company, i.stack.imgur.com is blocked and I'm just in the office. Probably, your snapshot had clarified the things for me. (I could have a look at it when I'm home again.)

However, out of curiosity, I tried my luck and want to show what I've got:

Actually, it is quite easy to add a widget to a status bar using QStatusBar::insertPermanentWidget().

Unfortunately, permanent widgets are placed on the right. If the requirement (to place it at left) is essential, this can be tweaked by nesting two status bars into each other. (Actually, every other layout should be capable also but the QMainWindow::setStatusBar() requires a QStatusBar*.)

The inner status bar is the one which has to be used for temporary messages. To prevent the funny effect of duplicated size grips, the size grip is disabled for the inner status bar (using QStatusBar::setSizeGripEnabled()).

Another side effect of nested status bars is the visualization of separators at the left and right of the inner status bar. I considered this as not that bad (concerning the aesthetical aspect) and didn't care about it.

May be, I could have used simply a QLabel (instead of the inner status bar) for message display (losing the additional capabilities provided by QStatusBar e.g. the timeout for auto-clear of a message).

To provide the start button, I originally used a QPushButton. Remembering that I have to place the start menu somehow I replaced it with a QToolBar as it may contain a QAction which in turn is ready equipped to manage a sub-menu.

As I got this working I realized the indicator which appeared at the start button when I set the menu. To keep the sample as short as possible I decided to live with this for now.

After having some communication with the questioner, I added an alternative implementation using a class derived from QLabel. The menu placement has to be done on its own. But finally, it's not that complicated...

The 2nd version is activated if USE_LABEL is defined (near beginning of source code).

My sample testQStartBtn.cc:

```<code>#include <QtWidgets>

#define USE_LABEL

#ifdef USE_LABEL
class StartButton: public QLabel {

  private:
    QMenu *_pQMenu;

  public:
    StartButton(QWidget *pQParent = 0): QLabel(pQParent), _pQMenu(nullptr) { }

    QMenu* menu() { return _pQMenu; }
    QMenu* setMenu(QMenu *pQMenu) { std::swap(_pQMenu, pQMenu); return pQMenu; }

  protected:
    virtual void mousePressEvent(QMouseEvent *pQEvent);
};

void StartButton::mousePressEvent(QMouseEvent *pQEvent)
{
  if (_pQMenu && pQEvent->button() == Qt::LeftButton) {
    if (!_pQMenu->isVisible()) {
      _pQMenu->show(); // a trick to force computation of height() before
      _pQMenu->popup(mapToGlobal(pos()) - QPoint(0, _pQMenu->height()));
    } else _pQMenu->hide();
  }
}
#endif // USE_LABEL

int main(int argc, char **argv)
{
  qDebug() << "Qt Version: " << QT_VERSION_STR;
  // main application
#undef qApp // undef macro qApp out of the way
  QApplication qApp(argc, argv);
  // setup GUI
  QMainWindow qWin;
  QLabel qLblCentral(QString::fromUtf8("Central\nWidget"));
  qLblCentral.setAlignment(Qt::AlignCenter);
  qWin.setCentralWidget(&qLblCentral);
  QStatusBar qStBarLayout;
  // the "Windows Start Menu" alike
#ifdef USE_LABEL
  StartButton qBtnStart;
  qBtnStart.setPixmap(QPixmap(
    QApplication::applicationDirPath() + QString::fromLatin1("/Start.png")));
#else // (not) USE_LABEL
  QToolBar qToolbarStart;
  QIcon qIcnStart(
    QApplication::applicationDirPath() + QString::fromLatin1("/Start.png"));
  QAction qCmdStart(qIcnStart, QString::fromUtf8("Start"), &qToolbarStart);
#endif // USE_LABEL
  QMenu qMenuStart;
  QAction qCmdStart1(QString::fromUtf8("Command 1"), &qMenuStart);
  qMenuStart.addAction(&qCmdStart1);
  QAction qCmdStart2(QString::fromUtf8("Command 2"), &qMenuStart);
  qMenuStart.addAction(&qCmdStart2);
  QAction qCmdStart3(QString::fromUtf8("Command 3"), &qMenuStart);
  qMenuStart.addAction(&qCmdStart3);
#ifdef USE_LABEL
  qBtnStart.setMenu(&qMenuStart);
  qStBarLayout.insertPermanentWidget(0, &qBtnStart);
#else // (not) USE_LABEL
  qCmdStart.setMenu(&qMenuStart);
  qToolbarStart.addAction(&qCmdStart);
  qStBarLayout.insertPermanentWidget(0, &qToolbarStart);
#endif // USE_LABEL
  // the rest of status bar
  QStatusBar qStBar;
  qStBar.showMessage(QString::fromUtf8("<- Start Menu"), 3000 /* ms */);
  qStBar.setSizeGripEnabled(false);
  qStBarLayout.insertPermanentWidget(1, &qStBar, 1);
  qWin.setStatusBar(&qStBarLayout);
  qWin.show();
  // install signal handlers
  QObject::connect(&qCmdStart1, &QAction::triggered,
    [](bool){ qDebug() << "Command 1 triggered"; });
  QObject::connect(&qCmdStart2, &QAction::triggered,
    [](bool){ qDebug() << "Command 2 triggered"; });
  QObject::connect(&qCmdStart3, &QAction::triggered,
    [](bool){ qDebug() << "Command 3 triggered"; });
  // run application
  return qApp.exec();
}
</code>```

I compiled with VS2013 and Qt5.6 on Windows 10 (64 bit). This is how it looks:

The updated version with the derived QLabel looks like this:

Body:
In my qt application, i have designed status bar with few icons. On the left of my status bar i have added menu icon (QPixmap) when i click that icon i need to show a menu similar to PC start menu. I searched a lot but i did not found Qwidget for this.

This is my qt application window

As per my recent comment i added my edited code below since i cannot add the code in comment section, plz suggest a solution

//Menu Button
    menuBtn->setIcon(QPixmap(":/new/prefix1/ic_menu_black.png"));
    statusBar()->addWidget(menuBtn);
    connect(menuBtn,SIGNAL(clicked(bool)),this,SLOT(showPopupMenu()));

void MainWindow::showPopupMenu(){

    QMenu qMenuStart;

    QAction qCmdStart1(QString::fromUtf8("Product Details"), &qMenuStart);
    qMenuStart.addAction(&qCmdStart1);

    QAction qCmdStart2(QString::fromUtf8("Memory Status"), &qMenuStart);
    qMenuStart.addAction(&qCmdStart2);

    QObject::connect(&qCmdStart1, &QAction::triggered,[](bool){
        qDebug() << "Product Details triggered"; }
    );
    QObject::connect(&qCmdStart2, &QAction::triggered,[](bool){
        qDebug() << "Memory Status triggered"; }
    );

    qMenuStart.exec();

    menuBtn->setMenu(&qMenuStart);

    qMenuStart.show();
    qMenuStart.popup(mapToGlobal(pos() - QPoint(0, qMenuStart.height())));

    qDebug()<<"Menu Clicked!";

}

popup menu on click of menu button

Body:
Reading your question, I was not quite sure what your actual problem is. Unfortunately, due to the security policy of our company, i.stack.imgur.com is blocked and I'm just in the office. Probably, your snapshot had clarified the things for me. (I could have a look at it when I'm home again.)

However, out of curiosity, I tried my luck and want to show what I've got:

Actually, it is quite easy to add a widget to a status bar using QStatusBar::insertPermanentWidget().

Unfortunately, permanent widgets are placed on the right. If the requirement (to place it at left) is essential, this can be tweaked by nesting two status bars into each other. (Actually, every other layout should be capable also but the QMainWindow::setStatusBar() requires a QStatusBar*.)

The inner status bar is the one which has to be used for temporary messages. To prevent the funny effect of duplicated size grips, the size grip is disabled for the inner status bar (using QStatusBar::setSizeGripEnabled()).

Another side effect of nested status bars is the visualization of separators at the left and right of the inner status bar. I considered this as not that bad (concerning the aesthetical aspect) and didn't care about it.

May be, I could have used simply a QLabel (instead of the inner status bar) for message display (losing the additional capabilities provided by QStatusBar e.g. the timeout for auto-clear of a message).

To provide the start button, I originally used a QPushButton. Remembering that I have to place the start menu somehow I replaced it with a QToolBar as it may contain a QAction which in turn is ready equipped to manage a sub-menu.

As I got this working I realized the indicator which appeared at the start button when I set the menu. To keep the sample as short as possible I decided to live with this for now.

After having some communication with the questioner, I added an alternative implementation using a class derived from QLabel. The menu placement has to be done on its own. But finally, it's not that complicated...

The 2nd version is activated if USE_LABEL is defined (near beginning of source code).

My sample testQStartBtn.cc:

#include <QtWidgets>

#define USE_LABEL

#ifdef USE_LABEL
class StartButton: public QLabel {

  private:
    QMenu *_pQMenu;

  public:
    StartButton(QWidget *pQParent = 0): QLabel(pQParent), _pQMenu(nullptr) { }

    QMenu* menu() { return _pQMenu; }
    QMenu* setMenu(QMenu *pQMenu) { std::swap(_pQMenu, pQMenu); return pQMenu; }

  protected:
    virtual void mousePressEvent(QMouseEvent *pQEvent);
};

void StartButton::mousePressEvent(QMouseEvent *pQEvent)
{
  if (_pQMenu && pQEvent->button() == Qt::LeftButton) {
    if (!_pQMenu->isVisible()) {
      _pQMenu->show(); // a trick to force computation of height() before
      _pQMenu->popup(mapToGlobal(pos()) - QPoint(0, _pQMenu->height()));
    } else _pQMenu->hide();
  }
}
#endif // USE_LABEL

int main(int argc, char **argv)
{
  qDebug() << "Qt Version: " << QT_VERSION_STR;
  // main application
#undef qApp // undef macro qApp out of the way
  QApplication qApp(argc, argv);
  // setup GUI
  QMainWindow qWin;
  QLabel qLblCentral(QString::fromUtf8("Central\nWidget"));
  qLblCentral.setAlignment(Qt::AlignCenter);
  qWin.setCentralWidget(&qLblCentral);
  QStatusBar qStBarLayout;
  // the "Windows Start Menu" alike
#ifdef USE_LABEL
  StartButton qBtnStart;
  qBtnStart.setPixmap(QPixmap(
    QApplication::applicationDirPath() + QString::fromLatin1("/Start.png")));
#else // (not) USE_LABEL
  QToolBar qToolbarStart;
  QIcon qIcnStart(
    QApplication::applicationDirPath() + QString::fromLatin1("/Start.png"));
  QAction qCmdStart(qIcnStart, QString::fromUtf8("Start"), &qToolbarStart);
#endif // USE_LABEL
  QMenu qMenuStart;
  QAction qCmdStart1(QString::fromUtf8("Command 1"), &qMenuStart);
  qMenuStart.addAction(&qCmdStart1);
  QAction qCmdStart2(QString::fromUtf8("Command 2"), &qMenuStart);
  qMenuStart.addAction(&qCmdStart2);
  QAction qCmdStart3(QString::fromUtf8("Command 3"), &qMenuStart);
  qMenuStart.addAction(&qCmdStart3);
#ifdef USE_LABEL
  qBtnStart.setMenu(&qMenuStart);
  qStBarLayout.insertPermanentWidget(0, &qBtnStart);
#else // (not) USE_LABEL
  qCmdStart.setMenu(&qMenuStart);
  qToolbarStart.addAction(&qCmdStart);
  qStBarLayout.insertPermanentWidget(0, &qToolbarStart);
#endif // USE_LABEL
  // the rest of status bar
  QStatusBar qStBar;
  qStBar.showMessage(QString::fromUtf8("<- Start Menu"), 3000 /* ms */);
  qStBar.setSizeGripEnabled(false);
  qStBarLayout.insertPermanentWidget(1, &qStBar, 1);
  qWin.setStatusBar(&qStBarLayout);
  qWin.show();
  // install signal handlers
  QObject::connect(&qCmdStart1, &QAction::triggered,
    [](bool){ qDebug() << "Command 1 triggered"; });
  QObject::connect(&qCmdStart2, &QAction::triggered,
    [](bool){ qDebug() << "Command 2 triggered"; });
  QObject::connect(&qCmdStart3, &QAction::triggered,
    [](bool){ qDebug() << "Command 3 triggered"; });
  // run application
  return qApp.exec();
}

I compiled with VS2013 and Qt5.6 on Windows 10 (64 bit). This is how it looks:

The updated version with the derived QLabel looks like this:


问:
Overlay branches in Git (Perforce)
I have been working with perforce for some time. We used overlay branches for customers. Only some files are specific for the customer. All other files are standard.

The overlay branch compared to a full branch has the advantage that nobody is tempted to do developments in the customer branch which should be done in the standard branch.

If a full branch would be created I would fear, that the developer would do the development in the customer branch.

Additionally with the overlay branch it is not needed to update the customer branch, if only standard things are adapted.

Is there a best practice how one can have a customer branch in which are only few adaptions?

答:
It does not matter if developer are working in the wrong branch as long as they are not able to push into said branch. And all major Git repos hosting servers have branch protection in place (GitHub, GitLab, BitBucket, ...)

The developer can create his/her own branch from the customer one in order to modify only a few files in isolation.

Client specific files are best managed with a different name, and used at deployment time.

Title: Overlay branches in Git (Perforce)


问:
How can one Tcl thread cause an event in another?
I have a system with multiple I/O interfaces, and I'm collecting the output of all of them into a common log.  Two of the interfaces are through well-behaved channels that are opened as file-like objects, and can be managed on an event basis with "fileevent readable".  The other two are the problem.

These are to a vendor-supplied library, which someone else has already kindly wrapped into a Tcl package (snoopy, FWIW).  However, the only read access is a blocking call, and there's nothing in the package that would cause an event equivalent to a fileevent.

I've figured out how to spawn a separate thread to block on the read, pull the result, and put it into a message queue for the main thread.  But having the main thread block on reading the queue would seem to defeat the purpose, especially since there are two queues it would have to block on.  And I haven't been able to get the reader to generate an event that can trigger the main thread to read the queue.

I've looked on the tcl.tk wiki to no avail so far.  I've tried using the uevent library to generate an event on a message push, but the event goes to the writing thread instead of the reading thread, which really doesn't help.  It seems like there should be some solution related to a Thread condition variable, but so far I haven't been able to find an appropriate design pattern for that use of the library.

If all else fails I'll fall back to a Tk event, but I'm trying to keep Tk out of this as it's meant to be an automated system with no GUI, and any mention of Tk pushes tclsh into wish and pops up a GUI window.

I feel like I'm close, but just missing something.

答:
I finally grokked what Donal was saying about Thread events.  I blame inadequate morning caffeine for not getting it the first time.

All the prior examples of thread::send I've seen concerned a master sending scripts down to the worker thread.  In this case, the worker thread needs to send scripts back up to the master, where the script is the one that would be called on [fileevent readable] if this was a channel.

Here's my test code for the interaction:

```<code>proc reader {payload} {
    puts $payload
}

set t1 [thread::create]
thread::send -async $t1 {
    proc produce {parentid} {
        while 1 {
            after 250   ;# substitutes for
            incr data   ;# the blocking read
            thread::send $parentid "reader $data"
        }
    }
}

set tid [thread::id]
thread::send -async $t1 [list produce $tid]

vwait forever
</code>```

The part I saw but didn't immediately grok was the importance of the master thread having an ID that can be sent to the worker.  The key that I'd missed was that the worker can send scripts to the master just as easily as the master can send scripts to the worker; the worker just usually doesn't know the master's Thread ID.

Once the ID is passed to it, the producer thread can therefore use thread::send to call a proc in the master to handle the data, and it becomes an event in the master thread, just as I'd desired.  It's not the way I've worked with threads in the past, but once understood it's powerful.

Body:
I finally grokked what Donal was saying about Thread events.  I blame inadequate morning caffeine for not getting it the first time.

All the prior examples of thread::send I've seen concerned a master sending scripts down to the worker thread.  In this case, the worker thread needs to send scripts back up to the master, where the script is the one that would be called on [fileevent readable] if this was a channel.

Here's my test code for the interaction:

proc reader {payload} {
    puts $payload
}

set t1 [thread::create]
thread::send -async $t1 {
    proc produce {parentid} {
        while 1 {
            after 250   ;# substitutes for
            incr data   ;# the blocking read
            thread::send $parentid "reader $data"
        }
    }
}

set tid [thread::id]
thread::send -async $t1 [list produce $tid]

vwait forever

The part I saw but didn't immediately grok was the importance of the master thread having an ID that can be sent to the worker.  The key that I'd missed was that the worker can send scripts to the master just as easily as the master can send scripts to the worker; the worker just usually doesn't know the master's Thread ID.

Once the ID is passed to it, the producer thread can therefore use thread::send to call a proc in the master to handle the data, and it becomes an event in the master thread, just as I'd desired.  It's not the way I've worked with threads in the past, but once understood it's powerful.


问:
How to find Effect Editor in Inkscape 0.92
I've just switched from Inkscake 0.48 to 0.92. In Inkscape 0.48, there is a "Path Effect Editor" Under the menu "Path", But when I switch in 0.92, there is nos effect editor available there.I am attaching the screenshots one, two, three, and four

My question is - How can I get this editing option in 0.92 (More specifically - How can I change the stroke width of pencil tool). Thanks in advance.

答: You can get by selecting "Patter Along Path" under Path Effet or just by selecting shape as Ellipse after selecting pencil tool.


问:
Xcode Server OTA Install: "cannot connect to server.local"
I cannot get the "Over The Air" installation of iOS apps to work using the latest version of macOS (10.12.5) and Xcode Server (5.3.1). I can create Xcode Bots and the integrate without any issue, but it always fails with "cannot connect to server.local" when trying to install the app from any device.
The "Xcode Server OTA Installation" profile is installed.
I can download the archive and product using Safari on the Mac without a problem.
In summary, everything work but the OTA installation always fails.

Tried on two different Macs already, also with a complete clean installation of macOS before.

Versions: macOS 10.12.5, Xcode 8.3.2 and Server 5.3.1

I found several old reports of this problem but all the workarounds didn't seem to help.

Same problem on Xcode 9 beta 1 with the now built-in Xcode server.

答: My SSL certificate had expired thats why happened to me. Make sure you add that to the list of things to check. Once I renewed that it started working again.</p>


问:
undefined reference to curl_global_init, curl_easy_init and other function(C)
I am trying to use Curl in C.

I visited Curl official page, and copied sample source code.

below is the link:
http://curl.haxx.se/libcurl/c/sepheaders.html

when I run this code with command "gcc test.c",

the console shows message like below.

```<code>/tmp/cc1vsivQ.o: In function `main':
test.c:(.text+0xe1): undefined reference to `curl_global_init'
test.c:(.text+0xe6): undefined reference to `curl_easy_init'
test.c:(.text+0x10c): undefined reference to `curl_easy_setopt'
test.c:(.text+0x12e): undefined reference to `curl_easy_setopt'
test.c:(.text+0x150): undefined reference to `curl_easy_setopt'
test.c:(.text+0x17e): undefined reference to `curl_easy_cleanup'
test.c:(.text+0x1b3): undefined reference to `curl_easy_cleanup'
test.c:(.text+0x1db): undefined reference to `curl_easy_setopt'
test.c:(.text+0x1e7): undefined reference to `curl_easy_perform'
test.c:(.text+0x1ff): undefined reference to `curl_easy_cleanup'
</code>```

I do not know how to solve this.

答:
I have the same problem, but i use g++ with a make file.
This is a linker issue.
You need to add option -lcurl on the compiler and on the linker.
In my case on the make file:

```<code>CC ?= gcc
CXX ?= g++
CXXFLAGS += -I ../src/ -I ./ -DLINUX -lcurl  <- compile option
LDFLAGS += -lrt -lpthread -lcurl      <- linker option
</code>```

Gerard

Body:
I am trying to use Curl in C.

I visited Curl official page, and copied sample source code.

below is the link:
http://curl.haxx.se/libcurl/c/sepheaders.html

when I run this code with command "gcc test.c",

the console shows message like below.

/tmp/cc1vsivQ.o: In function `main':
test.c:(.text+0xe1): undefined reference to `curl_global_init'
test.c:(.text+0xe6): undefined reference to `curl_easy_init'
test.c:(.text+0x10c): undefined reference to `curl_easy_setopt'
test.c:(.text+0x12e): undefined reference to `curl_easy_setopt'
test.c:(.text+0x150): undefined reference to `curl_easy_setopt'
test.c:(.text+0x17e): undefined reference to `curl_easy_cleanup'
test.c:(.text+0x1b3): undefined reference to `curl_easy_cleanup'
test.c:(.text+0x1db): undefined reference to `curl_easy_setopt'
test.c:(.text+0x1e7): undefined reference to `curl_easy_perform'
test.c:(.text+0x1ff): undefined reference to `curl_easy_cleanup'

I do not know how to solve this.

Body:
I have the same problem, but i use g++ with a make file.
This is a linker issue.
You need to add option -lcurl on the compiler and on the linker.
In my case on the make file:

CC ?= gcc
CXX ?= g++
CXXFLAGS += -I ../src/ -I ./ -DLINUX -lcurl  <- compile option
LDFLAGS += -lrt -lpthread -lcurl      <- linker option

Gerard