问:
How to listen to route changes in react router v4?
I have a couple of buttons that acts as routes. Everytime the route is changed, I want to make sure the button that is active changes.

Is there a way to listen to route changes in react router v4?

答:
I use withRouter to get the location prop. When the component is updated because of a new route, I check if the value changed:

@withRouter
class App extends React.Component {

  static propTypes = {
    location: React.PropTypes.object.isRequired
  }

  // ...

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      this.onRouteChanged();
    }
  }

  onRouteChanged() {
    console.log("ROUTE CHANGED");
  }

  // ...
  render(){
    return <Switch>
        <Route path="/" exact component={HomePage} />
        <Route path="/checkout" component={CheckoutPage} />
        <Route path="/success" component={SuccessPage} />
        // ...
        <Route component={NotFound} />
      </Switch>
  }
}
```


来源: stackexchange

问:
Decoding an image with Stegano Module
I have a image file that i have to decode with Stegano module. I tried everything but always getting syntax error.

Error:

```<code>root@kali:~/Downloads/Stegano-master# stegano-lsb reveal -i predat0r.png
Install Stegano: sudo pip install Stegano
Traceback (most recent call last):
  File "/usr/local/bin/stegano-lsb", line 32, in <module>
     from stegano import tools
  File "/usr/local/lib/python2.7/dist-packages/stegano/__init__.py", line 4, in <module>
     from . import red
  File "/usr/local/lib/python2.7/dist-packages/stegano/red/__init__.py", line 4, in <module>
     from .red import*
  File "/usr/local/lib/python2.7/dist-packages/stegano/red/red.py", line 33
     def hide(input_image: Union[str, I0[bytes]], message: str):

SyntaxError: invalid syntax
</code>```

http://imgur.com/a/4Rr1i this is the image that i have to decode.

What should i do now? Can someone help me with decoding this.

答:
Please use Python 3:

```<code>sudo apt-get install python3-pip

sudo pip3 install stegano
</code>```

and then run it under python3.

ContentLicense: CC BY-SA 3.0

Title: Decoding an image with Stegano Module

Body:
I have a image file that i have to decode with Stegano module. I tried everything but always getting syntax error.

Error:

root@kali:~/Downloads/Stegano-master# stegano-lsb reveal -i predat0r.png
Install Stegano: sudo pip install Stegano
Traceback (most recent call last):
  File "/usr/local/bin/stegano-lsb", line 32, in <module>
     from stegano import tools
  File "/usr/local/lib/python2.7/dist-packages/stegano/__init__.py", line 4, in <module>
     from . import red
  File "/usr/local/lib/python2.7/dist-packages/stegano/red/__init__.py", line 4, in <module>
     from .red import*
  File "/usr/local/lib/python2.7/dist-packages/stegano/red/red.py", line 33
     def hide(input_image: Union[str, I0[bytes]], message: str):

SyntaxError: invalid syntax

http://imgur.com/a/4Rr1i this is the image that i have to decode.

What should i do now? Can someone help me with decoding this.

Body:
Please use Python 3:

sudo apt-get install python3-pip

sudo pip3 install stegano

and then run it under python3.


问:
Sack with different weights, what has to be the diff for it to work
Question: I have a sack which can carry some weight, and number of items with weight and i want to put as much weight as possible in the sack to carry, after some thought I have got into a conclusion, I take the highest weight every time and put into the sack, intuitivaly that it will work if the weights that are given are incremented atleast by multiplication of 2. For e.g. 2 4 8 16 32 64..
Can anyone help me prove if I am right or wrong about that?  I have also an intuition about that, would love to hear urs.

Note: thought about saying that the sum of the previous numbers wont be bigger of the current nunber.

答:
Yes, described greedy algorithm will work for powers of two.

Note that partial sum of geometric sequence 1,2,4,8,16..2^(k-1) is 2^k-1, that is why you always should choose the largest possible item - it is always bigger than any sum of smaller items.

In mathematical sense set of 2's powers forms matroid

But it would fail in general case (example - 3,3,4 and sum 6). You can learn for dynamic programming to solve this problem with integer weights. It is similar to knapsack problem with unit item costs.


问:
Make only part of a resources string a link in xaml
My goal is to have a string with a link that opens a new window. The catch is that the string has to be localizable.

In order for our localization tool to be able to recognize the strings, it has to be defined like this:

```<code><sys:String x:Uid="testString" x:Key="testString">click here for a good time</sys:String>
</code>```

The string would then be referenced like this:

```<code><TextBlock Text="{StaticResource testString}"/>
</code>```

I need the word "here" to be a link that opens another window. The other words should do nothing when clicked on.

Is this even possible?

答:
Is this even possible?

Not without splitting up the string into words somehow and write some code. You need to define the actual link somewhere.

You could for example handle the Loaded event for the TextBlock and populate its Inline property.

Here is an example that should give you the idea.

```<code><TextBlock Text="{StaticResource testString}" Loaded="TextBlock_Loaded"/>
</code>```

```<code>private void TextBlock_Loaded(object sender, RoutedEventArgs e)
{
    const string linkText = "here";
    TextBlock txt = sender as TextBlock;
    string[] words = txt.Text.Split(' ');
    if (words.Contains(linkText))
    {
        txt.Text = string.Empty;
        foreach (string word in words)
        {
            if (word == linkText)
            {
                var link = new Hyperlink(new Run(linkText + " "));
                link.Click += (ss, ee) =>
                {
                    //do something when the link is clicked on
                };
                txt.Inlines.Add(link);
            }
            else
            {
                txt.Inlines.Add(word + " ");
            }
        }
        txt.Text.TrimEnd();
    }
}
</code>```

Body:
My goal is to have a string with a link that opens a new window. The catch is that the string has to be localizable.

In order for our localization tool to be able to recognize the strings, it has to be defined like this:

<sys:String x:Uid="testString" x:Key="testString">click here for a good time</sys:String>

The string would then be referenced like this:

<TextBlock Text="{StaticResource testString}"/>

I need the word "here" to be a link that opens another window. The other words should do nothing when clicked on.

Is this even possible?

Body:
Is this even possible?

Not without splitting up the string into words somehow and write some code. You need to define the actual link somewhere.

You could for example handle the Loaded event for the TextBlock and populate its Inline property.

Here is an example that should give you the idea.

<TextBlock Text="{StaticResource testString}" Loaded="TextBlock_Loaded"/>

private void TextBlock_Loaded(object sender, RoutedEventArgs e)
{
    const string linkText = "here";
    TextBlock txt = sender as TextBlock;
    string[] words = txt.Text.Split(' ');
    if (words.Contains(linkText))
    {
        txt.Text = string.Empty;
        foreach (string word in words)
        {
            if (word == linkText)
            {
                var link = new Hyperlink(new Run(linkText + " "));
                link.Click += (ss, ee) =>
                {
                    //do something when the link is clicked on
                };
                txt.Inlines.Add(link);
            }
            else
            {
                txt.Inlines.Add(word + " ");
            }
        }
        txt.Text.TrimEnd();
    }
}


问:
laravel 5.3 set session lifetime
I would like to use laravel to remember the login status. If I check the box remember the login status for 7 days, not check only remember 2 hours.

My thoughts are use the 'config/session.php' set the lifetime variable for 120min, and then use laravel function like session('login_status',7days), but session() doesn't have the parameter to set the lifetime.

Who can give me some ideas?

答:
You need to set a cookie on the clients' browser if you want the client to be logged in longer than the session duration. Laravel itself has an implementation for this using a remember_token.

More info about this can be found in the documentation.

Title: laravel 5.3 set session lifetime


问:
F#: Disposing of resources that are inside a closure?
Suppose I create a closure over a resource such as a StreamWriter:

```<code>let currentdir = Directory.GetCurrentDirectory()
let testfile = sprintf "%s\\%s" currentdir "closuretest.txt"

let getwriter() =
    let writer = new StreamWriter(testfile, false)
    (fun() -> writer.Write "test")
</code>```

Is there a way to close the StreamWriter when I'm done with the closure? Or do I need to replace the closure with a wrapper object that has a Write() method and a Dispose() method? (This is of course a trivialized example.) Thanks all.

答:
I sometimes do:</p>

```<code>let getwriter() =
  let writer = new StreamWriter(testfile, false)
  (fun() ->
    use writer = writer
    writer.Write "test")
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Suppose I create a closure over a resource such as a StreamWriter:

let currentdir = Directory.GetCurrentDirectory()
let testfile = sprintf "%s\\%s" currentdir "closuretest.txt"

let getwriter() =
    let writer = new StreamWriter(testfile, false)
    (fun() -> writer.Write "test")

Is there a way to close the StreamWriter when I'm done with the closure? Or do I need to replace the closure with a wrapper object that has a Write() method and a Dispose() method? (This is of course a trivialized example.) Thanks all.

Body:
I sometimes do:

let getwriter() =
  let writer = new StreamWriter(testfile, false)
  (fun() ->
    use writer = writer
    writer.Write "test")


问:
making a table using div in HTML
I want to make a table like this by using DIV in html & CSSdesired result
but I am having a table like this gained result
I tried but could not get the desired result. where I need to change my code? can anyone help me regarding this?

.tableMain {
  display: table;
  width: 100%;
  background-color: black;
}

.tableRow {
  display: table-row;
  color: aqua;
}

.tableCell,
.tableHead {
  border: 1px solid aqua;
  display: table-cell;
  padding-left: 5px;
}

.tableHeading {
  display: table-header-group;
  font-weight: bold;
}

.tableBody {
  display: table-row-group;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tableMain">
  <div class="tableBody">
    <div class="tableRow">
      <div class="tableCell">
        <h2>Header-1</h2>
      </div>
      <div class="tableCell">
        <h2>Header-2</h2>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <h2>Section-1</h2>
      </div>
      <div class="tableCell">
        <h3>Title</h3>
        <h4>Description</h4>
        <ul>
          <li>item-1</li>
          <li>item-2</li>
          <li>item-3</li>
        </ul>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <h2>Section-2</h2>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <h2>header-1</h2>
      </div>
      <div class="tableCell">
        <h2>header-2</h2>
      </div>
      <div class="tableCell">
        <h2>header-3</h2>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <p>A</p>
      </div>
      <div class="TableCell">
        <p>B</p>
      </div>
      <div class="tableCell">
        <p>C</p>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <p>A</p>
      </div>
      <div class="tableCell">
        <p>B</p>
      </div>
      <div class="tableCell">
        <p>C</p>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <p>A</p>
      </div>
      <div class="tableCell">
        <p>B</p>
      </div>
      <div class="tableCell">
        <p>C</p>
      </div>
    </div>
  </div>
</div></code>```

答:
...this is the only drawback when using css to fake a table - you can't fake colspans and rowspans.

So, manually styling the exact table might be possible, but for dynamic content it wouldn't be that easy.

Actually this is why so many html elements exist - each one has its purpose. It looks like to me that the table is the most suitable to this case.

In case you are using divs in order to make the table responsive, you can do it the other way around - ie style table rows, table cells, etc to look like div elements when needed.

Title: making a table using div in HTML

Body:
I want to make a table like this by using DIV in html & CSSdesired result
but I am having a table like this gained result
I tried but could not get the desired result. where I need to change my code? can anyone help me regarding this?

.tableMain {
  display: table;
  width: 100%;
  background-color: black;
}

.tableRow {
  display: table-row;
  color: aqua;
}

.tableCell,
.tableHead {
  border: 1px solid aqua;
  display: table-cell;
  padding-left: 5px;
}

.tableHeading {
  display: table-header-group;
  font-weight: bold;
}

.tableBody {
  display: table-row-group;
}

Header-1

Header-2

Section-1

Title

Description

item-1

item-2

item-3

Section-2

header-1

header-2

header-3

A

B

C

A

B

C

A

B

C


问:
Unable to connect to Database: Failed to connect to: localhost:27017: Connection refused
Why while I run the command mongod on server everything is ok and when I close ssh session on putty I see such error.

Unable to connect to Database: Failed to connect to: localhost:27017:
  Connection refused

答:
The issue here is that the mongo server is being run in the ssh session you are opening when you connect. You'll have to detach the mongo server from your session by using disown or by using a utility such as tmux or screen. This will allow your mongo server process to keep running after you have disconnected your ssh session.

Alternatively, as was mentioned in a comment above, if you run your mongo server as a service, you'll be able to disconnect from the ssh session and still  have your server process running.

Starting mongo as a service would look something like this -

```<code>sudo service mongod start
</code>```

So to explain it simply, when you connect via ssh, you are provided a shell on the server to execute commands. The moment you disconnect from your ssh session, your mongo server exits because it has no shell to run on. The shell that it did have was closed when you exited your ssh session.

Body:
The issue here is that the mongo server is being run in the ssh session you are opening when you connect. You'll have to detach the mongo server from your session by using disown or by using a utility such as tmux or screen. This will allow your mongo server process to keep running after you have disconnected your ssh session.

Alternatively, as was mentioned in a comment above, if you run your mongo server as a service, you'll be able to disconnect from the ssh session and still  have your server process running.

Starting mongo as a service would look something like this -

sudo service mongod start

So to explain it simply, when you connect via ssh, you are provided a shell on the server to execute commands. The moment you disconnect from your ssh session, your mongo server exits because it has no shell to run on. The shell that it did have was closed when you exited your ssh session.


问:
Auto-implemented property in VB.NET with a protected setter?
So far I had a read-only property in VB.NET as

```<code>Public ReadOnly Property Username() As String
</code>```

Now I need to make changes to my code as the setter to this property needs to be protected. In C# I would have done:

```<code>public string Username {get; protected set;}
</code>```

But I can't find such a short hand and good-looking solution in VB.NET. Does VB.NET provide that and I am unaware of this? Or do I have to write so much code and make it look little uglier?

```<code>Public Property Username() As String
    Get
        Return m_Username
    End Get
    Protected Set
        m_Username = Value
    End Set
End Property
Private m_Username As String
</code>```

It's going to make my class so dirty if I had 20 properties and set them like this.

答:
You could make your code a bit shorter by doing it like this:

```<code>Protected _username As String

Public ReadOnly Property Username As String
    Get
        Return _username
    End Get
End Property
</code>```

That way you can set the username through _username in classes that inherit this class.

Body:
So far I had a read-only property in VB.NET as

Public ReadOnly Property Username() As String

Now I need to make changes to my code as the setter to this property needs to be protected. In C# I would have done:

public string Username {get; protected set;}

But I can't find such a short hand and good-looking solution in VB.NET. Does VB.NET provide that and I am unaware of this? Or do I have to write so much code and make it look little uglier?

Public Property Username() As String
    Get
        Return m_Username
    End Get
    Protected Set
        m_Username = Value
    End Set
End Property
Private m_Username As String

It's going to make my class so dirty if I had 20 properties and set them like this.

Body:
You could make your code a bit shorter by doing it like this:

Protected _username As String

Public ReadOnly Property Username As String
    Get
        Return _username
    End Get
End Property

That way you can set the username through _username in classes that inherit this class.


问:
Pipe Broken with PipeInputStream with kubernetes-client exec()
I'm using the kubernetes-client to try copy a directory from a pod, but I'm doing something wrong with the input stream from stdout.  I get a java.io.IOException: Pipe broken exception when it tries to read().  I'm pretty sure that no data flows at all.  I'm half wondering if I need to read the InputStream on a separate thread or something?

The stream is created like this:

```<code>public InputStream copyFiles(String containerId,
                             String folderName) {

    ExecWatch exec = client.pods().withName(containerId).redirectingOutput().exec("tar -C " + folderName + " -c");

    // We need to wrap the InputStream so that when the stdout is closed, then the underlying ExecWatch is closed
    // also. This will cleanup any Websockets connections.
    ChainedCloseInputStreamWrapper inputStreamWrapper = new ChainedCloseInputStreamWrapper(exec.getOutput(), exec);

    return inputStreamWrapper;
}
</code>```

And the InputStream is processed in this function

```<code>void copyVideos(final String containerId) {
    TarArchiveInputStream tarStream = new TarArchiveInputStream(containerClient.copyFiles(containerId, "/videos/"));
    TarArchiveEntry entry;
    boolean videoWasCopied = false;
    try {
        while ((entry = tarStream.getNextTarEntry()) != null) {
            if (entry.isDirectory()) {
                continue;
            }
            String fileExtension = entry.getName().substring(entry.getName().lastIndexOf('.'));
            testInformation.setFileExtension(fileExtension);
            File videoFile = new File(testInformation.getVideoFolderPath(), testInformation.getFileName());
            File parent = videoFile.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            OutputStream outputStream = new FileOutputStream(videoFile);
            IOUtils.copy(tarStream, outputStream);
            outputStream.close();
            videoWasCopied = true;
            LOGGER.log(Level.INFO, "{0} Video file copied to: {1}/{2}", new Object[]{getId(),
                    testInformation.getVideoFolderPath(), testInformation.getFileName()});
        }
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, getId() + " Error while copying the video", e);
        ga.trackException(e);
    } finally {
        if (!videoWasCopied) {
            testInformation.setVideoRecorded(false);
        }
    }

}
</code>```

The InputStream Wrapper class is just there to close the ExecWatch at the end once the InputStream is closed, it looks like this:

```<code>private static class ChainedCloseInputStreamWrapper extends InputStream {

    private InputStream delegate;
    private Closeable resourceToClose;

    public ChainedCloseInputStreamWrapper(InputStream delegate, Closeable resourceToClose) {
        this.delegate = delegate;
        this.resourceToClose = resourceToClose;
    }

    @Override
    public int read() throws IOException {
        return delegate.read();
    }

    public int available() throws IOException {
        return delegate.available();
    }

    public void close() throws IOException {
        logger.info("Shutdown called!");
        delegate.close();

        // Close our dependent resource
        resourceToClose.close();
    }

    public boolean equals(Object o) {
        return delegate.equals(o);
    }

    public int hashCode() {
        return delegate.hashCode();
    }

    public int read(byte[] array) throws IOException {
        return delegate.read(array);
    }

    public int read(byte[] array,
                    int n,
                    int n2) throws IOException {
        return delegate.read(array, n, n2);
    }

    public long skip(long n) throws IOException {
        return delegate.skip(n);
    }

    public void mark(int n) {
        delegate.mark(n);
    }

    public void reset() throws IOException {
        delegate.reset();
    }

    public boolean markSupported() {
        return delegate.markSupported();
    }

    public String toString() {
        return delegate.toString();
    }

}
</code>```

答: Turns out I had the tar command wrong, so it was causing a failure and the stdout PipeInputStream was dead locking. I managed to find a workaround for the deadlock. But the main reason for the failure was that I forgot to tell tar to actually do something! I at least needed a "." to include the current directory. </p>

Body:
I'm using the kubernetes-client to try copy a directory from a pod, but I'm doing something wrong with the input stream from stdout.  I get a java.io.IOException: Pipe broken exception when it tries to read().  I'm pretty sure that no data flows at all.  I'm half wondering if I need to read the InputStream on a separate thread or something?

The stream is created like this:

public InputStream copyFiles(String containerId,
                             String folderName) {

    ExecWatch exec = client.pods().withName(containerId).redirectingOutput().exec("tar -C " + folderName + " -c");

    // We need to wrap the InputStream so that when the stdout is closed, then the underlying ExecWatch is closed
    // also. This will cleanup any Websockets connections.
    ChainedCloseInputStreamWrapper inputStreamWrapper = new ChainedCloseInputStreamWrapper(exec.getOutput(), exec);

    return inputStreamWrapper;
}

And the InputStream is processed in this function

void copyVideos(final String containerId) {
    TarArchiveInputStream tarStream = new TarArchiveInputStream(containerClient.copyFiles(containerId, "/videos/"));
    TarArchiveEntry entry;
    boolean videoWasCopied = false;
    try {
        while ((entry = tarStream.getNextTarEntry()) != null) {
            if (entry.isDirectory()) {
                continue;
            }
            String fileExtension = entry.getName().substring(entry.getName().lastIndexOf('.'));
            testInformation.setFileExtension(fileExtension);
            File videoFile = new File(testInformation.getVideoFolderPath(), testInformation.getFileName());
            File parent = videoFile.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            OutputStream outputStream = new FileOutputStream(videoFile);
            IOUtils.copy(tarStream, outputStream);
            outputStream.close();
            videoWasCopied = true;
            LOGGER.log(Level.INFO, "{0} Video file copied to: {1}/{2}", new Object[]{getId(),
                    testInformation.getVideoFolderPath(), testInformation.getFileName()});
        }
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, getId() + " Error while copying the video", e);
        ga.trackException(e);
    } finally {
        if (!videoWasCopied) {
            testInformation.setVideoRecorded(false);
        }
    }

}

The InputStream Wrapper class is just there to close the ExecWatch at the end once the InputStream is closed, it looks like this:

private static class ChainedCloseInputStreamWrapper extends InputStream {

    private InputStream delegate;
    private Closeable resourceToClose;

    public ChainedCloseInputStreamWrapper(InputStream delegate, Closeable resourceToClose) {
        this.delegate = delegate;
        this.resourceToClose = resourceToClose;
    }

    @Override
    public int read() throws IOException {
        return delegate.read();
    }

    public int available() throws IOException {
        return delegate.available();
    }

    public void close() throws IOException {
        logger.info("Shutdown called!");
        delegate.close();

        // Close our dependent resource
        resourceToClose.close();
    }

    public boolean equals(Object o) {
        return delegate.equals(o);
    }

    public int hashCode() {
        return delegate.hashCode();
    }

    public int read(byte[] array) throws IOException {
        return delegate.read(array);
    }

    public int read(byte[] array,
                    int n,
                    int n2) throws IOException {
        return delegate.read(array, n, n2);
    }

    public long skip(long n) throws IOException {
        return delegate.skip(n);
    }

    public void mark(int n) {
        delegate.mark(n);
    }

    public void reset() throws IOException {
        delegate.reset();
    }

    public boolean markSupported() {
        return delegate.markSupported();
    }

    public String toString() {
        return delegate.toString();
    }

}


问:
How to mock a SOAP Service class in C#
I want to fake the getCustomerName Service call here and mock it with fake Data

My class is "CustomerName" which calls a SOAPService call which returns the CustomerName for an CustomerNumber.I want to fake the SOAPService call to return some fakedata.

CustomerName class:

```<code>using (WebService.WebServiceClient CustomerData = new WebService.WebServiceClient ())
{
      WebServiceClient.TestResponse resp = CustomerData.getCustomerName(customerNumber);
      resp.CustomerName;
}
</code>```

I tried doing these

```<code>var FakeWebService = A.Fake<WebServiceClient>();
var FakeCustomerName=A.Fake<CustomerName>();
</code>```

Then I faked the Calls here and Fake response is some value

```<code>    A.CallTo(WebServiceClient.CustomerNumber).WithNonVoidReturnType().Returns(FakeResponse);
fakeCustomerName = FakeCustomerData.GetCustomerName(CustomerNumber);
</code>```

The problem I face is it's getting the data from the actual endpoint instead of fakedata?

I am not clear on how to do it..

答:
There are several problems with your approach. For starters, you can only fake virtual methods (or abstract ones, or methods defined on interfaces). I assume that WebService.WebServiceClient.getCustomerName is not virtual, so here's an alternative to @Micael's answer that will get you around that. I've used it many times in the past:

Like Micael says,  create an interface instead which holds the functionality the webservice provides.

```<code>public interface ICustomerData
{
    CustomerName GetCustomerName(CustomerNumber number);
}
</code>```

Then you can make your production collaborator CustomerData as he did, or if WebService.WebServiceClient is not sealed, you can do this:

```<code>public class CustomerData: WebService.WebServiceClient, ICustomerData
{}
</code>```

You will need to find a way to supply an implementation of ICustomerData to your production code so that you can use the actual implementation during production and a fake during the tests, which I talk about right now:

The second problem is that in your test, you're attempting to fake calls to WebServiceClient.CustomerNumber, which feels like a type to me, not an actual object that you're dealing with. Following along from our step above, you want to fake the ICustomerData interface:

```<code>var fakeCustomerData = A.Fake<ICustomerData>();
var someCustomerName = getACustomerNameSomehow();

A.CallTo(() => fakeCustomerData.GetCustomerName(A<CustomerNumber>.Ignored)
        .Returns(someCustomerName);
</code>```

This will make sure your fake returns someCustomerName whenever GetCustomerName is called. I changed someCustomerName from a fake because you may not need it to be a fake - if it's easy to create a CustomerName object to return from your fake service, I'd just do that. Only if you need to change its behaviour, or it's almost impossible to create, would I use a fake.

After the fake is configured, you should call some method on your production class (which you said was called CustomerName, just like the type returned from GetCustomerName?), that will eventually call the ICustomerData collaborator. In your original code, you're calling a method on the fake directly, which only tests the fake, not your own code. So instead you might have something like

```<code>var customerNameService = new CustomerName(fakeCustomerData);

var foundCustomerName = customerNameService.GetACustomerNameFromANumber(someCustomerNumber);
// in my imagination, GetACustomerNameFromANumber calls ICustomerData.GetCustomerName

// now do something to check if the foundCustomerName is right, or whatever
</code>```

Title: How to mock a SOAP Service class in C#

Body:
I want to fake the getCustomerName Service call here and mock it with fake Data

My class is "CustomerName" which calls a SOAPService call which returns the CustomerName for an CustomerNumber.I want to fake the SOAPService call to return some fakedata.

CustomerName class:

using (WebService.WebServiceClient CustomerData = new WebService.WebServiceClient ())
{
      WebServiceClient.TestResponse resp = CustomerData.getCustomerName(customerNumber);
      resp.CustomerName;
}

I tried doing these

var FakeWebService = A.Fake<WebServiceClient>();
var FakeCustomerName=A.Fake<CustomerName>();

Then I faked the Calls here and Fake response is some value

    A.CallTo(WebServiceClient.CustomerNumber).WithNonVoidReturnType().Returns(FakeResponse);
fakeCustomerName = FakeCustomerData.GetCustomerName(CustomerNumber);

The problem I face is it's getting the data from the actual endpoint instead of fakedata?

I am not clear on how to do it..

Body:
There are several problems with your approach. For starters, you can only fake virtual methods (or abstract ones, or methods defined on interfaces). I assume that WebService.WebServiceClient.getCustomerName is not virtual, so here's an alternative to @Micael's answer that will get you around that. I've used it many times in the past:

Like Micael says,  create an interface instead which holds the functionality the webservice provides.

public interface ICustomerData
{
    CustomerName GetCustomerName(CustomerNumber number);
}

Then you can make your production collaborator CustomerData as he did, or if WebService.WebServiceClient is not sealed, you can do this:

public class CustomerData: WebService.WebServiceClient, ICustomerData
{}

You will need to find a way to supply an implementation of ICustomerData to your production code so that you can use the actual implementation during production and a fake during the tests, which I talk about right now:

The second problem is that in your test, you're attempting to fake calls to WebServiceClient.CustomerNumber, which feels like a type to me, not an actual object that you're dealing with. Following along from our step above, you want to fake the ICustomerData interface:

var fakeCustomerData = A.Fake<ICustomerData>();
var someCustomerName = getACustomerNameSomehow();

A.CallTo(() => fakeCustomerData.GetCustomerName(A<CustomerNumber>.Ignored)
        .Returns(someCustomerName);

This will make sure your fake returns someCustomerName whenever GetCustomerName is called. I changed someCustomerName from a fake because you may not need it to be a fake - if it's easy to create a CustomerName object to return from your fake service, I'd just do that. Only if you need to change its behaviour, or it's almost impossible to create, would I use a fake.

After the fake is configured, you should call some method on your production class (which you said was called CustomerName, just like the type returned from GetCustomerName?), that will eventually call the ICustomerData collaborator. In your original code, you're calling a method on the fake directly, which only tests the fake, not your own code. So instead you might have something like

var customerNameService = new CustomerName(fakeCustomerData);

var foundCustomerName = customerNameService.GetACustomerNameFromANumber(someCustomerNumber);
// in my imagination, GetACustomerNameFromANumber calls ICustomerData.GetCustomerName

// now do something to check if the foundCustomerName is right, or whatever


问:
Using StatusStrip in C#
Consider System.Windows.Forms.StatusStrip. I have added a StatusStrip to my Windows Forms application, but I am having a few problems.

I would like to have a label anchored at the left and a progressbar anchored on the right in the StatusStrip, but I can't find a way to set these properties.

I then thought that I may need to create two StatusStrips and anchor them on either side of the bottom of the form... That didn't pan out; besides that, it just doesn't feel right.

答: Did you tried the Alignment property of ProgresBarToolStripItem set to the Right?</p>

OwnerDisplayName: Brad

Title: Using StatusStrip in C#

OwnerDisplayName: TcKs


问:
Laravel HTTPS routes
today I decided to move my website to HTTPS. Early my website work on HTTP.

My problem is in misunderstood how Laravel pass HTTP and https in helpers function route('name')

I change my website URL in config/app.php to https://www.domain.name and I think, this solution helps me. But I got a strange result.

In php artisan tinker if I pass route('ROUTE.NAME') I got right link https://www.domain.name/route/path
but in blade template I got http://www.domain.name/route/path

The same situation with \URL::to('/')

Maybe someone can explain to me why this happened?

答:
I struggled with this for ages. My solution was to put the following in my routes.php file (you may prefer a different place for it)

I have also wrapped a conditional statement around this line, so it only applies to my remote configuration:

```<code>if (App::environment('remote')) {
    URL::forceSchema('https');
}
</code>```

You can try to add in your AppServiceProvider in the boot method.
here: app/Providers/AppServiceProvider.php

Or another way:

So I figured it out. It not that easy but in your AppServiceProvider.php you must add: $this->app['request']->server->set('HTTPS', true); in register method. And that is how I figured it out.

Btw. Setting APP_URL does nothing to HTTP side of your app, it's for artisan.

PS. CloudFlare HTTPS Rewrites are also good idea :)

Title: Laravel HTTPS routes

Body:
I struggled with this for ages. My solution was to put the following in my routes.php file (you may prefer a different place for it)

I have also wrapped a conditional statement around this line, so it only applies to my remote configuration:

if (App::environment('remote')) {
    URL::forceSchema('https');
}

You can try to add in your AppServiceProvider in the boot method.
here: app/Providers/AppServiceProvider.php

Or another way:

So I figured it out. It not that easy but in your AppServiceProvider.php you must add: $this->app['request']->server->set('HTTPS', true); in register method. And that is how I figured it out.

Btw. Setting APP_URL does nothing to HTTP side of your app, it's for artisan.

PS. CloudFlare HTTPS Rewrites are also good idea :)


问:
Docker containers can't access local network DNS
When building a docker image, I have a curl command which pulls down a file as such:

RUN curl -L http://files.mycompany.com/ -o file.war

files.mycompany.com is a server accessable only from within the company network. I can reach this server from my host machine, but not from within the docker container if I use the name (IP works fine).

This works: RUN ping google.com

This works: RUN ping 10.3.2.1 (IP of files.mycompany.com)

This does not work: RUN ping files.mycompany.com (translates the name to another IP than if I ping the same server from the host machine)

Something is not setup correctly on my machine since building the container from another dev computer on the same network works fine. It's like the docker interface does not receive the DNS records from the local network?

I am running Ubuntu 17.04.

答:
Do this in your host:

```<code>cat /etc/resolv.conf
</code>```

If you see something like 127.0.0..., it means that the DNS config that your host uses is a daemon that listen to localhost. Docker can't tell your container to use the same DNS because the container has it's own localhost, so docker defaults to the Google DNS (8.8.8.8). You can confirm that doing this inside the container: cat /etc/resolv.conf

I recommend you to follow steps here, so edit your /etc/docker/daemon.json, and put this:

```<code>{"dns": ["your_dns_server_ip"]}
</code>```

Note about /etc/default/docker: this file is not used anymore in latest Ubuntu versions. Instead, create the json file that I've pointed out. See the docs: /etc/docker/daemon.json

Body:
Do this in your host:

cat /etc/resolv.conf

If you see something like 127.0.0..., it means that the DNS config that your host uses is a daemon that listen to localhost. Docker can't tell your container to use the same DNS because the container has it's own localhost, so docker defaults to the Google DNS (8.8.8.8). You can confirm that doing this inside the container: cat /etc/resolv.conf

I recommend you to follow steps here, so edit your /etc/docker/daemon.json, and put this:

{"dns": ["your_dns_server_ip"]}

Note about /etc/default/docker: this file is not used anymore in latest Ubuntu versions. Instead, create the json file that I've pointed out. See the docs: /etc/docker/daemon.json


问:
How to extract and split a string in multiple parts
I would like to search and split different files in a directory based on some pattern  which may contain different file formats:

```<code>/path/

somefile.txt 2010-01-01
file.txt 2010-01-02
f.txt 2010-01-03
test.txt 2010-01-04
photo.jpg 2010-01-04
script.py  2010-01-05
</code>```

In order to get:

```<code>somefile.txt
file.txt
f.txt
test.txt
</code>```

Here first I would like to catch all files which contains .txt and split them accordingly:

```<code>def catch_txt(path):
    result = [os.path.join(path, f) for f in os.listdir(path) if
re.search(r"\w+\.\w+\txt", f)]
    splitted_result = [files for files in result if
re.split(r"\w+\.\w+\txt", f)]
    # some other stuff
    return splitted_result
</code>```

But only gives a emtpy list.

答:
Your pattern:

```<code>r"\w+\.\w+\txt"
</code>```

looks for:

A word character, one or more times, followed by...

A literal dot, followed by...

A word character one or more times, followed by...

A tab character, followed by...

The literal characters 'xt'.

So your pattern will match filenames like:

```<code> hello.a    xt
</code>```

If you want to match filenames like:

```<code>hello.txt
</code>```

then you need to use a pattern like:

```<code>r"\w+\.txt"
</code>```

Body:
I would like to search and split different files in a directory based on some pattern  which may contain different file formats:

/path/

somefile.txt 2010-01-01
file.txt 2010-01-02
f.txt 2010-01-03
test.txt 2010-01-04
photo.jpg 2010-01-04
script.py  2010-01-05

In order to get:

somefile.txt
file.txt
f.txt
test.txt

Here first I would like to catch all files which contains .txt and split them accordingly:

def catch_txt(path):
    result = [os.path.join(path, f) for f in os.listdir(path) if
re.search(r"\w+\.\w+\txt", f)]
    splitted_result = [files for files in result if
re.split(r"\w+\.\w+\txt", f)]
    # some other stuff
    return splitted_result

But only gives a emtpy list.

Body:
Your pattern:

r"\w+\.\w+\txt"

looks for:

A word character, one or more times, followed by...

A literal dot, followed by...

A word character one or more times, followed by...

A tab character, followed by...

The literal characters 'xt'.

So your pattern will match filenames like:

 hello.a    xt

If you want to match filenames like:

hello.txt

then you need to use a pattern like:

r"\w+\.txt"


问:
Symfony: Why the isInitialized always is false?
I used doctrine query a user:

```<code>$customer = $this->getDoctrine()->getRepository('DemoUserBundle:Customer')->find(1);
</code>```

But i got the result:

Customer {#1441 ▼
    +isInitialized: false
    -id: 1
    -username: null
    -nickname: null
    -email: null
    -salt: null
    -password: null
    -roles: null
    -enabled: null
    -lastLogin: null
    -expired: null
    -expiredAt: null
    -created: null
    -modified: null
    -group: null
    -ceilphoneCode: null
    -avatar: null
    -tasks: null
    -applications: null
    -companies: null
    -creators: null
    -images: null
    -company: null
    -store: Store {#1440 ▶}
    -realName: null
    -sex: null
    -age: null
    -belongCompany: null
    -address: null
    -career: null
    -relationProducts: null
    -attributes: null
    -medias: null
    -logs: null
     …2
  }

the result is not completed, where are other data of this user? why the isInitialized is false?

答:
I added fetch="EAGER" to an other entity which called this entity and it is Ok for me.

Try $customer = $this->getDoctrine()->getRepository('DemoUserBundle:Customer')->find(1);

and $customer = $this->getDoctrine()->getRepository('DemoUserBundle:Customer')->find(2);

And you will understand.

Body:
I used doctrine query a user:

$customer = $this->getDoctrine()->getRepository('DemoUserBundle:Customer')->find(1);

But i got the result:

Customer {#1441 ▼
    +isInitialized: false
    -id: 1
    -username: null
    -nickname: null
    -email: null
    -salt: null
    -password: null
    -roles: null
    -enabled: null
    -lastLogin: null
    -expired: null
    -expiredAt: null
    -created: null
    -modified: null
    -group: null
    -ceilphoneCode: null
    -avatar: null
    -tasks: null
    -applications: null
    -companies: null
    -creators: null
    -images: null
    -company: null
    -store: Store {#1440 ▶}
    -realName: null
    -sex: null
    -age: null
    -belongCompany: null
    -address: null
    -career: null
    -relationProducts: null
    -attributes: null
    -medias: null
    -logs: null
     …2
  }

the result is not completed, where are other data of this user? why the isInitialized is false?


问:
PHP send mail error 3
When I try to send the form on my web site, I got this error:

Sorry ..., it seems that my mail server is not responding. Please try again later!

I thing that is a problem with me contact_me.php file

There is the code

```<code><?php
  // Check for empty fields
  if(empty($_POST['name'])          ||
     empty($_POST['email'])         ||
     empty($_POST['phone'])         ||
     empty($_POST['message'])   ||
     !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
  {
     echo "No arguments Provided!";
     return false;
  }

  $name = strip_tags(htmlspecialchars($_POST['name']));
  $email_address = strip_tags(htmlspecialchars($_POST['email']));
  $phone = strip_tags(htmlspecialchars($_POST['phone']));
  $message = strip_tags(htmlspecialchars($_POST['message']));

  error_reporting(E_STRICT);

  date_default_timezone_set('Portugal/Lisbon');

  require_once('class.phpmailer.php');

  $mail = new PHPMailer();

  $mail->IsSMTP(); // telling the class to use SMTP
  $mail->Host       = "a.a.pt"; // SMTP server
  $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only
  $mail->SMTPAuth   = true;                  // enable SMTP authentication
  $mail->Host       = "a.a.pt"; // sets the SMTP server
  $mail->Port       = 25;                    // set the SMTP port for the GMAIL server
  $mail->Username   = "a@a.pt"; // SMTP account username
  $mail->Password   = "a";        // SMTP account password

  $mail->SetFrom('a@a.pt', 'First Last');

  $mail->AddReplyTo("a@a.pt","First Last");

  $mail->Subject    = "PHPMailer Test Subject via smtp, basic with authentication";

  $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

  $address = "a@a.pt";
  $mail->AddAddress($address, "a@a.pt");

  $formcontent=" From: $name \n Phone: $phone \n Email: $email \n Message: $message";
  $formcontent= eregi_replace("[\]",'',$formcontent);
  $mail->MsgHTML($formcontent);

  if(!$mail->Send()) {
      echo "Mailer Error: " . $mail->ErrorInfo;
  } else {
           echo "Message sent!";
         }
?>
</code>```

答:
You can try using my class, i'm sure this runs 100%, even if it does not work for you is a credential problem or email server that for some reason waste for the connection

```<code>class Mailplus{
    protected  $host = "ssl://smtps.*.com";
    protected $port = "123";
    protected $username = "email@example";
    protected $password = "*";
    protected $from = "Email from - Name <email@example>";
    protected $smtp;
    function __construct() {
        require_once "Mail.php";
        $this->smtp = Mail::factory('smtp',
            array ('host' => $this->host,
                'port' => $this->port,
                'auth' => true,
                'username' => $this->username,
                'password' => $this->password));
    }

    function SendMail($to ,$subject,$body){
        $headers = array ('From' => $this->from,
            'Subject' => $subject,
            'MIME-Version' =>'1.0',
            'Content-Type' =>'text/html',
            'charset' => 'ISO-8859-1');
        $mail = $this->smtp->send($to, $headers, $body);
        if (PEAR::isError($mail)) {
            return "Ex_001";
        } else {
            return true;
        }
    }
}
</code>```

Then use this comand

```<code>$mail = new Mailplus ();
if ($mail.SendMail("to@example.com","Subject","html emial")==ture){
   //email sent
else{
   //email not sent
}
</code>```

Title: PHP send mail error 3

Body:
When I try to send the form on my web site, I got this error:

Sorry ..., it seems that my mail server is not responding. Please try again later!

I thing that is a problem with me contact_me.php file

There is the code

<?php
  // Check for empty fields
  if(empty($_POST['name'])          ||
     empty($_POST['email'])         ||
     empty($_POST['phone'])         ||
     empty($_POST['message'])   ||
     !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
  {
     echo "No arguments Provided!";
     return false;
  }

  $name = strip_tags(htmlspecialchars($_POST['name']));
  $email_address = strip_tags(htmlspecialchars($_POST['email']));
  $phone = strip_tags(htmlspecialchars($_POST['phone']));
  $message = strip_tags(htmlspecialchars($_POST['message']));

  error_reporting(E_STRICT);

  date_default_timezone_set('Portugal/Lisbon');

  require_once('class.phpmailer.php');

  $mail = new PHPMailer();

  $mail->IsSMTP(); // telling the class to use SMTP
  $mail->Host       = "a.a.pt"; // SMTP server
  $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only
  $mail->SMTPAuth   = true;                  // enable SMTP authentication
  $mail->Host       = "a.a.pt"; // sets the SMTP server
  $mail->Port       = 25;                    // set the SMTP port for the GMAIL server
  $mail->Username   = "a@a.pt"; // SMTP account username
  $mail->Password   = "a";        // SMTP account password

  $mail->SetFrom('a@a.pt', 'First Last');

  $mail->AddReplyTo("a@a.pt","First Last");

  $mail->Subject    = "PHPMailer Test Subject via smtp, basic with authentication";

  $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

  $address = "a@a.pt";
  $mail->AddAddress($address, "a@a.pt");

  $formcontent=" From: $name \n Phone: $phone \n Email: $email \n Message: $message";
  $formcontent= eregi_replace("[\]",'',$formcontent);
  $mail->MsgHTML($formcontent);

  if(!$mail->Send()) {
      echo "Mailer Error: " . $mail->ErrorInfo;
  } else {
           echo "Message sent!";
         }
?>

Body:
You can try using my class, i'm sure this runs 100%, even if it does not work for you is a credential problem or email server that for some reason waste for the connection

class Mailplus{
    protected  $host = "ssl://smtps.*.com";
    protected $port = "123";
    protected $username = "email@example";
    protected $password = "*";
    protected $from = "Email from - Name <email@example>";
    protected $smtp;
    function __construct() {
        require_once "Mail.php";
        $this->smtp = Mail::factory('smtp',
            array ('host' => $this->host,
                'port' => $this->port,
                'auth' => true,
                'username' => $this->username,
                'password' => $this->password));
    }

    function SendMail($to ,$subject,$body){
        $headers = array ('From' => $this->from,
            'Subject' => $subject,
            'MIME-Version' =>'1.0',
            'Content-Type' =>'text/html',
            'charset' => 'ISO-8859-1');
        $mail = $this->smtp->send($to, $headers, $body);
        if (PEAR::isError($mail)) {
            return "Ex_001";
        } else {
            return true;
        }
    }
}

Then use this comand

$mail = new Mailplus ();
if ($mail.SendMail("to@example.com","Subject","html emial")==ture){
   //email sent
else{
   //email not sent
}


问:
Creating Calculated Member in SSAS cube after renaming Dimension Attribute
I am very new to SSAS Cubes, and do not know MDX.

I need help in creating a calculated member. The dimension attribute that I am using in the calculated member calculation, is renamed, and that is why the calculation is not working.

I have a dimension named "IN" in the cube, and I am trying to count the "CounterKey" in the measures group when the value of attribute "C 1" in the "IN" dimension is 1.

I used the calculation below and it worked fine.

```<code>([Measures].[CounterKey count],([Dim IN].[C 1 Top Box].&[1]))
</code>```

I had to rename "C 1" to a more user friendly/descriptive name i.e. "Courtesy TB". After changing the name, I made the change in the calculated member as below as below

```<code>([Measures].[CounterKey count],([Dim IN].[Courtesy TB].&[1]))
</code>```

but the calculation is not working any more, and I am just getting a null as a result.

Any help will be highly appreciated.

答:
It seems this is the wrong renaming or something else. Try to drag'n'drop the member from your cube and insert into the formula. Will the following return the null?

```<code>[Dim IN].[C 1 Top Box].&[1].UniqueName
</code>```

If null, it means the member doesn't exist any more within a cube. It's a naming issue.

Body:
I am very new to SSAS Cubes, and do not know MDX.

I need help in creating a calculated member. The dimension attribute that I am using in the calculated member calculation, is renamed, and that is why the calculation is not working.

I have a dimension named "IN" in the cube, and I am trying to count the "CounterKey" in the measures group when the value of attribute "C 1" in the "IN" dimension is 1.

I used the calculation below and it worked fine.

([Measures].[CounterKey count],([Dim IN].[C 1 Top Box].&[1]))

I had to rename "C 1" to a more user friendly/descriptive name i.e. "Courtesy TB". After changing the name, I made the change in the calculated member as below as below

([Measures].[CounterKey count],([Dim IN].[Courtesy TB].&[1]))

but the calculation is not working any more, and I am just getting a null as a result.

Any help will be highly appreciated.

Body:
It seems this is the wrong renaming or something else. Try to drag'n'drop the member from your cube and insert into the formula. Will the following return the null?

[Dim IN].[C 1 Top Box].&[1].UniqueName

If null, it means the member doesn't exist any more within a cube. It's a naming issue.


问:
Send multiple content-type Ajax
I have succeed upload image using ajax with codeigniter. But now i want to sending array too so i can insert data inside controller and model.

This is my code for better explanation :

```<code><form method="POST" id="quiz_file" action="<?php echo site_url('home/upload_quiz/' . $kelas);?>" enctype="multipart/form-data">
<input name="filequiz" id="filequiz" type="file" />
</form>

This is the controller :
function upload_quiz($kelas)
{
    $temp = explode(".", $_FILES["filequiz"]["name"]);
    $extension = end($temp);
    $new_name = time() . "." . $extension;
    $config['upload_path']          = './assets/images/quiz_images/';
    $config['allowed_types']        = 'gif|jpg|png|jpeg';
    $config['max_size']             = 2000;
    $config['file_name']            = $new_name;
    $config['max_width']            = 10000;
    $config['max_height']           = 10000;
    $this->load->library('upload', $config);

    $session_data = $this->session->userdata('logged_in');
    $data['user_name'] = $session_data['user_name'];
    $data['kelas'] = $kelas;
    if ( ! $this->upload->do_upload('filequiz'))
    {
        print_r(array('error' => $this->upload->display_errors()));
        $data['error'] = array('error' => $this->upload->display_errors());
        $this->load->view('course', $data);
    }
    else
    {
        $this->load->model('Model');
        $asid = $this->input->post('asid');
        $value = $this->input->post('value');
        $this->Model->inputassignmentscore($asid,$value); <---- The error come from this
        $data['status'] = array('upload_data' => $this->upload->data());
        $quiz_name = $this->input->post('quiz_name');
        if($this->Model->input_quiz($quiz_name,$new_name,$kelas) == TRUE)
        {
            echo $asid;
            $this->load->view('course', $data);
        }
        elseif($this->Model->input_quiz($quiz_name,$new_name,$kelas) == FALSE)
        {
            $this->load->view('course', $data);
        }
    }
}
</code>```

This is the script code

```<code>var cmbvalue = [];
if(asid_quiz.length > 0)
{
    for(i=0;i<asid_quiz.length;i++)
    {
        cmbass = document.getElementsByName('quizcmb')[i].value;
        cmbvalue.push(cmbass);
        console.log('cmbass : ' + cmbvalue);
    }
}

$.ajax({
url: uploadURI,
type: 'post',
data:
{
    formData : formData,
    asid : asid_quiz,
    value : cmbvalue
},
processData: false,
contentType: false,
beforeSend: function ( xhr ) {
},
success: function(data)
{
}
});
</code>```

The formData is sending correctly. But the asid and value is empty. So i cannot insert data using controller and model.
How can i fix this ?

This is the complete code if you want to see : this is my post

When i try using console or alert, the value is exists.

答:
```<code>var asid_quiz = ['1','2','3'];
var cmbvalue = [];
for(i=0;i<asid_quiz.length;i++)
    {
        cmbass = asid_quiz[i];
        cmbvalue.push(cmbass);
        console.log('cmbass : ' + cmbvalue);
    }
$.ajax({
    type: 'POST',
    url: 'test.php',
    data: { album: 'test',asid:'asid_quiz',value:cmbvalue },

    success: function(response) {
        console.log(response);
    }
});
</code>```

Title: Send multiple content-type Ajax

Body:
I have succeed upload image using ajax with codeigniter. But now i want to sending array too so i can insert data inside controller and model.

This is my code for better explanation :

<form method="POST" id="quiz_file" action="<?php echo site_url('home/upload_quiz/' . $kelas);?>" enctype="multipart/form-data">
<input name="filequiz" id="filequiz" type="file" />
</form>

This is the controller :
function upload_quiz($kelas)
{
    $temp = explode(".", $_FILES["filequiz"]["name"]);
    $extension = end($temp);
    $new_name = time() . "." . $extension;
    $config['upload_path']          = './assets/images/quiz_images/';
    $config['allowed_types']        = 'gif|jpg|png|jpeg';
    $config['max_size']             = 2000;
    $config['file_name']            = $new_name;
    $config['max_width']            = 10000;
    $config['max_height']           = 10000;
    $this->load->library('upload', $config);

    $session_data = $this->session->userdata('logged_in');
    $data['user_name'] = $session_data['user_name'];
    $data['kelas'] = $kelas;
    if ( ! $this->upload->do_upload('filequiz'))
    {
        print_r(array('error' => $this->upload->display_errors()));
        $data['error'] = array('error' => $this->upload->display_errors());
        $this->load->view('course', $data);
    }
    else
    {
        $this->load->model('Model');
        $asid = $this->input->post('asid');
        $value = $this->input->post('value');
        $this->Model->inputassignmentscore($asid,$value); <---- The error come from this
        $data['status'] = array('upload_data' => $this->upload->data());
        $quiz_name = $this->input->post('quiz_name');
        if($this->Model->input_quiz($quiz_name,$new_name,$kelas) == TRUE)
        {
            echo $asid;
            $this->load->view('course', $data);
        }
        elseif($this->Model->input_quiz($quiz_name,$new_name,$kelas) == FALSE)
        {
            $this->load->view('course', $data);
        }
    }
}

This is the script code

var cmbvalue = [];
if(asid_quiz.length > 0)
{
    for(i=0;i<asid_quiz.length;i++)
    {
        cmbass = document.getElementsByName('quizcmb')[i].value;
        cmbvalue.push(cmbass);
        console.log('cmbass : ' + cmbvalue);
    }
}

$.ajax({
url: uploadURI,
type: 'post',
data:
{
    formData : formData,
    asid : asid_quiz,
    value : cmbvalue
},
processData: false,
contentType: false,
beforeSend: function ( xhr ) {
},
success: function(data)
{
}
});

The formData is sending correctly. But the asid and value is empty. So i cannot insert data using controller and model.
How can i fix this ?

This is the complete code if you want to see : this is my post

When i try using console or alert, the value is exists.


问:
How do setUp and tearDown work for Load Testing with Jmeter and Junit?
I have to do some setup and cleanup on the database I am load testing with Jmeter and Junit. I have put these in setUp and tearDown respectively. My question now is what happens when I fire off 100 threads that execute my test? Will Jmeter first run 100 setUp's, then 100 threads of my test and then 100 tearDowns? Or does it just create 100 threads to execute my test and run them all in parallel?

My concern is just that the setUp and tearDown may affect my testing, depending on how Jmeter and Junit do things. In that case, I would have to do setUp and tearDown completely outside of my test.

答:
I haven't used Junit and Jmeter together, so I'm assuming setUp and tearDown are part of Junit.

Given that, I would assume Junit would execute setUp, run the Jmeter script then run tearDown when Jmeter signals it is done.  Since JMeter uses the same script for multiple threads, and isn't "done" until the last thread finishes, you shouldn't have multiple setUp/teardown Scripts.

I would try it with 2 threads and see what happens.


问:
Spring Boot Sendmail
I can't configure Spring and Sendmail to work together.

Spring side:

pom.xml

```<code>  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
</code>```

application.properties

```<code>spring.mail.protocol=smtp
spring.mail.host=localhost
spring.mail.port=25
spring.mail.username=
spring.mail.password=
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=false
</code>```

send mail code(works fine with gmail)

```<code>@Async
@Override
public void sendActivationEmail(String username, String activationToken) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(username);
    message.setSubject(EmailUtils.EMAIL_ACTIVATION_SUBJECT);
    message.setText(String.format(EmailUtils.EMAIL_ACTIVATION_BODY, activationToken));
    this.javaMailSender.send(message);
}
</code>```

Linux side:

/etc/mail/access

```<code>Connect:localhost.localdomain           RELAY
Connect:localhost                       RELAY
Connect:127.0.0.1                       RELAY
</code>```

/etc/mail/local-host-names

```<code>mydomain.com
</code>```

/etc/mail/virtusertable

```<code>noreply@mydomain.com noreply
</code>```

(I have added noreply as a user)

I don't get any errors. Nothing in logs. No sent email as well. How do I configure it all?

答:
Certain timeout values are infinite in Spring Boot by default.
Try to set the timeout values to reasonable values as suggested in the documentation and see if it is timing out.

```<code>spring.mail.properties.mail.smtp.connecttimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000
</code>```

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-email.html

Also set the from address:

message.setFrom(...);

Title: Spring Boot Sendmail

Body:
I can't configure Spring and Sendmail to work together.

Spring side:

pom.xml

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>

application.properties

spring.mail.protocol=smtp
spring.mail.host=localhost
spring.mail.port=25
spring.mail.username=
spring.mail.password=
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=false

send mail code(works fine with gmail)

@Async
@Override
public void sendActivationEmail(String username, String activationToken) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(username);
    message.setSubject(EmailUtils.EMAIL_ACTIVATION_SUBJECT);
    message.setText(String.format(EmailUtils.EMAIL_ACTIVATION_BODY, activationToken));
    this.javaMailSender.send(message);
}

Linux side:

/etc/mail/access

Connect:localhost.localdomain           RELAY
Connect:localhost                       RELAY
Connect:127.0.0.1                       RELAY

/etc/mail/local-host-names

mydomain.com

/etc/mail/virtusertable

noreply@mydomain.com noreply

(I have added noreply as a user)

I don't get any errors. Nothing in logs. No sent email as well. How do I configure it all?

Body:
Certain timeout values are infinite in Spring Boot by default.
Try to set the timeout values to reasonable values as suggested in the documentation and see if it is timing out.

spring.mail.properties.mail.smtp.connecttimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-email.html

Also set the from address:

message.setFrom(...);


问:
How can I load a `application-{profile}.yml` property source without using `spring.profiles.active`?
I'm trying to integrate an existing application with Spring Boot. One of the things I'd like to do is clean up the way we load property files by having the usual Spring Boot application configuration file like this:

├── application.yaml
├── application-DEV.yaml

The thing is that I can't add the system property spring.profiles.active because I'm relying on some existing infrastructure which has a system property with the name environment instead. I'm trying an alternative solution to set the active profile by using an ApplicationContextInitializer which according to the documentation:

Typically used within web applications that require some programmatic initialization of the application context. For example, registering property sources or activating profiles against the context's environment.

This is my code which tries to add an active profile by reading the environment system property:

  @Slf4j
  public class AddEnvironmentProfileApplicationContextInitializer implements ApplicationContextInitializer {

     @Override
     public void initialize(ConfigurableApplicationContext applicationContext) {
        String environment = System.getProperty("environment");
        log.info("Adding active profile from System Property environment={}", environment);
        applicationContext.getEnvironment().addActiveProfile(environment);
     }
  }
```

which I'm loading with a starter dependency by defining the initializer in spring.factories with the key org.springframework.context.ApplicationContextInitializer.

If I run the application with -Denvironment=DEV, I can see that the DEV profile is added correctly, but the application-DEV.yml file is not loaded.

Am I missing something? I did inspect the source code for Spring Boot and it looks like the Property Sources are configured before running the Initializers, but then why would you define a profile with it if the right files are not loaded? Is this the desired behaviour or is it maybe a bug?

答:
If you don't want to set a spring.profile.active as a system property you can simply do this in your default yml.

```<code>spring:
  profile:
    active: ${environment}
</code>```

Body:
I'm trying to integrate an existing application with Spring Boot. One of the things I'd like to do is clean up the way we load property files by having the usual Spring Boot application configuration file like this:

├── application.yaml
├── application-DEV.yaml

The thing is that I can't add the system property spring.profiles.active because I'm relying on some existing infrastructure which has a system property with the name environment instead. I'm trying an alternative solution to set the active profile by using an ApplicationContextInitializer which according to the documentation:

Typically used within web applications that require some programmatic initialization of the application context. For example, registering property sources or activating profiles against the context's environment.

This is my code which tries to add an active profile by reading the environment system property:

  @Slf4j
  public class AddEnvironmentProfileApplicationContextInitializer implements ApplicationContextInitializer {

     @Override
     public void initialize(ConfigurableApplicationContext applicationContext) {
        String environment = System.getProperty("environment");
        log.info("Adding active profile from System Property environment={}", environment);
        applicationContext.getEnvironment().addActiveProfile(environment);
     }
  }

which I'm loading with a starter dependency by defining the initializer in spring.factories with the key org.springframework.context.ApplicationContextInitializer.

If I run the application with -Denvironment=DEV, I can see that the DEV profile is added correctly, but the application-DEV.yml file is not loaded.

Am I missing something? I did inspect the source code for Spring Boot and it looks like the Property Sources are configured before running the Initializers, but then why would you define a profile with it if the right files are not loaded? Is this the desired behaviour or is it maybe a bug?

Body:
If you don't want to set a spring.profile.active as a system property you can simply do this in your default yml.

spring:
  profile:
    active: ${environment}


问:
Filtering out bots and spiders for ad system. Blocking gone too far
We have an in house ad system, and are constantly fighting bots and spiders. Obviously we want to get to as close to 100% valid impressions as possible and I have a particular ad zone that I experiment with.

This ad zone appears on only 1 page of the site, so I compare our Google Analytics page views for that page to the impression count for that ad zone and try to get them as close as possible.

Basic protections include, a known bot/spider list, serving the ads with javascript, and a honeypot to automatically collect new scrapers/bots.

This puts ad delivery at 130-150% of page views. Meaning, bots are triggering impressions, but not page views.

So then I started only loading the ads on mouse movement and delivery dropped to 40-60% of page views.

Now this is desktop only, no mobile.

What am I not thinking of that fulfillment is now so low? There aren't that many people with JS turned off, or browsing without mice.

I actually assumed that I would barely interrupt impressions, thinking that most bots would simulate mouse movement, not that I would drop them so low.

Does anyone have any thoughts?

EDIT WITH JS SNIPPET

```<code>adShow = 0;
document.onmousemove = function(){
    if (adShow == 0) {
            var leaderboard = CODE_FOR_AD;
            var adLeaderboard = document.querySelector('.adspace-leaderboard#adspace');
            adLeaderboard.innerHTML = leaderboard;
            adShow = 1;
    }
}
</code>```

答:
As you commented to this answer (as I expected) you placed the JS snippet right after the opening body-tag, so before the actual HTML element (same would happen if you placed this snippet in the head section of the page).
It is quite likely that someone moves the mouse during the loading of the page, and so the mousemove event might be executed before the HTML element is there and thus the ad-space will never be actually loaded.

You could fix that easily by either placing the snippet right before the  closing tag, or by wrapping the code in an onDomReady or onLoad event. The last two will make the code execute respectively after all DOM has been loaded or even after all assets (images, etc.) have been loaded. In your case onDomReady would be enough.

Like this:

```<code>document.onDomReady = function(){
    adShow = 0;
    document.onmousemove = function(){
        if (adShow == 0) {
                var leaderboard = CODE_FOR_AD;
                var adLeaderboard = document.querySelector('.adspace-leaderboard#adspace');
                adLeaderboard.innerHTML = leaderboard;
                adShow = 1;
        }
    }
}
</code>```

Body:
We have an in house ad system, and are constantly fighting bots and spiders. Obviously we want to get to as close to 100% valid impressions as possible and I have a particular ad zone that I experiment with.

This ad zone appears on only 1 page of the site, so I compare our Google Analytics page views for that page to the impression count for that ad zone and try to get them as close as possible.

Basic protections include, a known bot/spider list, serving the ads with javascript, and a honeypot to automatically collect new scrapers/bots.

This puts ad delivery at 130-150% of page views. Meaning, bots are triggering impressions, but not page views.

So then I started only loading the ads on mouse movement and delivery dropped to 40-60% of page views.

Now this is desktop only, no mobile.

What am I not thinking of that fulfillment is now so low? There aren't that many people with JS turned off, or browsing without mice.

I actually assumed that I would barely interrupt impressions, thinking that most bots would simulate mouse movement, not that I would drop them so low.

Does anyone have any thoughts?

EDIT WITH JS SNIPPET

adShow = 0;
document.onmousemove = function(){
    if (adShow == 0) {
            var leaderboard = CODE_FOR_AD;
            var adLeaderboard = document.querySelector('.adspace-leaderboard#adspace');
            adLeaderboard.innerHTML = leaderboard;
            adShow = 1;
    }
}

Body:
As you commented to this answer (as I expected) you placed the JS snippet right after the opening body-tag, so before the actual HTML element (same would happen if you placed this snippet in the head section of the page).
It is quite likely that someone moves the mouse during the loading of the page, and so the mousemove event might be executed before the HTML element is there and thus the ad-space will never be actually loaded.

You could fix that easily by either placing the snippet right before the </body> closing tag, or by wrapping the code in an onDomReady or onLoad event. The last two will make the code execute respectively after all DOM has been loaded or even after all assets (images, etc.) have been loaded. In your case onDomReady would be enough.

Like this:

document.onDomReady = function(){
    adShow = 0;
    document.onmousemove = function(){
        if (adShow == 0) {
                var leaderboard = CODE_FOR_AD;
                var adLeaderboard = document.querySelector('.adspace-leaderboard#adspace');
                adLeaderboard.innerHTML = leaderboard;
                adShow = 1;
        }
    }
}


问:
In JavaScript, does using await inside a loop block the loop?
Take the following loop:

```<code>for(var i=0; i<100; ++i){
    let result = await some_slow_async_function();
    do_something_with_result();
}
</code>```

Does await block the loop? Or does the i continue to be incremented while awaiting?

Is the order of do_something_with_result() guaranteed sequential with regard to i? Or does it depend on how fast the awaited function is for each i?

答:
As @realbart says, it does block the loop, which then will make the calls sequential.

If you want to trigger a ton of awaitable operations and then handle them all together, you could do something like this:

```<code>const promisesToAwait = [];
for (let i = 0; i < 100; i++) {
  promisesToAwait.push(fetchDataForId(i));
}
const responses = await Promise.all(promisesToAwait);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Take the following loop:

for(var i=0; i<100; ++i){
    let result = await some_slow_async_function();
    do_something_with_result();
}

Does await block the loop? Or does the i continue to be incremented while awaiting?

Is the order of do_something_with_result() guaranteed sequential with regard to i? Or does it depend on how fast the awaited function is for each i?

Body:
As @realbart says, it does block the loop, which then will make the calls sequential.

If you want to trigger a ton of awaitable operations and then handle them all together, you could do something like this:

const promisesToAwait = [];
for (let i = 0; i < 100; i++) {
  promisesToAwait.push(fetchDataForId(i));
}
const responses = await Promise.all(promisesToAwait);


问:
How to get File name from uploaded path in php
I uploaded the file and stored the path in the database table. when i trying to retrieve the file name it displays the full path of the particular uploaded file.

for example:
stored path in table : wp-content/uploads/images/adminupload/dummy-pdf_2.pdf

expected result : dummy-pdf_2.pdf

please anyone tell me how to get the file name from uploaded path. Thanks in advance

答:
Use basename function

$path = "wp-content/uploads/images/adminupload/dummy-pdf_2.pdf";

$filename = basename($path);


问:
Use the increased navigation-bar title in iOS 11
iOS 11 Beta 1 uses the increased navigation-bar title for almost all system-apps (it started doing this in iOS 10 and the Music app). I am wondering if Apple has a public API for this coming in iOS 11, or whether it will stay private for now.

The behavior is that the title has an increased font-size, is left aligned and will move to the navigation-bar once the user scrolls down. I've attached some screens showing this behavior in the Messages app here:

Although I could not find any reference in the UINavigationController and UINavigationBar so far, maybe someone knows some more details!

答:
The only change done to UINavigationBar API for iOS 11 is prefersLargeTitles.

Documentation here: https://developer.apple.com/documentation/uikit/uinavigationbar/

You can do it to your own apps with one small change: check "Prefers Large Titles" for your navigation bar in IB, or if you prefer to do it in code using:

```<code>navigationController?.navigationBar.prefersLargeTitles = true
</code>```

If you need to change the text attributes of the large title you need to use the new largeTitleTextAttributes property on UINavigationBar:

```<code>UINavigationBar.appearance().largeTitleTextAttributes = [
    NSAttributedString.Key.foregroundColor: UIColor.black
]
</code>```

Body:
The only change done to UINavigationBar API for iOS 11 is prefersLargeTitles.

Documentation here: https://developer.apple.com/documentation/uikit/uinavigationbar/

You can do it to your own apps with one small change: check "Prefers Large Titles" for your navigation bar in IB, or if you prefer to do it in code using:

navigationController?.navigationBar.prefersLargeTitles = true

If you need to change the text attributes of the large title you need to use the new largeTitleTextAttributes property on UINavigationBar:

UINavigationBar.appearance().largeTitleTextAttributes = [
    NSAttributedString.Key.foregroundColor: UIColor.black
]


问:
client side validation in htmlhelper without Model Class
I visited through different links but couldn't find desired answer. I am not using model for this view. Before sending data to server I want to check whether the text input is null or not.How can I validate it?</p>

```<code>@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container">
    <h2>Student Information</h2>
    @using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
    {
        <label>First Name:</label>
        <input type="text" class="form-control" name="firstname" id="f_name" />
        <button type="submit" class="btn btn-success" >Insert</button>
    }
</div>

<script>
    $(function () {
        $("#target".submit(function (event) {
            event.preventDefault();
            //return false;
        })
    })
</script>
</code>```

答:
If you dont want custom script for validating data on client side, you can use jquery.validate.js and jquery.validate.unobstrusive.js. This will work just like mvc validation rules(Actually this validation logic is generated by MVC itself on the view when client side validation is enabled).

Just add this three script file inside your page.

```<code>    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.js"></script>
</code>```

Or you can select from your Script folder inside MVC application.
And Try to add following attribute in your Htmlelement for validation.

```<code><div class="container">
    <h2>Student Information</h2>
    @using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
    {
        <label>First Name:</label>
        <input data-val="true" data-val-required="First Name field is required." type="text" class="form-control" name="firstname" id="firstname" />

        <span class="field-validation-valid" data-valmsg-for="firstname" data-valmsg-replace="true"></span>
        <button type="submit" class="btn btn-success" >Insert</button>
    }
</div>
</code>```

This will work just like MVC validation inside your view.
You can get more information how to use JqueryValidate and jquery unobtrusive by clicking on this link : http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

Body:
I visited through different links but couldn't find desired answer. I am not using model for this view. Before sending data to server I want to check whether the text input is null or not.How can I validate it?

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Student Information

    @using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
    {
        First Name:
        <input type="text" class="form-control" name="firstname" id="f_name" />
        <button type="submit" class="btn btn-success" >Insert</button>
    }

Body:
If you dont want custom script for validating data on client side, you can use jquery.validate.js and jquery.validate.unobstrusive.js. This will work just like mvc validation rules(Actually this validation logic is generated by MVC itself on the view when client side validation is enabled).

Just add this three script file inside your page.

    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.js"></script>

Or you can select from your Script folder inside MVC application.
And Try to add following attribute in your Htmlelement for validation.

<div class="container">
    <h2>Student Information</h2>
    @using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
    {
        <label>First Name:</label>
        <input data-val="true" data-val-required="First Name field is required." type="text" class="form-control" name="firstname" id="firstname" />

        <span class="field-validation-valid" data-valmsg-for="firstname" data-valmsg-replace="true"></span>
        <button type="submit" class="btn btn-success" >Insert</button>
    }
</div>

This will work just like MVC validation inside your view.
You can get more information how to use JqueryValidate and jquery unobtrusive by clicking on this link : http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html


问:
Pass whole Model through ajax call
Is it possible to pass a whole Model through my jQuery's ajax call?
For know I can only get it working if i set one variable at the time.

As the code shows I pass the iVideo_ID through the ajax call. The Video object has a lot of other fields. So instead of writing all the attributes, can i pass the whole existing object (Video Model)?

```<code>$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/UpdateComment", // Controller/View
    data: { //Passing data
        iVideo_ID: '@(Model.Video.iVideo_ID)'
    }
});
</code>```

I have tried with this but it just return a Model that is null:

```<code>$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/NyMetode", // Controller/View
    data: '@(Model)'
});
</code>```

So how can i pass the whole model? Is it possible?

EDIT:
My View Model I try to pass:

```<code>public class CommentViewModel
{
   public List<Comments> Comments { get; set; }
   public List<Tasks> Tasks { get; set; }
   public Videos Video { get; set; }
   public List<VideoTaskScores> VideoTaskScores { get; set; }
}
</code>```

答:
actually ya you can do that

just change around a bit for more simplification I.e

```<code><script>
var jsonData= @html.raw(json.encode(Model));
</code>```

then in ajax data

```<code>data: modelName : jsonData,
</code>```

just make sure in your actionresult the param name is also modelName  ie

```<code>public ActionResult ActionName(model modelName)
</code>```

Title: Pass whole Model through ajax call

Body:
Is it possible to pass a whole Model through my jQuery's ajax call?
For know I can only get it working if i set one variable at the time.

As the code shows I pass the iVideo_ID through the ajax call. The Video object has a lot of other fields. So instead of writing all the attributes, can i pass the whole existing object (Video Model)?

$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/UpdateComment", // Controller/View
    data: { //Passing data
        iVideo_ID: '@(Model.Video.iVideo_ID)'
    }
});

I have tried with this but it just return a Model that is null:

$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/NyMetode", // Controller/View
    data: '@(Model)'
});

So how can i pass the whole model? Is it possible?

EDIT:
My View Model I try to pass:

public class CommentViewModel
{
   public List<Comments> Comments { get; set; }
   public List<Tasks> Tasks { get; set; }
   public Videos Video { get; set; }
   public List<VideoTaskScores> VideoTaskScores { get; set; }
}

Body:
actually ya you can do that

just change around a bit for more simplification I.e

<script>
var jsonData= @html.raw(json.encode(Model));

then in ajax data

data: modelName : jsonData,

just make sure in your actionresult the param name is also modelName  ie

public ActionResult ActionName(model modelName)


问:
To set selected item of Spinner by value, returns -1
i am using the following code to set selected item of a spinner by value. but the position that i get is -1.

Code:

```<code>final ArrayAdapter<CharSequence> adapter1 = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_list_item_1, location_days2);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        location_days.setAdapter(adapter1);
        String b = "5 Days";
        int a = adapter.getPosition(b); //this should return 5, but returns -1
        location_days.setSelection(a);
</code>```

String Array:

private String[] location_days2 = {"Select days","1 Day", "2 Days", "3 Days", "0 Days", "5 Days","6 Days"};

答:
```<code>int a = adapter.getPosition(b);
</code>```

replace adapter with adapter1 in the above line, because you have initialized adapter as "adapter1"

Body:
i am using the following code to set selected item of a spinner by value. but the position that i get is -1.

Code:

final ArrayAdapter<CharSequence> adapter1 = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_list_item_1, location_days2);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        location_days.setAdapter(adapter1);
        String b = "5 Days";
        int a = adapter.getPosition(b); //this should return 5, but returns -1
        location_days.setSelection(a);

String Array:

private String[] location_days2 = {"Select days","1 Day", "2 Days", "3 Days", "0 Days", "5 Days","6 Days"};

Body:
int a = adapter.getPosition(b);

replace adapter with adapter1 in the above line, because you have initialized adapter as "adapter1"


问:
ASP.NET Ajax PopupControlExtender On Close event?
I have a text box with an associated popupcontrolextender.This opens a panel containing a checkboxlist.

What i want to do is add the values selected in the checkbox list to the text box when the user clicks out of the panel.

I started to use the OnselectedIndexChanged, of the checkboxlist, and update the text box after every checkbox has been checked / unchecked. But the checkboxlist is quite long and when you click one of the checkboxes near the bottom, because everything is in an update panel, the checkboxlist scrolls to the top after the autopostback - not very user-friendly.

Any ideas???

Thanks in advance.

答:
It sounds like you want to stop this behavior:

But the checkboxlist is quite long and when you click one of the checkboxes near the bottom, because everything is in an update panel, the checkboxlist scrolls to the top after the autopostback

Would that work better? Here's an oldie but a goodie article:

https://web.archive.org/web/20211020140248/https://www.4guysfromrolla.com/articles/111704-1.aspx


问:
Python create folders structure based on current date
i'm using the following var on my script to send output to one

```<code>output = "/opt/output"
</code>```

i want to adjust it to make the output relative to the date current date of trigger the script it should be structured like this

```<code>output = "/opt/output/year/month/day"
</code>```

i'm not sure if i'm using the correct way here i used the following approach

```<code>output = "/opt/output/" + today.strftime('%Y%m%d')
</code>```

any tips here

答:
i figure it by

```<code>today = datetime.datetime.now()
year = today.strftime("%Y")
month=today.strftime("%m")
day=today.strftime("%d")
output = "/opt/output/"  + year +"/" + month + "/" + day
</code>```

thats worked fine to me

Body:
i'm using the following var on my script to send output to one

output = "/opt/output"

i want to adjust it to make the output relative to the date current date of trigger the script it should be structured like this

output = "/opt/output/year/month/day"

i'm not sure if i'm using the correct way here i used the following approach

output = "/opt/output/" + today.strftime('%Y%m%d')

any tips here

Body:
i figure it by

today = datetime.datetime.now()
year = today.strftime("%Y")
month=today.strftime("%m")
day=today.strftime("%d")
output = "/opt/output/"  + year +"/" + month + "/" + day

thats worked fine to me


问:
save checked items from CheckedListBox selected Items to .txt file
i'm new to c# and windows form application.
i want to save to save selected items from checkedlistbox to a .txt file if not exist then create, if exist then append.

here's how i bind the data to my checkedlistbox, i'm not sure if this is the right way, or there's another way to add value to checkedboxlist.

```<code>public void bind_clbDepartment()
    {
        DataSet ds = DataBank3.get_department();
        DataTable dt = ds.Tables[0];

        foreach (DataRow drow in dt.Rows)
        {
            clbDepartment.Items.Add(drow["id_dept"] + ":" + drow["name_dept"]);
        }
    }

private void Save_Click(object sender, EventArgs e)
        {
            //save selected items from clbDepartment to D:\test.txt
            //create if not exist, append if exist
        }
</code>```

答:
As this article says you've got a few options

To write an array of strings to a file do this

```<code>string[] lines = { "First line", "Second line", "Third line" };
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
</code>```

To write a single string do this

```<code>string text = "A class is the most powerful data type in C#. Like a structure, a class defines the data and behavior of the data type.";
System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);
</code>```

To selective write strings in an array do this

```<code>using (System.IO.StreamWriter file =
            new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
        {
            foreach (string line in lines)
            {
                // If the line doesn't contain the word 'Second', write the line to the file.
                if (!line.Contains("Second"))
                {
                    file.WriteLine(line);
                }
            }
        }
</code>```

To append a line to the end of an existing file do this

```<code>using (System.IO.StreamWriter file =
    new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
{
    file.WriteLine("Fourth line");
}
</code>```

Body:
i'm new to c# and windows form application.
i want to save to save selected items from checkedlistbox to a .txt file if not exist then create, if exist then append.

here's how i bind the data to my checkedlistbox, i'm not sure if this is the right way, or there's another way to add value to checkedboxlist.

public void bind_clbDepartment()
    {
        DataSet ds = DataBank3.get_department();
        DataTable dt = ds.Tables[0];

        foreach (DataRow drow in dt.Rows)
        {
            clbDepartment.Items.Add(drow["id_dept"] + ":" + drow["name_dept"]);
        }
    }

private void Save_Click(object sender, EventArgs e)
        {
            //save selected items from clbDepartment to D:\test.txt
            //create if not exist, append if exist
        }

Body:
As this article says you've got a few options

To write an array of strings to a file do this

string[] lines = { "First line", "Second line", "Third line" };
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);

To write a single string do this

string text = "A class is the most powerful data type in C#. Like a structure, a class defines the data and behavior of the data type.";
System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

To selective write strings in an array do this

using (System.IO.StreamWriter file =
            new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
        {
            foreach (string line in lines)
            {
                // If the line doesn't contain the word 'Second', write the line to the file.
                if (!line.Contains("Second"))
                {
                    file.WriteLine(line);
                }
            }
        }

To append a line to the end of an existing file do this

using (System.IO.StreamWriter file =
    new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
{
    file.WriteLine("Fourth line");
}


问:
Set Delphi 5 Form on monitor where previous Form was present in dual monitor system
Delphi 5 does not have a built-in function to set a Form on a monitor where a previous Form is opened in the case of dual monitors. For this, I have imported windows dll. I searched for this and found MonitorFromWindow() and MonitorFromPoint().

I implemented MonitorFromWindow() but am not able to implement MonitorFromPoint().

How do I get the monitor and set my Form on it?

```<code>function MonitorFromWindow(hwnd: HWND; dwFlags: DWORD): HWND; stdcall; external 'User32.dll';

procedure TSmForm.AfterCreateForm(Session: ISmSession; SmHelpContext: TDM_Int32; IsDLL: Boolean);
type
  HMONITOR = type THandle;
var
  MBMonitor: HMONITOR;
const
  MONITOR_DEFAULTTONEAREST = $00000002;
begin
  //If you decide to remove the next two lines, make sure no one use this function and assume init of SmSession is here (like ScriptMaintanance etc.).
  if SmSession<>Session then
    SmSession := Session;
  if SmHelpContext > 0 then
    HelpContext := SmHelpContext;
  //Following lines ensure that if the form resides in a dll, its icon is the same as the host application's
  if (IsDLL) then
  begin
    if (Icon.Empty) and (ParentHWND <> 0) then
      SendMessage(Handle, WM_SETICON, 1, SendMessage(ParentHWND, WM_GETICON, 1, 0));
  end;

  MBMonitor := MonitorFromWindow(Self.Handle, MONITOR_DEFAULTTONEAREST);

  //HWND_NOTOPMOST
  SetWindowPos(Self.Handle, MBMonitor, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE);
end { of TSmForm.AfterCreateForm } ;
</code>```

答:
```<code>Monitor:=   screen.Forms[Screen.FormCount-1].Monitor;
Self.Left := Monitor.Left + ((Monitor.Width - Self.Width) div 2);
Self.Top :=  Monitor.Top + ((Monitor.Height - Self.Height) div 2);
</code>```

Body:
Delphi 5 does not have a built-in function to set a Form on a monitor where a previous Form is opened in the case of dual monitors. For this, I have imported windows dll. I searched for this and found MonitorFromWindow() and MonitorFromPoint().

I implemented MonitorFromWindow() but am not able to implement MonitorFromPoint().

How do I get the monitor and set my Form on it?

function MonitorFromWindow(hwnd: HWND; dwFlags: DWORD): HWND; stdcall; external 'User32.dll';

procedure TSmForm.AfterCreateForm(Session: ISmSession; SmHelpContext: TDM_Int32; IsDLL: Boolean);
type
  HMONITOR = type THandle;
var
  MBMonitor: HMONITOR;
const
  MONITOR_DEFAULTTONEAREST = $00000002;
begin
  //If you decide to remove the next two lines, make sure no one use this function and assume init of SmSession is here (like ScriptMaintanance etc.).
  if SmSession<>Session then
    SmSession := Session;
  if SmHelpContext > 0 then
    HelpContext := SmHelpContext;
  //Following lines ensure that if the form resides in a dll, its icon is the same as the host application's
  if (IsDLL) then
  begin
    if (Icon.Empty) and (ParentHWND <> 0) then
      SendMessage(Handle, WM_SETICON, 1, SendMessage(ParentHWND, WM_GETICON, 1, 0));
  end;

  MBMonitor := MonitorFromWindow(Self.Handle, MONITOR_DEFAULTTONEAREST);

  //HWND_NOTOPMOST
  SetWindowPos(Self.Handle, MBMonitor, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE);
end { of TSmForm.AfterCreateForm } ;


问:
Prev and next buttons to change divs
I'm trying to create a code in jQuery that adds the class active to the next div and removes it from the previous div and vice versa with the previous. This all in mind with animations I want to add later.

If you want to see the code with HTML and CSS:
http://codepen.io/salman15/pen/kXVmRG?editors=1010

```<code>$(document).ready(function() {
    $('#next').click(function() {
        var location = $(this).parent().parent();
        $('.active').removeClass('active');
        $('div').next('#case').addClass('active');
    });

    $('#prev').click(function() {
        var location = $(this).parent().parent();
        $('.active').removeClass('active');
        $(this).prev('#case').removeClass('active');
    });
});
</code>```

答:
```<code>//file
 $(document).ready(function(){

  $('.d1 li.s1').click(function(){
   $('li').removeClass("active");
  $(this).addClass("active");
  });
  $('ul.ddd li.ggg').click(function(){
    $('li').removeClass("active");
    $(this).addClass("active");
});
 $(".next").click(function(){
 i=1
            var $toHighlight = $('.active').next().length > 0 ? $('.active').next() : $('#MainMenu li.s1').first();
            $('.active').removeClass('active');
            $toHighlight.addClass('active');
            });

         $(".previous").click(function(){
            var $toHighlight = $('.active').prev().length > 0 ? $('.active').prev() : $('ul.mainmenu1 li.s1').last();

            $('.active').removeClass('active');
            $toHighlight.addClass('active');
        });
});
</code>```

Title: Prev and next buttons to change divs

Body:
I'm trying to create a code in jQuery that adds the class active to the next div and removes it from the previous div and vice versa with the previous. This all in mind with animations I want to add later.

If you want to see the code with HTML and CSS:
http://codepen.io/salman15/pen/kXVmRG?editors=1010

$(document).ready(function() {
    $('#next').click(function() {
        var location = $(this).parent().parent();
        $('.active').removeClass('active');
        $('div').next('#case').addClass('active');
    });

    $('#prev').click(function() {
        var location = $(this).parent().parent();
        $('.active').removeClass('active');
        $(this).prev('#case').removeClass('active');
    });
});