问:
Why is width: 100% not working on div {display: table-cell}?
I'm trying to vertically and horizontally center some content overlaying an image slide (flexslider).  There were some similar questions to this one, but I couldn't find a satisfactory solution that applied directly to my specific problem.  Because of the limitations of FlexSlider, I cannot use position: absolute; on the img tag in my implementation.

I almost have workaround below working. The only problem is I cannot get the width & height declarations to work on inner-wrapper div with the display: table-cell property.

Is this standard behavior, or am I missing something with my code?  If it's standard behavior, what's the best solution to my problem?

HTML

```<code><ul>
    <li>
        <img src="#">
        <div class="outer-wrapper">
            <div class="inner-wrapper">
                <h1>My Title</h1>
                <h5>Subtitle</h5>
            </div>
        </div>
    </li>
</ul>
</code>```

CSS

```<code>html, body {
    margin: 0; padding: 0;
    width: 100%; height: 100%;
}

ul {
    background: #CCC;
    height: 100%;
    width: 100%;
    list-style-position: outside;
    margin: 0; padding: 0;
}

li {
    width: 100%;
    display: table;
}

img {
    width: 100%;
    height: 410px;
}

.outer-wrapper {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    margin: 0; padding: 0;
}

.inner-wrapper {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 100%;
    height: 100%;
}
</code>```

Note: the centered content will be more than 1 element, so I can't use the line-height trick.

jsFiddle.

答:
Welcome to 2017 these days will  using vW and vH do the trick

html, body {
    margin: 0; padding: 0;
    width: 100%; height: 100%;
}

ul {
    background: #CCC;
    height: 100%;
    width: 100%;
    list-style-position: outside;
    margin: 0; padding: 0;
}

li {
    width: 100%;
    display: table;
}

img {
    width: 100%;
    height: 410px;
}

.outer-wrapper {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    margin: 0; padding: 0;
}

.inner-wrapper {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 100vw; /* only change is here "%" to "vw" ! */
    height: 100vh; /* only change is here "%" to "vh" ! */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li>
        <img src="#">
        <div class="outer-wrapper">
            <div class="inner-wrapper">
                <h1>My Title</h1>
                <h5>Subtitle</h5>
            </div>
        </div>
    </li>
</ul></code>```

Body:
I'm trying to vertically and horizontally center some content overlaying an image slide (flexslider).  There were some similar questions to this one, but I couldn't find a satisfactory solution that applied directly to my specific problem.  Because of the limitations of FlexSlider, I cannot use position: absolute; on the img tag in my implementation.

I almost have workaround below working. The only problem is I cannot get the width & height declarations to work on inner-wrapper div with the display: table-cell property.

Is this standard behavior, or am I missing something with my code?  If it's standard behavior, what's the best solution to my problem?

HTML

My Title

Subtitle

CSS

html, body {
    margin: 0; padding: 0;
    width: 100%; height: 100%;
}

ul {
    background: #CCC;
    height: 100%;
    width: 100%;
    list-style-position: outside;
    margin: 0; padding: 0;
}

li {
    width: 100%;
    display: table;
}

img {
    width: 100%;
    height: 410px;
}

.outer-wrapper {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    margin: 0; padding: 0;
}

.inner-wrapper {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 100%;
    height: 100%;
}

Note: the centered content will be more than 1 element, so I can't use the line-height trick.

jsFiddle.

Body:
Welcome to 2017 these days will  using vW and vH do the trick

html, body {
    margin: 0; padding: 0;
    width: 100%; height: 100%;
}

ul {
    background: #CCC;
    height: 100%;
    width: 100%;
    list-style-position: outside;
    margin: 0; padding: 0;
}

li {
    width: 100%;
    display: table;
}

img {
    width: 100%;
    height: 410px;
}

.outer-wrapper {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    margin: 0; padding: 0;
}

.inner-wrapper {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 100vw; /* only change is here "%" to "vw" ! */
    height: 100vh; /* only change is here "%" to "vh" ! */
}

<ul>
    <li>
        <img src="#">
        <div class="outer-wrapper">
            <div class="inner-wrapper">
                <h1>My Title</h1>
                <h5>Subtitle</h5>
            </div>
        </div>
    </li>
</ul>


来源: stackexchange

问:
Returning subclass of parameterized type in Scala
I'm trying to return a subclass of a parameterized type Output[T <: Input] but for some reason I cannot seem to get the syntax right:

```<code>sealed trait Input
case class A(id: Int) extends Input
case class B(id: String) extends Input

sealed trait Output[+T <: Input]
case class OutA(some: String) extends Output[A]
case class OutB(thing: Int) extends Output[B]

def doStuff[T <: Input, RT <: Output[T]](input: T): RT =
  input match {
    case A(i) => OutA(i.toString)
    case B(s) => OutB(s.toInt)
  }

// error: type mismatch;
//  found   : OutA
//  required: RT
//            case A(i) => OutA(i.toString)
//
// error: type mismatch;
//  found   : OutB
//  required: RT
//            case B(s) => OutB(s.toInt)

def doStuff[T <: Input](input: T): Output[T] =
  input match {
    case A(i) => OutA(i.toString)
    case B(s) => OutB(s.toInt)
  }

// error: type mismatch;
//  found   : OutA
//  required: Output[T]
//            case A(i) => OutA(i.toString)

// error: type mismatch;
//  found   : OutB
//  required: Output[T]
//            case B(s) => OutB(s.toInt)

def doStuff[T <: Input, RT <: Output[_]](input: T): RT =
  input match {
    case A(i) => OutA(i.toString)
    case B(s) => OutB(s.toInt)
  }

// error: type mismatch;
//  found   : OutA
//  required: RT
//            case A(i) => OutA(i.toString)

// error: type mismatch;
//  found   : OutB
//  required: RT
//            case B(s) => OutB(s.toInt)
</code>```

In my actual code the Input and Output subclasses are wrapped in containers that I cannot modify and the input is also coming from another system over which I have no control. However, this seems to be the smallest example I could come up with for which I get the same compile-time type errors.

How can I solve my problem?

答:
You can do it this way (this is an example of a type class in Scala, searching for this term will give you quite a few posts explaining the pattern):

```<code>case class StuffDoer[T](doStuff: T => Output[T])
object StuffDoer {
  implicit val ADoer: StuffDoer[A] = StuffDoer(x => OutA(x.id.toString))
  implicit val BDoer: StuffDoer[B] = StuffDoer(x => OutB(x.id.toInt))
  implicit val InputDoer: StuffDoer[Input] = StuffDoer {
    case a: A => ADoer.doStuff(a)
    case b: B => BDoer.doStuff(b)
  }
}

def doStuff[T](input: T)(implicit doer: StuffDoer[T]) = doer.doStuff(input)
</code>```

(Really, some variation of this problem is asked from time to time, but writing the answer is faster than searching for previous questions.)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to return a subclass of a parameterized type Output[T <: Input] but for some reason I cannot seem to get the syntax right:

sealed trait Input
case class A(id: Int) extends Input
case class B(id: String) extends Input

sealed trait Output[+T <: Input]
case class OutA(some: String) extends Output[A]
case class OutB(thing: Int) extends Output[B]

def doStuff[T <: Input, RT <: Output[T]](input: T): RT =
  input match {
    case A(i) => OutA(i.toString)
    case B(s) => OutB(s.toInt)
  }

// error: type mismatch;
//  found   : OutA
//  required: RT
//            case A(i) => OutA(i.toString)
//
// error: type mismatch;
//  found   : OutB
//  required: RT
//            case B(s) => OutB(s.toInt)

def doStuff[T <: Input](input: T): Output[T] =
  input match {
    case A(i) => OutA(i.toString)
    case B(s) => OutB(s.toInt)
  }

// error: type mismatch;
//  found   : OutA
//  required: Output[T]
//            case A(i) => OutA(i.toString)

// error: type mismatch;
//  found   : OutB
//  required: Output[T]
//            case B(s) => OutB(s.toInt)

def doStuff[T <: Input, RT <: Output[_]](input: T): RT =
  input match {
    case A(i) => OutA(i.toString)
    case B(s) => OutB(s.toInt)
  }

// error: type mismatch;
//  found   : OutA
//  required: RT
//            case A(i) => OutA(i.toString)

// error: type mismatch;
//  found   : OutB
//  required: RT
//            case B(s) => OutB(s.toInt)

In my actual code the Input and Output subclasses are wrapped in containers that I cannot modify and the input is also coming from another system over which I have no control. However, this seems to be the smallest example I could come up with for which I get the same compile-time type errors.

How can I solve my problem?

Body:
You can do it this way (this is an example of a type class in Scala, searching for this term will give you quite a few posts explaining the pattern):

case class StuffDoer[T](doStuff: T => Output[T])
object StuffDoer {
  implicit val ADoer: StuffDoer[A] = StuffDoer(x => OutA(x.id.toString))
  implicit val BDoer: StuffDoer[B] = StuffDoer(x => OutB(x.id.toInt))
  implicit val InputDoer: StuffDoer[Input] = StuffDoer {
    case a: A => ADoer.doStuff(a)
    case b: B => BDoer.doStuff(b)
  }
}

def doStuff[T](input: T)(implicit doer: StuffDoer[T]) = doer.doStuff(input)

(Really, some variation of this problem is asked from time to time, but writing the answer is faster than searching for previous questions.)


问:
Swift 3 live microphone levels capture
I'm trying to capture the levels coming in from the phones microphone. I am setting up a app so a user can create voice memos. I have the code setup to record the memos and save them on the phone I am now trying to set up a sound wave to animate the view when the user is typing.

I have started using the library SwiftSiriWaveformView which is working very well. Now I just need to figure out how to capture the microphone level.

I have created a method

```<code>internal func refreshAudioView(_:Timer) {
    if self.recorder == nil {
        self.endTimer()

        return
    }

    print("Average Power: \(CGFloat(self.recorder.averagePower(forChannel: 0)))")
}
</code>```

Which is added to a timer in this method

```<code>@IBAction func startRecordingPressed(_ sender: UIButton) {
    if self.recorder != nil {
        //if here it means that the record button was double clicked
        return
    }
    self.filename = "wnw-voice-memo\(getDateFormatter("dd-MM-y_hmmss").string(from: Date())).m4a"
    self.url = getDocumentsDirectory().appendingPathComponent(self.filename)
    print(self.url)

    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

    do {
        self.recorder = try AVAudioRecorder(url: self.url, settings: settings)
        self.recorder.delegate = self
        self.recorder.record()

        timer = Timer.scheduledTimer(timeInterval: 0.009, target: self, selector: #selector(refreshAudioView(_:)), userInfo: nil, repeats: true)
    } catch {
        //failed to record!
    }
}
</code>```

However when I run the app the average power is only ever shows as Average Power: -160.0

I have tried researching this but I have only found other solutions related to generating an audio wave from a save file, not from a live stream.

Does anyone know how I can get the current microphone levels?

答: Set recorder.meteringEnabled = true and in refreshAudioView call recorder. updateMeters() before accessing peakPowerForChannel & averagePowerForChannel. Also try to read power of channel 1 in addition to channel 0 you already monitoring.

Title: Swift 3 live microphone levels capture

Body:
I'm trying to capture the levels coming in from the phones microphone. I am setting up a app so a user can create voice memos. I have the code setup to record the memos and save them on the phone I am now trying to set up a sound wave to animate the view when the user is typing.

I have started using the library SwiftSiriWaveformView which is working very well. Now I just need to figure out how to capture the microphone level.

I have created a method

internal func refreshAudioView(_:Timer) {
    if self.recorder == nil {
        self.endTimer()

        return
    }

    print("Average Power: \(CGFloat(self.recorder.averagePower(forChannel: 0)))")
}

Which is added to a timer in this method

@IBAction func startRecordingPressed(_ sender: UIButton) {
    if self.recorder != nil {
        //if here it means that the record button was double clicked
        return
    }
    self.filename = "wnw-voice-memo\(getDateFormatter("dd-MM-y_hmmss").string(from: Date())).m4a"
    self.url = getDocumentsDirectory().appendingPathComponent(self.filename)
    print(self.url)

    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

    do {
        self.recorder = try AVAudioRecorder(url: self.url, settings: settings)
        self.recorder.delegate = self
        self.recorder.record()

        timer = Timer.scheduledTimer(timeInterval: 0.009, target: self, selector: #selector(refreshAudioView(_:)), userInfo: nil, repeats: true)
    } catch {
        //failed to record!
    }
}

However when I run the app the average power is only ever shows as Average Power: -160.0

I have tried researching this but I have only found other solutions related to generating an audio wave from a save file, not from a live stream.

Does anyone know how I can get the current microphone levels?


问:
Vertical align input and button without bootstrap
I wonder what's the best way to vertically align an input field and a button without Bootstrap.

Here's how it looks right know:

Some code:

```<code><!doctype html>
        <title>Postnummer</title>
      <div class="container-fluid">
          <div class="divider"></div>
          <div class="row">
              <div class="col-md-12">
                  <form class="navbar-form">
                    <div class="input-group">
                      <input style="height:50px; color: black; border-radius: 0px;" type="number"  id="searchZipCode"class="form-control" placeholder="Sök postnummer">
                      <div class="input-group-btn">
                      <a id="submitBtn">
                        <button style="height:50px; border-radius: 0px" type="button" click="submitZipCode()" class="btn btn-default"><i class="fa fa-search fa-2x"></i></button>
                      </a>
                      </div>
                    </div>
                  </form>
              </div>
          </div>
    </div>
</code>```

Fiddle: https://jsfiddle.net/5mxzu4m5/

I want the the icon on the right side of the input field. Really grateful for all the answers! :)

答:
Simple and Sleek Solution:
Replace src="..." with your link

HTML

```<code><div>
<input type="text" id="text1">
<br>
<img src="http://findicons.com/files/icons/1264/clearblack/128/find.png" height="50px" width="50px">
</div>
</code>```

CSS

```<code>img{
  float:right;
}
div{
  width:90px;
}
</code>```

Body:
I wonder what's the best way to vertically align an input field and a button without Bootstrap.

Here's how it looks right know:

Some code:

<!doctype html>
        <title>Postnummer</title>

                  <form class="navbar-form">

                      <input style="height:50px; color: black; border-radius: 0px;" type="number"  id="searchZipCode"class="form-control" placeholder="Sök postnummer">

                        <button style="height:50px; border-radius: 0px" type="button" click="submitZipCode()" class="btn btn-default"></button>

                  </form>

Fiddle: https://jsfiddle.net/5mxzu4m5/

I want the the icon on the right side of the input field. Really grateful for all the answers! :)

Body:
Simple and Sleek Solution:
Replace src="..." with your link

HTML

<div>
<input type="text" id="text1">
<br>
<img src="http://findicons.com/files/icons/1264/clearblack/128/find.png" height="50px" width="50px">
</div>

CSS

img{
  float:right;
}
div{
  width:90px;
}


问:
SystemVerilog - how to use string as event or as time?
I have a transaction which contains:

```<code>string delay;
string delay_type;
</code>```

If delay_type == "time", the delay will have the following structure:
"3ns" (number and time unit).

If delay_type == "event", the delay will have the following structure:
"@(posedge clk)" (@(posedge/negdge of signal)).

How can I use this in the bfm?

For example, in case of delay_type == "time", I want to be able to do:
#3ns (where 3ns is the delay string).

And  in case of delay_type == "event", I want to be able to wait for the event (for example for the posedge of some signal).

答: You would be better off trying to convert the text file of transactions you are reading directly to SystemVerilog. Or if you have a limited number of events, encoding them into sothing you can branch into a case statement might be feasible. </p>

Body:
I have a transaction which contains:

string delay;
string delay_type;

If delay_type == "time", the delay will have the following structure:
"3ns" (number and time unit).

If delay_type == "event", the delay will have the following structure:
"@(posedge clk)" (@(posedge/negdge of signal)).

How can I use this in the bfm?

For example, in case of delay_type == "time", I want to be able to do:
#3ns (where 3ns is the delay string).

And  in case of delay_type == "event", I want to be able to wait for the event (for example for the posedge of some signal).


问:
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

```<code>int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}
</code>```

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

```<code>int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
</code>```

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

答:
In my opinion both ways are fine, but the second one is "prettier".

In programing it is important to write the code in the easiest way you can think of, and make it simple for other programmers to understand your code if you'll be replaced or for any other reason.

There is no complexity issue involved with your two codes so they are both fine as I said, but the think I don't like about the first code is the use of 'return' statment without any real need of 'return' statment here.

There is another way writing this code, better then your way (in my opinion), but not better as your teacher's one.

```<code>int main()
{
    bool ShouldExit = false;
    while ( true )
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") break;
    }
}
</code>```

Another main reason why I don't like your first code and my code above is because of the use of infinite loop, when you make yourself used to infinite loops it is just a matter of time until you will make your more complicated programs with major bugs in it.

Again - all of the things I wrote are in my opinion only and not gospel truth.

Rotem

ContentLicense: CC BY-SA 2.5

Body:
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

Body:
In my opinion both ways are fine, but the second one is "prettier".

In programing it is important to write the code in the easiest way you can think of, and make it simple for other programmers to understand your code if you'll be replaced or for any other reason.

There is no complexity issue involved with your two codes so they are both fine as I said, but the think I don't like about the first code is the use of 'return' statment without any real need of 'return' statment here.

There is another way writing this code, better then your way (in my opinion), but not better as your teacher's one.

int main()
{
    bool ShouldExit = false;
    while ( true )
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") break;
    }
}

Another main reason why I don't like your first code and my code above is because of the use of infinite loop, when you make yourself used to infinite loops it is just a matter of time until you will make your more complicated programs with major bugs in it.

Again - all of the things I wrote are in my opinion only and not gospel truth.

Rotem


问:
Python: for loops: using an index from a list and another index from another list
I would like to loop as something like:

```<code>for j in range(1,4) and for k in ['one', 'two', 'three']:
               print(str(j) + ' is written ' + k)
</code>```

I tried with and but it didn't work. How does someone get this effect?

And what would happen in the case that the two lists have different lengths? How could I still iterate through both of them?

答:
Check this out:</p>

```<code>for j,k in enumerate(['one', 'two', 'three'], 1):
    print("{} is written {}".format(j, k))
</code>```

Body:
I would like to loop as something like:

for j in range(1,4) and for k in ['one', 'two', 'three']:
               print(str(j) + ' is written ' + k)

I tried with and but it didn't work. How does someone get this effect?

And what would happen in the case that the two lists have different lengths? How could I still iterate through both of them?

Body:
Check this out:

for j,k in enumerate(['one', 'two', 'three'], 1):
    print("{} is written {}".format(j, k))


问:
Search for key inside dictionary and print values- Javascript
I have a dictionary that looks a little like this:

```<code>var index = {
  "Italian": [
    {
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [
    {
      "name": "Cosme",
      "rating": "5.0"
    }
  ]
}
</code>```

I also have a search bar that people can enter queries into. What I want to do is take the query and search for it inside index.

Example: search = "italian", results = {"name": "Il Brigante", "rating": "5.0"}, {"name": "Giardino Doro Ristorante", "rating": "5.0"}

Is that kind of search possible? Any help would be appreciated. Thanks so much in advance. Happy 4th!

Cheers,
Theoi

答:
Check out square-bracket-notation.

This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).

Source with examples

Applying this to your problem:

var index = {
  "Italian": [
    {
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [
    {
      "name": "Cosme",
      "rating": "5.0"
    }
  ]
}

var query = "Italian"
var result = index[query]

console.log(index["Italian"])```

Body:
I have a dictionary that looks a little like this:

var index = {
  "Italian": [
    {
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [
    {
      "name": "Cosme",
      "rating": "5.0"
    }
  ]
}

I also have a search bar that people can enter queries into. What I want to do is take the query and search for it inside index.

Example: search = "italian", results = {"name": "Il Brigante", "rating": "5.0"}, {"name": "Giardino Doro Ristorante", "rating": "5.0"}

Is that kind of search possible? Any help would be appreciated. Thanks so much in advance. Happy 4th!

Cheers,
Theoi


问:
ubuntu 16 python cannot import tensor flow after successfully installed
After installing python anaconda and then tensorflow according to tf documentation https://www.tensorflow.org/install/install_linux
when opening ipython and type

```<code>import tensorflow as tf
</code>```

I get the error message:

```<code>ModuleNotFoundError: No module named 'tensorflow'
</code>```

Any help appriciated

答:
Most likely it's because your python alias on Ubuntu isn't pointing at the same version/installation of Python for which you have actually installed Tensorflow.

Run python -V to see which Python version the alias actually points to and compare that with what you originally thought you installed TF for.

Body:
After installing python anaconda and then tensorflow according to tf documentation https://www.tensorflow.org/install/install_linux
when opening ipython and type

import tensorflow as tf

I get the error message:

ModuleNotFoundError: No module named 'tensorflow'

Any help appriciated


问:
Search word from text file
I have maybe pretty easy question because I'm new but I did not find any answer for it from google. Idea is search some words from the text file.

Here is the code:

```<code>private void button6_Click(object sender, EventArgs e)
{
    DialogResult result = openFileDialog2.ShowDialog();
    if (result == DialogResult.OK)
    {
        string file = openFileDialog2.FileName;
        try
        {
            string text = File.ReadAllText(file);
        }
        catch (IOException)
        {
        }
    }
}

private void button5_Click(object sender, EventArgs e)
{
    //Search from selected .txt file like: ("a"), ("b"), ("c")
}
</code>```

My English is bad so hopefully you get it and thanks for even trying to help me :)!

答: You can read the whole text as a string (as you did) and then use either String.IndexOf() to get the index of the word (-1 if not found) or use Regular Expressions for that.

Title: Search word from text file

Body:
I have maybe pretty easy question because I'm new but I did not find any answer for it from google. Idea is search some words from the text file.

Here is the code:

private void button6_Click(object sender, EventArgs e)
{
    DialogResult result = openFileDialog2.ShowDialog();
    if (result == DialogResult.OK)
    {
        string file = openFileDialog2.FileName;
        try
        {
            string text = File.ReadAllText(file);
        }
        catch (IOException)
        {
        }
    }
}

private void button5_Click(object sender, EventArgs e)
{
    //Search from selected .txt file like: ("a"), ("b"), ("c")
}

My English is bad so hopefully you get it and thanks for even trying to help me :)!


问:
how to replace two same keys array and make none set keys empty
Let say we have 2 flowing arrays

```<code>$arr1= array('a' => "XL");
$arr2= array('a' => "XLd",'b'=>"CDW");
</code>```

i need to assign $arr1 to $arr2  and make other keys empty whith a builtin function not foreach.

It should looks as bellow:

```<code>array(2) { ['a']=> string(2) "XL" ['b']=> string(0) ""}
</code>```

thanks

答:
If I understand your question correctly, this should do:</p>

```<code>$out = array_merge(
    $arr2,
    array_fill_keys(array_keys($arr2), ''),
    $arr1
);
</code>```

Body:
Let say we have 2 flowing arrays

$arr1= array('a' => "XL");
$arr2= array('a' => "XLd",'b'=>"CDW");

i need to assign $arr1 to $arr2  and make other keys empty whith a builtin function not foreach.

It should looks as bellow:

array(2) { ['a']=> string(2) "XL" ['b']=> string(0) ""}

thanks

Body:
If I understand your question correctly, this should do:

$out = array_merge(
    $arr2,
    array_fill_keys(array_keys($arr2), ''),
    $arr1
);


问:
How to use IMAP in Google App engine (Java)
We are trying to use IMAP in our web app which is running on Google App enigne (GAE) , we are using java version of GAE.

By default GAE included javax.mail packages in their sdk but they not included IMAP protocol packages.

So we try to add java mail library to our app to get IMAP packges but this library not compatible with app engine java sdk javax.mail packages because this library also having javax.mail packages with differences in code compare to appengine sdk javax.mail packages.

so what is the best way to use IMAP in Java version of app engine ??

答:
I recently needed to send email from AppEngine using IMAP and this worked for me.
I've added this libraries:

```<code>    <!-- https://mvnrepository.com/artifact/javax.activation/activation -->
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.6.0-rc2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.sun.mail/smtp -->
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>smtp</artifactId>
        <version>1.6.0-rc2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.6.0-rc2</version>
    </dependency>
</code>```

And this is the code:

```<code>package ro.cbn.it.call.utils;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

import com.sun.mail.smtp.SMTPTransport;

import java.util.Properties;

public class MailUtils {

    public static void sendEmail(String userId, String password, String messageBody, String fromEmail, String messageSubject, String messageToAddress) throws MessagingException {
        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.required", "true");
        props.put("mail.smtp.sasl.enable", "false");
        Session session = Session.getInstance(props);
        //session.setDebug(true);
        final URLName unusedUrlName = null;
        SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
        // If the password is non-null, SMTP tries to do AUTH LOGIN.
        transport.connect("smtp.gmail.com", 587, userId, password);
        MimeMessage message = new MimeMessage(session);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(messageBody.getBytes(), "text/plain"));
        message.setSender(new InternetAddress(fromEmail));
        message.setSubject(messageSubject);
        message.setDataHandler(handler);
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(messageToAddress));
        transport.sendMessage(message, message.getAllRecipients());

        System.out.println("SentTo:"+messageToAddress);
    }
}
</code>```

Body:
I recently needed to send email from AppEngine using IMAP and this worked for me.
I've added this libraries:

    <!-- https://mvnrepository.com/artifact/javax.activation/activation -->
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.6.0-rc2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.sun.mail/smtp -->
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>smtp</artifactId>
        <version>1.6.0-rc2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.6.0-rc2</version>
    </dependency>

And this is the code:

package ro.cbn.it.call.utils;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

import com.sun.mail.smtp.SMTPTransport;

import java.util.Properties;

public class MailUtils {

    public static void sendEmail(String userId, String password, String messageBody, String fromEmail, String messageSubject, String messageToAddress) throws MessagingException {
        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.required", "true");
        props.put("mail.smtp.sasl.enable", "false");
        Session session = Session.getInstance(props);
        //session.setDebug(true);
        final URLName unusedUrlName = null;
        SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
        // If the password is non-null, SMTP tries to do AUTH LOGIN.
        transport.connect("smtp.gmail.com", 587, userId, password);
        MimeMessage message = new MimeMessage(session);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(messageBody.getBytes(), "text/plain"));
        message.setSender(new InternetAddress(fromEmail));
        message.setSubject(messageSubject);
        message.setDataHandler(handler);
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(messageToAddress));
        transport.sendMessage(message, message.getAllRecipients());

        System.out.println("SentTo:"+messageToAddress);
    }
}


问:
When to use supervised or unsupervised learning?

Which are the fundamental criterias for using supervised or unsupervised learning?

When is one better than the other?

Is there specific cases when you can only use one of them?

Thanks

答:
If you a have labeled dataset you can use both. If you have no labels you only can use unsupervised learning.

It´s not a question of "better". It´s a question of what you want to achieve. E.g. clustering data is usually unsupervised – you want the algorithm to tell you how your data is structured. Categorizing is supervised since you need to teach your algorithm what is what in order to make predictions on unseen data.

See 1.

On a side note: These are very broad questions. I suggest you familiarize yourself with some ML foundations.

Good podcast for example here: http://ocdevel.com/podcasts/machine-learning

Very good book / notebooks by Jake VanderPlas: http://nbviewer.jupyter.org/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/Index.ipynb


问:
How to create an array of non-const C strings on the stack without repetitive code in C++03?
I'm writing a unit test for a module that takes an array of mutable C strings in C++03 with getopt. The function argument is char*const[]. I want to create the arguments on the stack inside the function. My current solution is:

```<code>char args_stor[][1024] = {
    "parser",
    "-o",
    "SomeValue"
};
char* args[] = {
    args_stor[0],
    args_stor[1],
    args_stor[2]
};
</code>```

How can I avoid the repetitive part, and if possible, transform it into one statement?

The function declaration is:

```<code>int getopt(int argc, char* const argv[], const char *optstring);
</code>```

Use case is therefore:

```<code>getopt(3, args, ":o:");
</code>```

答:
I don't think that you can do that. getopt  requires char * const[]. The only improvement you can make is to use separate char[] declarations for each argument instead of the 2D array. This way you only allocate the needed space:

```<code>char opt1[] = "parser";
char opt2[] = "-o";
char *args[] = { opt1, opt2 };
</code>```

Body:
I'm writing a unit test for a module that takes an array of mutable C strings in C++03 with getopt. The function argument is char*const[]. I want to create the arguments on the stack inside the function. My current solution is:

char args_stor[][1024] = {
    "parser",
    "-o",
    "SomeValue"
};
char* args[] = {
    args_stor[0],
    args_stor[1],
    args_stor[2]
};

How can I avoid the repetitive part, and if possible, transform it into one statement?

The function declaration is:

int getopt(int argc, char* const argv[], const char *optstring);

Use case is therefore:

getopt(3, args, ":o:");

Body:
I don't think that you can do that. getopt  requires char * const[]. The only improvement you can make is to use separate char[] declarations for each argument instead of the 2D array. This way you only allocate the needed space:

char opt1[] = "parser";
char opt2[] = "-o";
char *args[] = { opt1, opt2 };


问:
CMake: how to get the backslash literal in Regexp replace?
I am trying to replace forwardslashes with backslashes.
To do that i have the following line of code:

```<code>STRING(REGEX REPLACE "/" "\\" SourceGroup ${SourceGroupPath} )
</code>```

SourceGroupPath = A/File/Path.
SourceGroup is the variable to set the result to.

The problem i am having is with, the "\\" part to the code.
I have tried several ways to getting to use the backslash literal like "\\"
and using unicode but nothing seems to work.

The error i get in CMake is:

CMake Error at CMakeLists.txt:41
  (STRING):   string sub-command REGEX,
  mode REPLACE: replace-expression ends
  in a backslash.

Can someone please help me out?

Thanks,

Wouter

答:
The reason is that in a CMake string literal, the backslash is an escape character  (just like in C, Java or JavaScript) and in regex, the backslash is an escape character as well.

So to represent a regex as a string literal, you need double escaping. (That's why many "higher level" languages have regex literal notation, BTW.)

The string literal "\\" represents the in-memory string "\" and that's an invalid regex, hence the "ends in a backslash" error.

The string literal "\\\\" represents "\\" in memory which is a valid regex (representing a single backslash).

Body:
I am trying to replace forwardslashes with backslashes.
To do that i have the following line of code:

STRING(REGEX REPLACE "/" "\\" SourceGroup ${SourceGroupPath} )

SourceGroupPath = A/File/Path.
SourceGroup is the variable to set the result to.

The problem i am having is with, the "\\" part to the code.
I have tried several ways to getting to use the backslash literal like "\\"
and using unicode but nothing seems to work.

The error i get in CMake is:

CMake Error at CMakeLists.txt:41
  (STRING):   string sub-command REGEX,
  mode REPLACE: replace-expression ends
  in a backslash.

Can someone please help me out?

Thanks,

Wouter


问:
Spark 2.1 cannot write Vector field on CSV
I was migrating my code from Spark 2.0 to 2.1 when I stumbled into a problem related to Dataframe saving.

Here's the code

import org.apache.spark.sql.types._
import org.apache.spark.ml.linalg.VectorUDT
val df = spark.createDataFrame(Seq(Tuple1(1))).toDF("values")
val toSave = new org.apache.spark.ml.feature.VectorAssembler().setInputCols(Array("values")).transform(df)
toSave.write.csv(path)
```

<p>This code succeeds when using Spark 2.0.0</p>

<p>Using Spark 2.1.0.cloudera1, I get the following error : </p>

```java.lang.UnsupportedOperationException: CSV data source does not support struct<type:tinyint,size:int,indices:array<int>,values:array<double>> data type.
  at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat.org$apache$spark$sql$execution$datasources$csv$CSVFileFormat$$verifyType$1(CSVFileFormat.scala:233)
  at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat$$anonfun$verifySchema$1.apply(CSVFileFormat.scala:237)
  at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat$$anonfun$verifySchema$1.apply(CSVFileFormat.scala:237)
  at scala.collection.Iterator$class.foreach(Iterator.scala:893)
  at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
  at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
  at org.apache.spark.sql.types.StructType.foreach(StructType.scala:96)
  at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat.verifySchema(CSVFileFormat.scala:237)
  at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat.prepareWrite(CSVFileFormat.scala:121)
  at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:108)
  at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:101)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:58)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:56)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:74)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:114)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:114)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:135)
  at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
  at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:132)
  at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:113)
  at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:87)
  at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:87)
  at org.apache.spark.sql.execution.datasources.DataSource.writeInFileFormat(DataSource.scala:484)
  at org.apache.spark.sql.execution.datasources.DataSource.write(DataSource.scala:520)
  at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:215)
  at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:198)
  at org.apache.spark.sql.DataFrameWriter.csv(DataFrameWriter.scala:579)
  ... 50 elided
```

Is this only on my side ?

Is this related to the cloudera release of Spark 2.1 ? (from their repo, it seems they didn't mess with spark.sql so maybe not)

Thanks !

答:
As a workaround you can use the VectorDisassembler class from this fork, or take the solution described here.

I have used VectorDisassembler to store the resulting dataframe of the ml.feature.StandardScaler.fit method into a CSV.

The code looks roughly like this:

```<code>val disassembler = new org.apache.spark.ml.feature.VectorDisassembler()
val disassembledDF = disassembler.setInputCol("scaledFeatures").transform(df)
disassembledDF.show()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was migrating my code from Spark 2.0 to 2.1 when I stumbled into a problem related to Dataframe saving.

Here's the code

import org.apache.spark.sql.types._
import org.apache.spark.ml.linalg.VectorUDT
val df = spark.createDataFrame(Seq(Tuple1(1))).toDF("values")
val toSave = new org.apache.spark.ml.feature.VectorAssembler().setInputCols(Array("values")).transform(df)
toSave.write.csv(path)

This code succeeds when using Spark 2.0.0

Using Spark 2.1.0.cloudera1, I get the following error :

java.lang.UnsupportedOperationException: CSV data source does not support struct<type:tinyint,size:int,indices:array<int>,values:array<double>> data type.
  at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat.org$apache$spark$sql$execution$datasources$csv$CSVFileFormat$$verifyType$1(CSVFileFormat.scala:233)
  at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat$$anonfun$verifySchema$1.apply(CSVFileFormat.scala:237)
  at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat$$anonfun$verifySchema$1.apply(CSVFileFormat.scala:237)
  at scala.collection.Iterator$class.foreach(Iterator.scala:893)
  at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
  at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
  at org.apache.spark.sql.types.StructType.foreach(StructType.scala:96)
  at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat.verifySchema(CSVFileFormat.scala:237)
  at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat.prepareWrite(CSVFileFormat.scala:121)
  at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:108)
  at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:101)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:58)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:56)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:74)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:114)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:114)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:135)
  at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
  at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:132)
  at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:113)
  at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:87)
  at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:87)
  at org.apache.spark.sql.execution.datasources.DataSource.writeInFileFormat(DataSource.scala:484)
  at org.apache.spark.sql.execution.datasources.DataSource.write(DataSource.scala:520)
  at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:215)
  at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:198)
  at org.apache.spark.sql.DataFrameWriter.csv(DataFrameWriter.scala:579)
  ... 50 elided

Is this only on my side ?

Is this related to the cloudera release of Spark 2.1 ? (from their repo, it seems they didn't mess with spark.sql so maybe not)

Thanks !

Body:
As a workaround you can use the VectorDisassembler class from this fork, or take the solution described here.

I have used VectorDisassembler to store the resulting dataframe of the ml.feature.StandardScaler.fit method into a CSV.

The code looks roughly like this:

val disassembler = new org.apache.spark.ml.feature.VectorDisassembler()
val disassembledDF = disassembler.setInputCol("scaledFeatures").transform(df)
disassembledDF.show()


问:
Adding Expression of JsonEqualTo to Ebean query
I have a Ebean Query object and would like to add an Object of type expression to the where clause

```<code>query.where().add(Expr.jsonEqualTo(,,,))
</code>```

Is there any way to do this?

```<code>query.where().add(Expr.eq(param, value))
</code>```

is possible for example

I am using EbeanORM 6.8.1 by the way

答:
Assuming you programatically want to add some conditions, you could write something like </p>

```<code>ExpressionList<Customer> query = Customer.find.where().eq("name", "John");
if (condition)
    query.eq("lastName", "Doe");
query.findList();
</code>```

Body:
I have a Ebean Query object and would like to add an Object of type expression to the where clause

query.where().add(Expr.jsonEqualTo(,,,))

Is there any way to do this?

query.where().add(Expr.eq(param, value))

is possible for example

I am using EbeanORM 6.8.1 by the way

Body:
Assuming you programatically want to add some conditions, you could write something like

ExpressionList<Customer> query = Customer.find.where().eq("name", "John");
if (condition)
    query.eq("lastName", "Doe");
query.findList();


问:
UIDatePicker date method is picking wrong date: iPhone Dev
I am getting very strange behaviour on UIDatePicker. I have a view with date picker declared in .h file as  IBOutlet UIDatePicker *datePicker; with property nonatomic and retain. datePicker is properly linked in IB file.

In the code I am setting the minimum, maximum, initial date and action to call for UICOntrolEventValueChanged using following code

```<code>If (!currentDate) {
    initialDate = [NSDate date];
} else {
    initialDate = currentdate;
}

[datePicker setMinimumDate:[NSDate date]];
[datePicker setMaximumDate:[[NSDate date] addTimeInterval:5 * 365.25 * 24 * 60 * 60]]; // to get upto 5 years
[datePicker setDate:initialDate animated:YES];

[datePicker addTarget:self action:@selector(getDatePickerValue:) forControlEvents:UIControlEventValueChanged];
</code>```

In getDatePickerValue, I get the new date using datePicker.date.

When the view is closed (using a done button), I get the current value of the date using datePicker.date.

Now if the view is called with no 'currentDate', the picker returns 'todays date'. This is what happens the 'first' time my pickerView is called. Each subsequent call to the view, with no 'current date' gives me a different and later date from today. So,

first time I get today's date say 9 Jun 2010

   second time datePicker.date returns 10 Jun 2010

   third time 11 Jun 2010 and so on. Though its not always incremental, but mostly it is.

I have put NSLogs, and verified the initial date is set correctly.

The problem is only on the device (on OS 3.0), the issue is not replicated on simulator.

I can't find what I have done wrong. I hope somebody else has come across similar problem and can help me resolve this.

答:
```<code>IBOUTLET UIDatePicker *datePicker;
IBOUTLET UILabel *label;
}
-(void)click:(id)sender;

- (void)viewDidLoad {

    [super viewDidLoad];
    NSDate *dateFromPicker = [[NSDate alloc]init];
    [date setDate:dat animated:YES];
}
-(void)click:(id)sender {

    NSDate *selectDate = [datePicker date];
    NSString *dateString = [NSString stringWithFormat:@"%@",selectDate];

    [label setText:dateString];
}
</code>```

this will work,

Body:
I am getting very strange behaviour on UIDatePicker. I have a view with date picker declared in .h file as  IBOutlet UIDatePicker *datePicker; with property nonatomic and retain. datePicker is properly linked in IB file.

In the code I am setting the minimum, maximum, initial date and action to call for UICOntrolEventValueChanged using following code

If (!currentDate) {
    initialDate = [NSDate date];
} else {
    initialDate = currentdate;
}

[datePicker setMinimumDate:[NSDate date]];
[datePicker setMaximumDate:[[NSDate date] addTimeInterval:5 * 365.25 * 24 * 60 * 60]]; // to get upto 5 years
[datePicker setDate:initialDate animated:YES];

[datePicker addTarget:self action:@selector(getDatePickerValue:) forControlEvents:UIControlEventValueChanged];

In getDatePickerValue, I get the new date using datePicker.date.

When the view is closed (using a done button), I get the current value of the date using datePicker.date.

Now if the view is called with no 'currentDate', the picker returns 'todays date'. This is what happens the 'first' time my pickerView is called. Each subsequent call to the view, with no 'current date' gives me a different and later date from today. So,

first time I get today's date say 9 Jun 2010

   second time datePicker.date returns 10 Jun 2010

   third time 11 Jun 2010 and so on. Though its not always incremental, but mostly it is.

I have put NSLogs, and verified the initial date is set correctly.

The problem is only on the device (on OS 3.0), the issue is not replicated on simulator.

I can't find what I have done wrong. I hope somebody else has come across similar problem and can help me resolve this.

Body:
IBOUTLET UIDatePicker *datePicker;
IBOUTLET UILabel *label;
}
-(void)click:(id)sender;

- (void)viewDidLoad {

    [super viewDidLoad];
    NSDate *dateFromPicker = [[NSDate alloc]init];
    [date setDate:dat animated:YES];
}
-(void)click:(id)sender {

    NSDate *selectDate = [datePicker date];
    NSString *dateString = [NSString stringWithFormat:@"%@",selectDate];

    [label setText:dateString];
}

this will work,


问:
Change the state of the condition variable for a while loop outside the while loop
I am currently trying to start and stop a while loop by a pressing a key  (start) and stopping by releasing the key.

So something like this:

```<code>from pynput import keyboard
global condition
condition = False

def on_press(key):
    global condition
    if key == keyboard.Key.cmd_r:
        print('pressed cmd_r'.format(key))
        condition = True
    else:
        print('incorrect character {0}, press cmd_r'.format(key))

def on_release(key):
    global condition
    print('{0} released'.format(key))
    if key == keyboard.Key.cmd_r:
        condition = False
        #keyboard.Listener.stop
        #return False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

while condition==True:
    print "Condition true"
</code>```

I am not sure why this is not working?..
It should in my head?

答:
You may need something like main loop where you can include your special while loop to achieve this.

Update 1 - How? (wrong)

```<code>while True:
    # main loop
    while condition:
        # your special loop
        # do something...
    time.sleep(0.1) # sleep 0.1 seconds
</code>```

The "main loop" is an infinite loop and executes included instructions every 0.1 second. Hence you provide the ability to keep checking the condition. If the condition == True your "special loop" is going to execute and it stops when the condition == False, and then  the "main loop" continues its execution.

Update 2 - The implementation (correct)

Ok, I've run the code and I see that the "main loop" solution isn't right here. For now, I have quick, tested solution, based on multithreading:

```<code>import time
import threading

from pynput import keyboard

condition = False

def my_special_task():
    global condition
    while condition:
        print("condition = %s" % condition)
        time.sleep(0.1)

def on_press(key):
    global condition
    if key == keyboard.Key.ctrl_r:
        print('Pressed ctrl_r')
        condition = True
        thread = threading.Thread(target=my_special_task)
        thread.start()
    else:
        print("Incorrect KEY: %s, press ctrl_r instead" % key)

def on_release(key):
    global condition
    print("%s released" % key)
    if key == keyboard.Key.ctrl_r:
        condition = False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
</code>```

Body:
I am currently trying to start and stop a while loop by a pressing a key  (start) and stopping by releasing the key.

So something like this:

from pynput import keyboard
global condition
condition = False

def on_press(key):
    global condition
    if key == keyboard.Key.cmd_r:
        print('pressed cmd_r'.format(key))
        condition = True
    else:
        print('incorrect character {0}, press cmd_r'.format(key))

def on_release(key):
    global condition
    print('{0} released'.format(key))
    if key == keyboard.Key.cmd_r:
        condition = False
        #keyboard.Listener.stop
        #return False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

while condition==True:
    print "Condition true"

I am not sure why this is not working?..
It should in my head?

Body:
You may need something like main loop where you can include your special while loop to achieve this.

Update 1 - How? (wrong)

while True:
    # main loop
    while condition:
        # your special loop
        # do something...
    time.sleep(0.1) # sleep 0.1 seconds

The "main loop" is an infinite loop and executes included instructions every 0.1 second. Hence you provide the ability to keep checking the condition. If the condition == True your "special loop" is going to execute and it stops when the condition == False, and then  the "main loop" continues its execution.

Update 2 - The implementation (correct)

Ok, I've run the code and I see that the "main loop" solution isn't right here. For now, I have quick, tested solution, based on multithreading:

import time
import threading

from pynput import keyboard

condition = False

def my_special_task():
    global condition
    while condition:
        print("condition = %s" % condition)
        time.sleep(0.1)

def on_press(key):
    global condition
    if key == keyboard.Key.ctrl_r:
        print('Pressed ctrl_r')
        condition = True
        thread = threading.Thread(target=my_special_task)
        thread.start()
    else:
        print("Incorrect KEY: %s, press ctrl_r instead" % key)

def on_release(key):
    global condition
    print("%s released" % key)
    if key == keyboard.Key.ctrl_r:
        condition = False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()


问:
Conditionally replace elements of a vector based on an index
It's best explained with an example.

I have a vector, or column from data.frame named vec:

```<code>vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

```<code>c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)
</code>```

If we had:

```<code>vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

The end vector would look like:

```<code>c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)
</code>```

A very badly written solution is:

```<code>vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}
</code>```

答:
Another option:

```<code>`[<-`(vec,c(outer(which(vec==1),1:3,"+")),1)
# [1] NA NA  1  1  1  1 NA  1  1  1  1 NA NA NA
</code>```

Although the above works with the examples, it stretches the length of vec if a 1 is found in the last positions. Better to make a simple check and wrap into a function:

```<code>threeNAs<-function(vec) {
    ind<-c(outer(which(vec==1),1:3,"+"))
    ind<-ind[ind<=length(vec)]
    `[<-`(vec,ind,1)
}
</code>```

Body:
It's best explained with an example.

I have a vector, or column from data.frame named vec:

vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)

If we had:

vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)

The end vector would look like:

c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)

A very badly written solution is:

vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}

Body:
Another option:

`[<-`(vec,c(outer(which(vec==1),1:3,"+")),1)
# [1] NA NA  1  1  1  1 NA  1  1  1  1 NA NA NA

Although the above works with the examples, it stretches the length of vec if a 1 is found in the last positions. Better to make a simple check and wrap into a function:

threeNAs<-function(vec) {
    ind<-c(outer(which(vec==1),1:3,"+"))
    ind<-ind[ind<=length(vec)]
    `[<-`(vec,ind,1)
}


问:
TYPO3 Remove "Select & Upload Files" button
Removing the "Select & Upload Files" button from Page properties works with the following line in PageTSConfig:

```<code>TCEFORM.pages.media.config.appearance.fileUploadAllowed = 0
</code>```

Now I want to remove the "Select & Upload Files" button within content elements (for example with CType "textmedia"), too.

I tried out several things, but with no success. I found no working PageTSConfig "rule" for this case. Does somebody know how the "Select & Upload Files" button can be removed for content elements like textmedia elements?

Using TYPO3 8.7.1

答:
The code you use is always the same.

In PageTsConfig you have to use:

```<code>TCEFORM.[TABLE].[COLUMN].config.appearance.fileUploadAllowed = 0
</code>```

In TCA you have to use:

```<code>$GLOBALS['TCA']['TABLE']['columns']['COLUMN']['config']['appearance']['fileUploadAllowed'] = 0;
</code>```

You have to replace TABLE with the table you want to modify and COLUMN with the column you want to modify.

In page properties you have pages as TABLE and media as COLUMN.

In textmedia you have tt_content as TABLE and assets (i think) as COLUMN.

Body:
Removing the "Select & Upload Files" button from Page properties works with the following line in PageTSConfig:

TCEFORM.pages.media.config.appearance.fileUploadAllowed = 0

Now I want to remove the "Select & Upload Files" button within content elements (for example with CType "textmedia"), too.

I tried out several things, but with no success. I found no working PageTSConfig "rule" for this case. Does somebody know how the "Select & Upload Files" button can be removed for content elements like textmedia elements?

Using TYPO3 8.7.1

Body:
The code you use is always the same.

In PageTsConfig you have to use:

TCEFORM.[TABLE].[COLUMN].config.appearance.fileUploadAllowed = 0

In TCA you have to use:

$GLOBALS['TCA']['TABLE']['columns']['COLUMN']['config']['appearance']['fileUploadAllowed'] = 0;

You have to replace TABLE with the table you want to modify and COLUMN with the column you want to modify.

In page properties you have pages as TABLE and media as COLUMN.

In textmedia you have tt_content as TABLE and assets (i think) as COLUMN.


问:
How to pass prop to eventhandler?
I have 4 span with onClick={this.clickhandler}. Inside the clickhandler there is an audio which i'd like to play when clicked. The problem is, i want 4 different audio-urls inside the same clickhandler. How can i associate each span with an audio-string and pass it to the same eventhandler?

clickhander(e) {
    const audio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
    audio.play()
    console.dir(e.target)
}
render() {
    return(

Simon Game

                <Heart fill="#555"/>

                <Heart fill="#402" />

                <Heart fill="#f39" />

                <Heart fill="#29f" />

    )
}```
</div>
</div>
</p>

<p>EDIT: i tried the solutions below but i get this error:  The error you provided does not contain a stack trace.</p>

<p>this is my code now: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Home extends Component {

    constructor(props){
        super(props)
    }
    clickhander(e, url) {
        const str = url
        const audio = new Audio(String(str));
        audio.play()

    }
    render() {
        return(
            <div className="container">
                <h1 className="header">Simon Game</h1>
                <span  onClick={this.clickhander.bind(this, "https://s3.amazonaws.com/freecodecamp/simonSound1.mp3")}>
                    <Heart fill="#555"/>
                </span>
                <span onClick={this.clickhander}>
                    <Heart fill="#402" />
                </span>
                <span onClick={this.clickhander}>
                    <Heart fill="#f39" />
                </span>
                <span onClick={this.clickhander}>
                    <Heart fill="#29f" />
                </span>
            </div>
        )
    }
}

export default Home</code>```

答:
You can pass it as a second parameter to your handler:

clickhander(e, url) {
    const audio = new Audio(url);
    audio.play()
    console.dir(e.target)
}
render() {
    return(

Simon Game

             this.clickhander(e, "url1")}>
                <Heart fill="#555"/>

             this.clickhander(e, "url2")}>
                <Heart fill="#402" />

             this.clickhander(e, "url3")}>
                <Heart fill="#f39" />

             this.clickhander(e, "url4")}>
                <Heart fill="#29f" />

    )
}```

Title: How to pass prop to eventhandler?

Body:
I have 4 span with onClick={this.clickhandler}. Inside the clickhandler there is an audio which i'd like to play when clicked. The problem is, i want 4 different audio-urls inside the same clickhandler. How can i associate each span with an audio-string and pass it to the same eventhandler?

clickhander(e) {
    const audio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
    audio.play()
    console.dir(e.target)
}
render() {
    return(

Simon Game

                <Heart fill="#555"/>

                <Heart fill="#402" />

                <Heart fill="#f39" />

                <Heart fill="#29f" />

    )
}

EDIT: i tried the solutions below but i get this error:  The error you provided does not contain a stack trace.

this is my code now:

class Home extends Component {

    constructor(props){
        super(props)
    }
    clickhander(e, url) {
        const str = url
        const audio = new Audio(String(str));
        audio.play()

    }
    render() {
        return(

Simon Game

                    <Heart fill="#555"/>

                    <Heart fill="#402" />

                    <Heart fill="#f39" />

                    <Heart fill="#29f" />

        )
    }
}

export default Home

Body:
You can pass it as a second parameter to your handler:

clickhander(e, url) {
    const audio = new Audio(url);
    audio.play()
    console.dir(e.target)
}
render() {
    return(
        <div className="container">
            <h1 className="header">Simon Game</h1>
            <span  onClick={(e) => this.clickhander(e, "url1")}>
                <Heart fill="#555"/>
            </span>
            <span onClick={(e) => this.clickhander(e, "url2")}>
                <Heart fill="#402" />
            </span>
            <span onClick={(e) => this.clickhander(e, "url3")}>
                <Heart fill="#f39" />
            </span>
            <span onClick={(e) => this.clickhander(e, "url4")}>
                <Heart fill="#29f" />
            </span>
        </div>
    )
}


问:
Picking a Random Word from a list in python?
In Python 3, how would I print a random word from a list of words?</p>

答:
```<code>str='book pen paper pencil'
x=str.split()
print(x)
y=len(x)
import random
z=random.randrange(-1,y)
print(x[z])
</code>```


问:
Checking out tags on Git
I was going through some git internals and came across tags and how they're stored internally. In the Git SCM site I found the following:

Checking out Tags

You can’t really checkout a tag in Git, since they can’t be moved
  around. If you want to put a version of your repository in your
  working directory that looks like a specific tag, you can create a new
  branch at a specific tag with git checkout -b [branchname] [tagname]:

git checkout -b version2 v2.0.0

Switched to a new branch 'version2'

Of course if you do this and do a commit, your version2 branch will be
  slightly different than your v2.0.0 tag since it will move forward
  with your new changes, so do be careful.

I have the following doubts:

Why can't we check out tags? Can't we traverse the Git TAG to make HEAD point to the commit pointed to by the tag?

Can we create a new commit which will then point to the commit
pointed to by tag as the parent?

It is said that if we create a new branch from the tag and commit, it'll be slightly different. What difference are they talking about? Won't the new commit (assuming nothing has changed) refer to the tagged commit as its parent with everything else (trees & blobs) remaining the same?

Thank you.

EDIT:

I'm referring to cases where HEAD and the tag point to different commits.

答:
Why can't we check out tags?

We can!

Can't we traverse the Git TAG to make HEAD point to the commit pointed to by the tag?

Yes, we can do just that (though, strictly speaking, we don't even need much if any traversal: commits are snapshots, so we're done once we reach the right one, and tags generally require either zero or one intermediate steps to reach the commit).

The more typical state for the HEAD file—which is an actual file in .git named HEAD—is that it contains the name of a branch, rather than the ID of a commit.  This mode does not have much of a formal name, but I call it "being on a branch", to contrast it with the other mode.

The mode we get when .git/HEAD points directly to some commit (by containing its hash ID) is, as CodeWizard mentioned in a comment, called a "detached HEAD".  Since .git/HEAD no longer contains the name of a branch, we are now on no branch—or, equivalently, on some sort of unnamed branch, where we can use the @ symbol (since Git version 1.8.5) to name it, or by spelling out the word HEAD.  Of course HEAD is a fine name; it's just that Git will overwrite the contents of the .git/HEAD file as soon as we run git checkout master again, for instance, and then we will no longer have the hash ID stored anywhere.

Can we create a new commit which will then point to the commit pointed to by tag as the parent?

English is a bit ambiguous here, but I think a diagram makes it clearer that the answer is "yes":

```<code> initially: on branch `master` with commit `H` as the current commit

 ...--F--G     <-- tag: v2.0.0
          \
           H   <-- master (HEAD)
</code>```

Here, commit H points back to commit G; commit G points to commit F; and so on.  The branch named master points to commit H, and the tag name v2.0.0 points to commit G (either directly, if it's a lightweight tag, or through one annotated tag object, if it's an annotated tag).

```<code> After `git checkout v2.0.0`:

 ...--F--G     <-- HEAD, tag: v2.0.0
          \
           H   <-- master
</code>```

The .git/HEAD file now contains the hash ID of commit G.

```<code>If we make a new commit now:

           I   <-- HEAD
          /
 ...--F--G     <-- tag: v2.0.0
          \
           H   <-- master
</code>```

New commit I has commit G as its parent, as you suggested.  The .git/HEAD file now contains the hash ID of commit I.

It is said that if we create a new branch from the tag and commit, it'll be slightly different. What difference are they talking about? Won't the new commit (assuming nothing has changed) refer to the tagged commit as its parent with everything else (trees & blobs) remaining the same?

The commit contents would be identical, but the drawing of the commit graph would change a bit.  Here's the new graph drawings, starting from the same starting point, but using git checkout -b version2 v2.0.0 as the middle step.

```<code> initially: on branch `master` with commit `H` as the current commit

 ...--F--G     <-- tag: v2.0.0
          \
           H   <-- master (HEAD)

 After `git checkout -b version2 v2.0.0`:

 ...--F--G     <-- version2 (HEAD), tag: v2.0.0
          \
           H   <-- master

If we make a new commit now:

           I   <-- version2 (HEAD)
          /
 ...--F--G     <-- tag: v2.0.0
          \
           H   <-- master
</code>```

Note that in this case—the one where we are "on a branch" named version2—the branch name moves along with us as we make new commits.  When we are not on any branch, in the "detached HEAD" mode, new commits just update (the commit hash ID stored in) .git/HEAD.  But when .git/HEAD contains the name of a branch, those new commits update that branch.  The .git/HEAD file itself just continues to contain the name of the branch.

This, in fact, is what it means to be "on a branch": whenever .git/HEAD contains the name of the branch, various operations—specifically including making new commits and using git reset—change the hash ID the branch name remembers, rather than changing .git/HEAD itself.  Whenever .git/HEAD contains the hash ID of a commit, these same operations just update .git/HEAD itself.

The git checkout command usually updates the contents of .git/HEAD, and is one of the few commands that can change the branch name stored in .git/HEAD.  (I say "usually" here because git checkout is kind of a kitchen-sink command, having various modes that do oddball things just because they're closely related to the main thing that it usually does.)  Specifically, if you are on a branch, git checkout can put you on a different branch; if you're not on any branch, git checkout can get you onto one; if you use --detach or a tag name or similar, git checkout can put you into detached HEAD mode; and if you're not on any branch, git checkout can change which commit HEAD points to.

(The git reset command can do some of these things, but it won't take you on or off any branch.  Like git checkout, it's a bit "kitchen sinky": it has many things it can do and it is hard to describe these well without many words and several diagrams!)

Title: Checking out tags on Git

Body:
Why can't we check out tags?

We can!

Can't we traverse the Git TAG to make HEAD point to the commit pointed to by the tag?

Yes, we can do just that (though, strictly speaking, we don't even need much if any traversal: commits are snapshots, so we're done once we reach the right one, and tags generally require either zero or one intermediate steps to reach the commit).

The more typical state for the HEAD file—which is an actual file in .git named HEAD—is that it contains the name of a branch, rather than the ID of a commit.  This mode does not have much of a formal name, but I call it "being on a branch", to contrast it with the other mode.

The mode we get when .git/HEAD points directly to some commit (by containing its hash ID) is, as CodeWizard mentioned in a comment, called a "detached HEAD".  Since .git/HEAD no longer contains the name of a branch, we are now on no branch—or, equivalently, on some sort of unnamed branch, where we can use the @ symbol (since Git version 1.8.5) to name it, or by spelling out the word HEAD.  Of course HEAD is a fine name; it's just that Git will overwrite the contents of the .git/HEAD file as soon as we run git checkout master again, for instance, and then we will no longer have the hash ID stored anywhere.

Can we create a new commit which will then point to the commit pointed to by tag as the parent?

English is a bit ambiguous here, but I think a diagram makes it clearer that the answer is "yes":

 initially: on branch `master` with commit `H` as the current commit

 ...--F--G     <-- tag: v2.0.0
          \
           H   <-- master (HEAD)

Here, commit H points back to commit G; commit G points to commit F; and so on.  The branch named master points to commit H, and the tag name v2.0.0 points to commit G (either directly, if it's a lightweight tag, or through one annotated tag object, if it's an annotated tag).

 After `git checkout v2.0.0`:

 ...--F--G     <-- HEAD, tag: v2.0.0
          \
           H   <-- master

The .git/HEAD file now contains the hash ID of commit G.

If we make a new commit now:

           I   <-- HEAD
          /
 ...--F--G     <-- tag: v2.0.0
          \
           H   <-- master

New commit I has commit G as its parent, as you suggested.  The .git/HEAD file now contains the hash ID of commit I.

It is said that if we create a new branch from the tag and commit, it'll be slightly different. What difference are they talking about? Won't the new commit (assuming nothing has changed) refer to the tagged commit as its parent with everything else (trees & blobs) remaining the same?

The commit contents would be identical, but the drawing of the commit graph would change a bit.  Here's the new graph drawings, starting from the same starting point, but using git checkout -b version2 v2.0.0 as the middle step.

 initially: on branch `master` with commit `H` as the current commit

 ...--F--G     <-- tag: v2.0.0
          \
           H   <-- master (HEAD)

 After `git checkout -b version2 v2.0.0`:

 ...--F--G     <-- version2 (HEAD), tag: v2.0.0
          \
           H   <-- master

If we make a new commit now:

           I   <-- version2 (HEAD)
          /
 ...--F--G     <-- tag: v2.0.0
          \
           H   <-- master

Note that in this case—the one where we are "on a branch" named version2—the branch name moves along with us as we make new commits.  When we are not on any branch, in the "detached HEAD" mode, new commits just update (the commit hash ID stored in) .git/HEAD.  But when .git/HEAD contains the name of a branch, those new commits update that branch.  The .git/HEAD file itself just continues to contain the name of the branch.

This, in fact, is what it means to be "on a branch": whenever .git/HEAD contains the name of the branch, various operations—specifically including making new commits and using git reset—change the hash ID the branch name remembers, rather than changing .git/HEAD itself.  Whenever .git/HEAD contains the hash ID of a commit, these same operations just update .git/HEAD itself.

The git checkout command usually updates the contents of .git/HEAD, and is one of the few commands that can change the branch name stored in .git/HEAD.  (I say "usually" here because git checkout is kind of a kitchen-sink command, having various modes that do oddball things just because they're closely related to the main thing that it usually does.)  Specifically, if you are on a branch, git checkout can put you on a different branch; if you're not on any branch, git checkout can get you onto one; if you use --detach or a tag name or similar, git checkout can put you into detached HEAD mode; and if you're not on any branch, git checkout can change which commit HEAD points to.

(The git reset command can do some of these things, but it won't take you on or off any branch.  Like git checkout, it's a bit "kitchen sinky": it has many things it can do and it is hard to describe these well without many words and several diagrams!)


问:
Convert method to Delegate?
I want to call for example TryDo.Do(MessageBox.Show(""), null);

how can I do that??

```<code>using System;

namespace TryCatchHandlers
{
    public static class TryDo
    {
        public static CallResult Do(Delegate action, params object[] args)
        {
            try
            {
                return new CallResult (action.DynamicInvoke(args), action.Method.ReturnType, true);
            }
            catch
            {
                return new CallResult(null, null, false);
            }
        }
    }

    public class CallResult
    {
        public CallResult() { }

        internal CallResult(object result, Type resultType, bool isSuccessful)
        {
            Result = result;
            ResultType = resultType;
            IsSuccessful = isSuccessful;
        }
        public object Result { get; private set; }
        public Type ResultType { get; private set; }
        public bool IsSuccessful { get; private set; }
    }
}
</code>```

答:
Try this:</p>

```<code>Delegate d = (Action)delegate { MessageBox.Show(""); };
TryDo.Do(d, null);
</code>```

Title: Convert method to Delegate?

Body:
I want to call for example TryDo.Do(MessageBox.Show(""), null);

how can I do that??

using System;

namespace TryCatchHandlers
{
    public static class TryDo
    {
        public static CallResult Do(Delegate action, params object[] args)
        {
            try
            {
                return new CallResult (action.DynamicInvoke(args), action.Method.ReturnType, true);
            }
            catch
            {
                return new CallResult(null, null, false);
            }
        }
    }

    public class CallResult
    {
        public CallResult() { }

        internal CallResult(object result, Type resultType, bool isSuccessful)
        {
            Result = result;
            ResultType = resultType;
            IsSuccessful = isSuccessful;
        }
        public object Result { get; private set; }
        public Type ResultType { get; private set; }
        public bool IsSuccessful { get; private set; }
    }
}

Body:
Try this:

Delegate d = (Action)delegate { MessageBox.Show(""); };
TryDo.Do(d, null);


问:
How to Update Text of TextBlock in WPF
Whenever I am Trying to update my Text to TextBlock. It is throwing the following exception: "Object reference set to null".

My Code:

```<code><UniformGrid Grid.Row="1" Grid.Column="1" Height="30" >
    <Border DockPanel.Dock="Top">
        <TextBlock Foreground="White" TextAlignment="Justify" VerticalAlignment="Center" x:Name="TbcontentName" FontWeight="SemiBold"  />
    </Border>
</UniformGrid>
</code>```

i am using this TextBlock In another Window

```<code>if((setMainWindowCall.Try("TbcontentName") as TextBox).Text != null)
    (setMainWindowCall.FindName("TbcontentName") as TextBox).Text = _nameOfUc;
</code>```

答:
You are using ... as TextBox where you define TbcontentName to be a TextBlock in your XAML, so the dynamic cast returns null and a NullPointerException is thrown when you try to access the .Text-Property. Either change as TextBox to as TextBlock in your code or change

```<code><TextBlock ... x:Name="TbcontentName" ... />
</code>```

to

```<code><TextBox ... x:Name="TbcontentName" ... />
</code>```

Title: How to Update Text of TextBlock in WPF

Body:
Whenever I am Trying to update my Text to TextBlock. It is throwing the following exception: "Object reference set to null".

My Code:

<UniformGrid Grid.Row="1" Grid.Column="1" Height="30" >
    <Border DockPanel.Dock="Top">
        <TextBlock Foreground="White" TextAlignment="Justify" VerticalAlignment="Center" x:Name="TbcontentName" FontWeight="SemiBold"  />
    </Border>
</UniformGrid>

i am using this TextBlock In another Window

if((setMainWindowCall.Try("TbcontentName") as TextBox).Text != null)
    (setMainWindowCall.FindName("TbcontentName") as TextBox).Text = _nameOfUc;

Body:
You are using ... as TextBox where you define TbcontentName to be a TextBlock in your XAML, so the dynamic cast returns null and a NullPointerException is thrown when you try to access the .Text-Property. Either change as TextBox to as TextBlock in your code or change

<TextBlock ... x:Name="TbcontentName" ... />

to

<TextBox ... x:Name="TbcontentName" ... />


问:
Search for key inside dictionary and print values- Javascript
I have a dictionary that looks a little like this:

```<code>var index = {
  "Italian": [
    {
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [
    {
      "name": "Cosme",
      "rating": "5.0"
    }
  ]
}
</code>```

I also have a search bar that people can enter queries into. What I want to do is take the query and search for it inside index.

Example: search = "italian", results = {"name": "Il Brigante", "rating": "5.0"}, {"name": "Giardino Doro Ristorante", "rating": "5.0"}

Is that kind of search possible? Any help would be appreciated. Thanks so much in advance. Happy 4th!

Cheers,
Theoi

答:
I assume that there is no situation when we have indexes like 'itAlIaN'/ 'italian' / 'ITALIAN' so index is unique no matter if you have lower/upper case

var index = {
    "Italian": [
        {
            "name": "Il Brigante",
            "rating": "5.0"
        },
        {
            "name": "Giardino Doro Ristorante",
            "rating": "5.0"
        }
    ],
    "Mexican": [
        {
            "name": "Cosme",
            "rating": "5.0"
        }
    ]
}

// function to normalize index by having keys lowercase
function lowercaseIndex (obj) {
    var keys = Object.keys(obj);
    var n = keys.length;
    var normalized = {};
    while (n--) {
        var key = keys[n];
        normalized[key.toLowerCase()] = obj[key];
    }

    return normalized;
}

index = lowercaseIndex(index);

function search(needle) {
    return index[needle.toLowerCase()] || "No results";
}

// tests
console.log(search('Italian')); // output: [{"name":"Il Brigante","rating":"5.0"},{"name":"Giardino Doro Ristorante","rating":"5.0"}]
console.log(search('italian')); // output: [{"name":"Il Brigante","rating":"5.0"},{"name":"Giardino Doro Ristorante","rating":"5.0"}]
console.log(search('iTaLiAn')); // output: [{"name":"Il Brigante","rating":"5.0"},{"name":"Giardino Doro Ristorante","rating":"5.0"}]
console.log(search('mexican')); // output: [{"name":"Cosme","rating":"5.0"}]
console.log(search('English')); // output: "No results"```

Body:
I have a dictionary that looks a little like this:

var index = {
  "Italian": [
    {
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [
    {
      "name": "Cosme",
      "rating": "5.0"
    }
  ]
}

I also have a search bar that people can enter queries into. What I want to do is take the query and search for it inside index.

Example: search = "italian", results = {"name": "Il Brigante", "rating": "5.0"}, {"name": "Giardino Doro Ristorante", "rating": "5.0"}

Is that kind of search possible? Any help would be appreciated. Thanks so much in advance. Happy 4th!

Cheers,
Theoi


问:
Dsymutil warning "no debug symbols in executable"
I am working on eliminating warnings for an iOS program in Xcode by fixing the problems causing the warnings as much as possible.  Thankfully, I have been mostly successful at this, but I have two warnings which refuse to go away:  I get a report of a "Dsymutil warning", which the relevant log says is reported when it tries to generate a .dSYM file.  The two warnings are:

warning: no debug symbols in executable (-arch armv7)

warning: no debug symbols in executable (-arch arm64)

I can make these warnings vanish by cleaning and cleaning the build folder.  However, they'll simply show up again when I compile again.

Relevant statistics:

Phones tested:  iPhone 5s, iPhone SE

OS:  iOS 10.3.2

Development environment:  Xcode 8.3.2

Build Active Architecture Only:  No

Does anyone have any idea why I'm getting these warnings, and are they anything to worry about?  I'm not really finding anything particularly relevant via Google or in Apple's documentation.

Thanks in advance for any help anyone can provide.

答:
In your target Build Settings, try to
turn on DWARF with dSYM, debugging symbols, and deployment
postprocessing.
Hope this will help...</p>


问:
Woocommerce Subscription change expiration date
I try to create a subscription with a specific expiration date.

In the function below,
$product_args is an array with details about the product. This array contain product_id, regular_price, etc. The product_id refers to a subscription variable product.

$start_date_timestamp is the subscription start date. This timestamp can be some month before.

By example, I need to create a subscription starting 2 month before (the April 1st). The subscription length is 3 months, so the subscription expiration must be July 1st.

But the problem right now is that the subscription expiration is set to September 27. (Because we are currently June 27)

```<code> static function create_subscription($customer_id,$product_args,$billing_args,$shipping_args = false,$order_notes = false,$client_notes = false,$order_status = false,$start_date_timestamp = false) {

        $start_date = false;
        if($start_date_timestamp==false)
        {
            $start_date = date( 'Y-m-d H:i:s', strtotime( 'now' ) );
        }
        else
        {
            $start_date = date( 'Y-m-d H:i:s', $start_date_timestamp);
        }

        $order_id = \perfo\woocommerce\order::create_order( $customer_id, $product_args, $billing_args,$shipping_args,$order_notes,$client_notes,$order_status);

        if ( ! is_wp_error($order_id) )
        {
            $wc_product = wc_get_product($product_args['product_id']);

            $period = \WC_Subscriptions_Product::get_period( $wc_product );
            $interval = \WC_Subscriptions_Product::get_interval( $wc_product );
            $length = \WC_Subscriptions_Product::get_length( $wc_product );
            $expiration = \WC_Subscriptions_Product::get_expiration_date( $product_args['product_id'],$start_date );

            $subscription = wcs_create_subscription(array('order_id' => $order_id, 'billing_period' => $period, 'billing_interval' => $interval, 'start_date' => $start_date,'end'=>$expiration));

            if(!is_wp_error($subscription))
            {
                $wc_product->set_regular_price($product_args['regular_price']);
                $wc_product->set_price($product_args['regular_price']);
                $subscription->add_product( $wc_product, $product_args['quantity']);

                $subscription->set_address( $billing_args, 'billing' );

                if($shipping_args)
                    $subscription->set_address( $shipping_args, 'shipping' );

                $subscription->update_dates( array(
                    'end'          => $expiration,
                ) );

                $subscription->calculate_totals();
                $subscription->save();

            }
            else
            {
                wp_delete_post($order_id,true);
            }

            return $subscription;
        }

        return $order_id;
    }
</code>```

答:
Your end date must be valid date and it must be in format 'Y-m-d H:i:s'

Please try this code. This is working fine at my end

```<code>$current_date = date("Y-m-d H:i:s") ;

// Setting start date to 1 day before the current date : you can set as require
$start_date = date('Y-m-d H:i:s',strtotime($current_date . "-1 days"));

// end date : setting 12 month after the current date : you can set as require
$end_date = date('Y-m-d H:i:s',strtotime("+12 months", strtotime($start_date)));

$dates_to_update = array();
$dates_to_update['end'] = $end_date;
// $dates_to_update['next_payment'] = $end_date;
// $dates_to_update['trial_end'] = $end_date;
$subscription->update_dates($dates_to_update);
</code>```

https://hotexamples.com/examples/-/WC_Subscriptions_Product/get_expiration_date/php-wc_subscriptions_product-get_expiration_date-method-examples.html

https://hotexamples.com/examples/-/-/wcs_is_datetime_mysql_format/php-wcs_is_datetime_mysql_format-function-examples.html

Body:
I try to create a subscription with a specific expiration date.

In the function below,
$product_args is an array with details about the product. This array contain product_id, regular_price, etc. The product_id refers to a subscription variable product.

$start_date_timestamp is the subscription start date. This timestamp can be some month before.

By example, I need to create a subscription starting 2 month before (the April 1st). The subscription length is 3 months, so the subscription expiration must be July 1st.

But the problem right now is that the subscription expiration is set to September 27. (Because we are currently June 27)

 static function create_subscription($customer_id,$product_args,$billing_args,$shipping_args = false,$order_notes = false,$client_notes = false,$order_status = false,$start_date_timestamp = false) {

        $start_date = false;
        if($start_date_timestamp==false)
        {
            $start_date = date( 'Y-m-d H:i:s', strtotime( 'now' ) );
        }
        else
        {
            $start_date = date( 'Y-m-d H:i:s', $start_date_timestamp);
        }

        $order_id = \perfo\woocommerce\order::create_order( $customer_id, $product_args, $billing_args,$shipping_args,$order_notes,$client_notes,$order_status);

        if ( ! is_wp_error($order_id) )
        {
            $wc_product = wc_get_product($product_args['product_id']);

            $period = \WC_Subscriptions_Product::get_period( $wc_product );
            $interval = \WC_Subscriptions_Product::get_interval( $wc_product );
            $length = \WC_Subscriptions_Product::get_length( $wc_product );
            $expiration = \WC_Subscriptions_Product::get_expiration_date( $product_args['product_id'],$start_date );

            $subscription = wcs_create_subscription(array('order_id' => $order_id, 'billing_period' => $period, 'billing_interval' => $interval, 'start_date' => $start_date,'end'=>$expiration));

            if(!is_wp_error($subscription))
            {
                $wc_product->set_regular_price($product_args['regular_price']);
                $wc_product->set_price($product_args['regular_price']);
                $subscription->add_product( $wc_product, $product_args['quantity']);

                $subscription->set_address( $billing_args, 'billing' );

                if($shipping_args)
                    $subscription->set_address( $shipping_args, 'shipping' );

                $subscription->update_dates( array(
                    'end'          => $expiration,
                ) );

                $subscription->calculate_totals();
                $subscription->save();

            }
            else
            {
                wp_delete_post($order_id,true);
            }

            return $subscription;
        }

        return $order_id;
    }

Body:
Your end date must be valid date and it must be in format 'Y-m-d H:i:s'

Please try this code. This is working fine at my end

$current_date = date("Y-m-d H:i:s") ;

// Setting start date to 1 day before the current date : you can set as require
$start_date = date('Y-m-d H:i:s',strtotime($current_date . "-1 days"));

// end date : setting 12 month after the current date : you can set as require
$end_date = date('Y-m-d H:i:s',strtotime("+12 months", strtotime($start_date)));

$dates_to_update = array();
$dates_to_update['end'] = $end_date;
// $dates_to_update['next_payment'] = $end_date;
// $dates_to_update['trial_end'] = $end_date;
$subscription->update_dates($dates_to_update);

https://hotexamples.com/examples/-/WC_Subscriptions_Product/get_expiration_date/php-wc_subscriptions_product-get_expiration_date-method-examples.html

https://hotexamples.com/examples/-/-/wcs_is_datetime_mysql_format/php-wcs_is_datetime_mysql_format-function-examples.html


问:
How can I hash a password in Java?
I need to hash passwords for storage in a database. How can I do this in Java?

I was hoping to take the plain text password, add a random salt, then store the salt and the hashed password in the database.

Then when a user wanted to log in, I could take their submitted password, add the random salt from their account information, hash it and see if it equates to the stored hash password with their account information.

答:
While the NIST recommendation PBKDF2 has already been mentioned, I'd like to point out that there was a public password hashing competition that ran from 2013 to 2015. In the end, Argon2 was chosen as the recommended password hashing function.

There is a fairly well adopted Java binding for the original (native C) library that you can use.

In the average use-case, I don't think it does matter from a security perspective if you choose PBKDF2 over Argon2 or vice-versa. If you have strong security requirements, I recommend considering Argon2 in your evaluation.

For further information on the security of password hashing functions see security.se.

Title: How can I hash a password in Java?


问:
ssis want to update a sql table based on a flat file
Rather new to SSIS so not sure how to handle this.

I have a flat file which i managed to successfully read from. So right now my data flow consists of just a flat file source.

What i want to do is something like this:

Update SqlTable S
set s.columnA = f.columna
from FlatFile f
where s.columnID = f.columnID

Right now the only way i can see of doing this would be to insert the contents of the flat file into a sql table, then doing my update. This seems wasteful considering i don't need to save the data of the flat file. I just need to update an existing sql table based on the data in the flat file. So is there some way to run the query directly in the SSIS package instead of having to insert a bunch of data into a sql table that i will just wind up dropping?

thanks

答:
Update SqlTable S set s.columnA = f.columna from FlatFile f where s.columnID = f.columnID

That statement above is a SQL statement.  You cannot connect a sql table to a flat file.  You need to work in SQL to do an update, since that is where the table lives

You have 2 choices:

Use an OLEDB Command component within the data flow.  The downside is this calls the statement for each record, so if you have 1,000s of records it is very inefficient.

Push the records to a table using an OLE DB Destination and then you can call your update using an Execute SQL Task.  You can then truncate the table if you like

A possible 3rd option is to roll your own OLE DB destination to do an update on record sets vs records.

While this might sound wasteful, to create a table in the database to store update records, it is done very often.  You just drop the worktable or truncate when complete.