问:
Embedding multiple user controls into a page?
I've embedded multiple user controls into the same page. The user controls typically have 2 different views, an edit/default view and a completed view. When the user completes an edit then I switch the MultiView to the completed state. This pattern works okay in pages.

The problem is when I go back to the master view/page then the user brings back the control, the view is still in the completed state.

What are some simple methods for resetting/correcting the multiview state? I could have a Reset() function on every control but it feels like I may be able to avoid that.

Update:

This page is designed to show an account/profile view and it has the following parts:

```<code><asp:MultiView>
...read only view
<asp:EmailEditView>
<asp:AccountEditView>
</code>```

etc..

And then each of those views has a user control. Inside the user control, we have something like this

```<code><asp:multiview>
<asp:view id="edit"/>
<asp:view id="completed"/>
</code>```

I've found the following problems with this design:

When the user completes an action of user control such as changing an email. The view stays in the finished state even when they go back to it a second time.

When the user goes back to the original form the data is stale. This design really screws with the postback mechanism. If I don't use !IsPostBack on the main form for databding then my dropdownlist on the sub forms will not work. However, once I add the !isPostBack on the main form then the data becomes stale.

I can add a "reset" flag to every user control and add something like this

```<code>if ((!IsPostback) || (reset) )
</code>```

As well as resetting the view. In the other scenario, I can add an event handler to load the reload/bind the data when the user clicks "back", i.e where I change the form back.

答:
I'm trying to recreate the functionality of your problem while taking out the complexity of user controls.  Here's my best guess so far (please correct me if I'm wrong)

```<code><asp:MultiView runat="server" ID="MainMultiView" ActiveViewIndex="0">
    <asp:View runat="server" ID="DefaultView">
        Default View
        <asp:Button runat="server" ID="EditEmailButton" Text="Edit Email" OnClick="EditEmailButton_Click" />
        <asp:Button runat="server" ID="EditAccountButton" Text="Edit Account" OnClick="EditAccountButton_Click" />
    </asp:View>
    <asp:View runat="server" ID="EmailView">
        <asp:MultiView runat="server" ID="EmailMultiView" ActiveViewIndex="0">
            <asp:View runat="server" ID="EmailEditView">
                Edit Email
                <asp:Button runat="server" ID="SaveEmailButton" Text="Save"
                    onclick="SaveEmailButton_Click" />
                <asp:Button runat="server" ID="CancelEmailButton" Text="Cancel"
                    onclick="CancelEmailButton_Click" />
            </asp:View>
            <asp:View runat="server" ID="EmailCompleteView">
                Email Edit Complete!
            </asp:View>
        </asp:MultiView>
    </asp:View>
    <asp:View runat="server" ID="AccountView">
        <asp:MultiView runat="server" ID="AccountMultiView" ActiveViewIndex="0">
            <asp:View runat="server" ID="AccountEditView">
                Edit Account
                <asp:Button runat="server" ID="SaveAccountButton" Text="Save"
                    onclick="SaveAccountButton_Click" />
                <asp:Button runat="server" ID="CancelAccountButton" Text="Cancel"
                    onclick="CancelAccountButton_Click" />
            </asp:View>
            <asp:View runat="server" ID="AccountCompleteView">
                Account Edit Complete!
            </asp:View>
        </asp:MultiView>
    </asp:View>
</asp:MultiView>
</code>```

-- code behind

```<code>protected void EditEmailButton_Click(object sender, EventArgs e)
{
    MainMultiView.SetActiveView(EmailView);
}

protected void EditAccountButton_Click(object sender, EventArgs e)
{
    MainMultiView.SetActiveView(AccountView);
}

protected void SaveEmailButton_Click(object sender, EventArgs e)
{
    // Save();
    EmailMultiView.SetActiveView(EmailCompleteView);
}

protected void CancelEmailButton_Click(object sender, EventArgs e)
{
    EmailMultiView.SetActiveView(EmailCompleteView);
}

protected void SaveAccountButton_Click(object sender, EventArgs e)
{
    // Save();
    AccountMultiView.SetActiveView(AccountCompleteView);
}

protected void CancelAccountButton_Click(object sender, EventArgs e)
{
    AccountMultiView.SetActiveView(AccountCompleteView);
}
</code>```

Body:
I've embedded multiple user controls into the same page. The user controls typically have 2 different views, an edit/default view and a completed view. When the user completes an edit then I switch the MultiView to the completed state. This pattern works okay in pages.

The problem is when I go back to the master view/page then the user brings back the control, the view is still in the completed state.

What are some simple methods for resetting/correcting the multiview state? I could have a Reset() function on every control but it feels like I may be able to avoid that.

Update:

This page is designed to show an account/profile view and it has the following parts:

<asp:MultiView>
...read only view
<asp:EmailEditView>
<asp:AccountEditView>

etc..

And then each of those views has a user control. Inside the user control, we have something like this

<asp:multiview>
<asp:view id="edit"/>
<asp:view id="completed"/>

I've found the following problems with this design:

When the user completes an action of user control such as changing an email. The view stays in the finished state even when they go back to it a second time.

When the user goes back to the original form the data is stale. This design really screws with the postback mechanism. If I don't use !IsPostBack on the main form for databding then my dropdownlist on the sub forms will not work. However, once I add the !isPostBack on the main form then the data becomes stale.

I can add a "reset" flag to every user control and add something like this

if ((!IsPostback) || (reset) )

As well as resetting the view. In the other scenario, I can add an event handler to load the reload/bind the data when the user clicks "back", i.e where I change the form back.

Body:
I'm trying to recreate the functionality of your problem while taking out the complexity of user controls.  Here's my best guess so far (please correct me if I'm wrong)

<asp:MultiView runat="server" ID="MainMultiView" ActiveViewIndex="0">
    <asp:View runat="server" ID="DefaultView">
        Default View
        <asp:Button runat="server" ID="EditEmailButton" Text="Edit Email" OnClick="EditEmailButton_Click" />
        <asp:Button runat="server" ID="EditAccountButton" Text="Edit Account" OnClick="EditAccountButton_Click" />
    </asp:View>
    <asp:View runat="server" ID="EmailView">
        <asp:MultiView runat="server" ID="EmailMultiView" ActiveViewIndex="0">
            <asp:View runat="server" ID="EmailEditView">
                Edit Email
                <asp:Button runat="server" ID="SaveEmailButton" Text="Save"
                    onclick="SaveEmailButton_Click" />
                <asp:Button runat="server" ID="CancelEmailButton" Text="Cancel"
                    onclick="CancelEmailButton_Click" />
            </asp:View>
            <asp:View runat="server" ID="EmailCompleteView">
                Email Edit Complete!
            </asp:View>
        </asp:MultiView>
    </asp:View>
    <asp:View runat="server" ID="AccountView">
        <asp:MultiView runat="server" ID="AccountMultiView" ActiveViewIndex="0">
            <asp:View runat="server" ID="AccountEditView">
                Edit Account
                <asp:Button runat="server" ID="SaveAccountButton" Text="Save"
                    onclick="SaveAccountButton_Click" />
                <asp:Button runat="server" ID="CancelAccountButton" Text="Cancel"
                    onclick="CancelAccountButton_Click" />
            </asp:View>
            <asp:View runat="server" ID="AccountCompleteView">
                Account Edit Complete!
            </asp:View>
        </asp:MultiView>
    </asp:View>
</asp:MultiView>

-- code behind

protected void EditEmailButton_Click(object sender, EventArgs e)
{
    MainMultiView.SetActiveView(EmailView);
}

protected void EditAccountButton_Click(object sender, EventArgs e)
{
    MainMultiView.SetActiveView(AccountView);
}

protected void SaveEmailButton_Click(object sender, EventArgs e)
{
    // Save();
    EmailMultiView.SetActiveView(EmailCompleteView);
}

protected void CancelEmailButton_Click(object sender, EventArgs e)
{
    EmailMultiView.SetActiveView(EmailCompleteView);
}

protected void SaveAccountButton_Click(object sender, EventArgs e)
{
    // Save();
    AccountMultiView.SetActiveView(AccountCompleteView);
}

protected void CancelAccountButton_Click(object sender, EventArgs e)
{
    AccountMultiView.SetActiveView(AccountCompleteView);
}


来源: stackexchange

问:
Powershell script not running on scheduled task
I can run the script outside and inside the Task Scheduler. But the scheduled tasks will not run the script automatically when triggered. I have tried configuring the Local Security Policies by changing,  User Account Control: Admin Approval Mode for the Built-i Administrator account (Not Defined) - User Account Control: Run all administrators in Admin Approval Mode (Disabled) - User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode (Elevate without prompting). This did not work. Any help would be great. Thanks.

Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add arguments: -NoProfile -ExecutionPolicy Bypass -File C:\Users\Andersen\Desktop\moveFiles.ps1

```<code>Try
{

$Time = Get-Date

if(Test-Path C:\Users\Andersen\Desktop\src) {
    "Source exists."
} else {
    Write-Output "This script made a read attempt at [$Time]. Source (C:\Users\Andersen\Desktop\src) cannot be found." | out-file C:\Users\Andersen\Desktop\KofaxScriptErrorLog.txt -Append
    Exit
}

$IDsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\ID - Sub Invoice").Count
$Jsrc  = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\J - Sub Invoice").Count
$ORsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR - Sub Invoice").Count
$OR2   = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR2 - Sub Invoice").Count
$SCsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\SC Invoice").Count
$WAsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\WA - Sub Invoice").Count

# move Kofax ID files to ID folder in Egnyte
If ($IDsrc -ne 0){
Get-ChildItem  -Path "C:\Users\Andersen\Desktop\src\ID - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\ID - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax J files to J folder in Egnyte
If ($Jsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\J - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\J - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax OR files to OR folder in Egnyte
If ($ORsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\OR - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax OR2 files to OR2 folder in Egnyte
If ($OR2src -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR2 - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\OR2 - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax SC(multi) files to SC(multi) folder in Egnyte
If ($SCsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\SC Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\SC Invoice" -Force -ErrorAction Stop
                    }
# move Kofax WA files to WA folder in Egnyte
If ($WAsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\WA - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\WA - Sub Invoice" -Force -ErrorAction Stop
    }

}

Catch {

$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
    "The script to move files from the Kofax server to Egynte made a run attempt at $Time. Error Details: $ErrorMessage $FailedItem" | out-file C:\Users\Andersen\Desktop\KofaxScriptErrorLog.txt -Append
    Break
}

Finally
{

    "This script made a complete read attempt at $Time" | out-file C:\Users\Andersen\Desktop\KofaxScriptLog.txt -Append
}
</code>```

答:
Ensure you have your execution to unrestricted.

```<code>Set-ExecutionPolicy Unrestricted
</code>```

And add the following action into the Program\Script section and click Yes on the prompt that appears.

```<code>PowerShell.exe "& 'C:\LocationFolder\YourScript.ps1'"
</code>```

If you can not set your execution policy to unrestricted just add -NoProfile -ExecutionPolicy Bypass to the above command.

ContentLicense: CC BY-SA 4.0

Body:
I can run the script outside and inside the Task Scheduler. But the scheduled tasks will not run the script automatically when triggered. I have tried configuring the Local Security Policies by changing,  User Account Control: Admin Approval Mode for the Built-i Administrator account (Not Defined) - User Account Control: Run all administrators in Admin Approval Mode (Disabled) - User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode (Elevate without prompting). This did not work. Any help would be great. Thanks.

Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add arguments: -NoProfile -ExecutionPolicy Bypass -File C:\Users\Andersen\Desktop\moveFiles.ps1

Try
{

$Time = Get-Date

if(Test-Path C:\Users\Andersen\Desktop\src) {
    "Source exists."
} else {
    Write-Output "This script made a read attempt at [$Time]. Source (C:\Users\Andersen\Desktop\src) cannot be found." | out-file C:\Users\Andersen\Desktop\KofaxScriptErrorLog.txt -Append
    Exit
}

$IDsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\ID - Sub Invoice").Count
$Jsrc  = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\J - Sub Invoice").Count
$ORsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR - Sub Invoice").Count
$OR2   = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR2 - Sub Invoice").Count
$SCsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\SC Invoice").Count
$WAsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\WA - Sub Invoice").Count

# move Kofax ID files to ID folder in Egnyte
If ($IDsrc -ne 0){
Get-ChildItem  -Path "C:\Users\Andersen\Desktop\src\ID - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\ID - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax J files to J folder in Egnyte
If ($Jsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\J - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\J - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax OR files to OR folder in Egnyte
If ($ORsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\OR - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax OR2 files to OR2 folder in Egnyte
If ($OR2src -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR2 - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\OR2 - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax SC(multi) files to SC(multi) folder in Egnyte
If ($SCsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\SC Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\SC Invoice" -Force -ErrorAction Stop
                    }
# move Kofax WA files to WA folder in Egnyte
If ($WAsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\WA - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\WA - Sub Invoice" -Force -ErrorAction Stop
    }

}

Catch {

$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
    "The script to move files from the Kofax server to Egynte made a run attempt at $Time. Error Details: $ErrorMessage $FailedItem" | out-file C:\Users\Andersen\Desktop\KofaxScriptErrorLog.txt -Append
    Break
}

Finally
{

    "This script made a complete read attempt at $Time" | out-file C:\Users\Andersen\Desktop\KofaxScriptLog.txt -Append
}

Body:
Ensure you have your execution to unrestricted.

Set-ExecutionPolicy Unrestricted

And add the following action into the Program\Script section and click Yes on the prompt that appears.

PowerShell.exe "& 'C:\LocationFolder\YourScript.ps1'"

If you can not set your execution policy to unrestricted just add -NoProfile -ExecutionPolicy Bypass to the above command.

ContentLicense: CC BY-SA 3.0


问:
iOS UILabel bounding rectangle not sized correctly
I have a UILabel (as highlighted in yellow), which has the following conditions applied to it.

Label has variable text length

Font set to 40

Minimum font-size set to 20

Number of lines set to 3

Although this looks like a duplicated question I believe it is not. The issue I am having is that when the text exceeds the available 3 line length after being sized-down to 20 points, the UILabel's bounding box is sized incorrectly (i.e. note the extraneous spacing above and below the text).

The end result should be a UILabel without any spacing. Is there are solution to this, while keeping the number of lines set to 3?

答:
That looks like a bug. If you increase your base font size, you will see the space increase. Also, if you inspect the layout at runtime, you will see the content size to be calculated as too big.

My guess is, UILabel takes your original font size (40) to calculate the content size for 3 lines of text and does not take into account that the font size has already been decreased before truncation.

I fiddled with content hugging/compression priorities but could not make it work either.

The only workaround I found was to manually set the font size down to 20. That will get you the frame you want.


问:
Why do I get the error 'Method execute in android.os.AsyncTask not mocked'
I'm writing an Android app which needs to listen for UDP broadcast msgs.

I'm trying to mock the AsyncTask in a listener class so I can unit test it.

The problem is I always get the error
java.lang.RuntimeException: Method execute in android.os.AsyncTask not mocked.

```<code>public class DiscoveryListener
{
    WorkGroupEventHandler workGroupEventHandler;

    private AsyncTask<Void, Void, Void> asyncTask;
    private boolean listener_active = false;

    public boolean GetListener_active()
    {
        return listener_active;
    }

    public DiscoveryListener(WorkGroupEventHandler eventHandler)
    {
        workGroupEventHandler = eventHandler;
    }

    public void Start()
    {
        if (listener_active == false)
        {
            listener_active = true;
            RunUdpListener();
        }
    }

    public void Stop()
    {
        listener_active = false;
        asyncTask.cancel(true);
    }

    public void RunUdpListener()
    {
        asyncTask = new AsyncTask<Void, Void, Void>()
        {

        @Override
        protected Void doInBackground(Void... params)
        {
            byte[] msg = new byte[4096];
            DatagramPacket datagramPacket = new DatagramPacket(msg, msg.length);
            MulticastSocket multicastReceiveSocket = null;

            try
            {
                multicastReceiveSocket = new MulticastSocket( 60000 );

                while (listener_active)
                {
                    if (isCancelled() == false)
                    {
                        multicastReceiveSocket.receive(datagramPacket);
                        ProcessIncommingMessage(datagramPacket.getAddress(), msg);
                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                if (multicastReceiveSocket != null)
                {
                    multicastReceiveSocket.close();
                }
            }

            return null;
            }
        };

        asyncTask.execute();
    }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest({android.util.Log.class, android.os.AsyncTask.class})
public class DiscoveryListenerUnitTest
{
    private WorkGroupEventHandler eventHandler = new WorkGroupEventHandler()
    {
        @Override
        public void onWorkGroupEventHandle(String IpAddress, String Workgroup, String SerialNumber)
        {
        }
    };

    private DiscoveryListener discoveryListener = new DiscoveryListener(eventHandler);
    private AsyncTask asyncTask;

    @Test
    public void discoveryListener_doesStart() throws Exception
    {
        PowerMockito.mockStatic(android.util.Log.class);

        PowerMockito.whenNew(AsyncTask.class).withNoArguments().thenReturn(asyncTask);
        asyncTask = PowerMockito.mock(AsyncTask.class);
        when(asyncTask.execute()).thenReturn(null);

        discoveryListener.Start();
        assertEquals(true, discoveryListener.GetListener_active());
    }
}
</code>```

答:
AsyncTask.execute is final, and Mockito can't mock final classes or methods.

```<code>    Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.
</code>```

Specifically, this is because Java can resolve the link at compile time, which means Mockito can't use its generated subclasses and method overrides to change the behavior.

You may choose to use Powermock, which uses a special classloader to rewrite the old behavior, or Robolectric, which does the same but replaces classes with Android-specific test-friendly alternate implementations ("shadows") including one for AsyncTask.

Body:
I'm writing an Android app which needs to listen for UDP broadcast msgs.

I'm trying to mock the AsyncTask in a listener class so I can unit test it.

The problem is I always get the error
java.lang.RuntimeException: Method execute in android.os.AsyncTask not mocked.

public class DiscoveryListener
{
    WorkGroupEventHandler workGroupEventHandler;

    private AsyncTask<Void, Void, Void> asyncTask;
    private boolean listener_active = false;

    public boolean GetListener_active()
    {
        return listener_active;
    }

    public DiscoveryListener(WorkGroupEventHandler eventHandler)
    {
        workGroupEventHandler = eventHandler;
    }

    public void Start()
    {
        if (listener_active == false)
        {
            listener_active = true;
            RunUdpListener();
        }
    }

    public void Stop()
    {
        listener_active = false;
        asyncTask.cancel(true);
    }

    public void RunUdpListener()
    {
        asyncTask = new AsyncTask<Void, Void, Void>()
        {

        @Override
        protected Void doInBackground(Void... params)
        {
            byte[] msg = new byte[4096];
            DatagramPacket datagramPacket = new DatagramPacket(msg, msg.length);
            MulticastSocket multicastReceiveSocket = null;

            try
            {
                multicastReceiveSocket = new MulticastSocket( 60000 );

                while (listener_active)
                {
                    if (isCancelled() == false)
                    {
                        multicastReceiveSocket.receive(datagramPacket);
                        ProcessIncommingMessage(datagramPacket.getAddress(), msg);
                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                if (multicastReceiveSocket != null)
                {
                    multicastReceiveSocket.close();
                }
            }

            return null;
            }
        };

        asyncTask.execute();
    }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest({android.util.Log.class, android.os.AsyncTask.class})
public class DiscoveryListenerUnitTest
{
    private WorkGroupEventHandler eventHandler = new WorkGroupEventHandler()
    {
        @Override
        public void onWorkGroupEventHandle(String IpAddress, String Workgroup, String SerialNumber)
        {
        }
    };

    private DiscoveryListener discoveryListener = new DiscoveryListener(eventHandler);
    private AsyncTask asyncTask;

    @Test
    public void discoveryListener_doesStart() throws Exception
    {
        PowerMockito.mockStatic(android.util.Log.class);

        PowerMockito.whenNew(AsyncTask.class).withNoArguments().thenReturn(asyncTask);
        asyncTask = PowerMockito.mock(AsyncTask.class);
        when(asyncTask.execute()).thenReturn(null);

        discoveryListener.Start();
        assertEquals(true, discoveryListener.GetListener_active());
    }
}

Body:
AsyncTask.execute is final, and Mockito can't mock final classes or methods.

    Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.

Specifically, this is because Java can resolve the link at compile time, which means Mockito can't use its generated subclasses and method overrides to change the behavior.

You may choose to use Powermock, which uses a special classloader to rewrite the old behavior, or Robolectric, which does the same but replaces classes with Android-specific test-friendly alternate implementations ("shadows") including one for AsyncTask.


问:
Get all the content within <style> tag in a html file using jquery
I have a html file and some css written inside style tag. I have requirement to extract text inside this tag. eg: </p>

```<code><style>
    html,body {
        margin: 0px;
        width:100%;
    }
    .center-text {
        text-align: center;
    }
</style>
</code>```

<p>I need to extract values inside this tag in a string using jquery. I tried several posts but couldn't get any appropriate answer.  </p>

答:
have you tried this?

```<code>$("#YourDiv").html($("style").html())
</code>```

this will get css code as string and put it into div
if you need to save it to db you can send it via ajax to your server

Body:
I have a html file and some css written inside style tag. I have requirement to extract text inside this tag. eg:

I need to extract values inside this tag in a string using jquery. I tried several posts but couldn't get any appropriate answer.

Body:
have you tried this?

$("#YourDiv").html($("style").html())

this will get css code as string and put it into div
if you need to save it to db you can send it via ajax to your server


问:
How to iterate over json response array
I have a question about Gatling.

I need to get the following response:

```<code>[
{
"id": 1,
"name": "Jack"
},
{
"id": 2,
"name": "John"
}
]
</code>```

grab those ids, iterate over them and make a new request for each of them.
So far I have this:

```<code>.exec(
            http("Image list")
                .get("/api/img")
                .headers(headers_0)
                .check(
                    jsonPath("$..id").findAll.saveAs("imgs")
                )
        )
</code>```

It successfuly saves ids to "imgs" which is session variable but I am not able to iterate over them or process it at all.
How can I process it? I am new to Gatling and Scala so I have no idea how to approach this.
Please help.

答:
You can treat the imgs session variable as a Scala List:

```<code>val ids = session("imgs").as[List[Int]]
ids.foreach(id => ...)
</code>```

An update to reflect the fact that the internal implementation is now a Vector, as OP has discovered:

```<code>val ids = session("imgs").as[Seq[Int]]
</code>```

Title: How to iterate over json response array

Body:
I have a question about Gatling.

I need to get the following response:

[
{
"id": 1,
"name": "Jack"
},
{
"id": 2,
"name": "John"
}
]

grab those ids, iterate over them and make a new request for each of them.
So far I have this:

.exec(
            http("Image list")
                .get("/api/img")
                .headers(headers_0)
                .check(
                    jsonPath("$..id").findAll.saveAs("imgs")
                )
        )

It successfuly saves ids to "imgs" which is session variable but I am not able to iterate over them or process it at all.
How can I process it? I am new to Gatling and Scala so I have no idea how to approach this.
Please help.

Body:
You can treat the imgs session variable as a Scala List:

val ids = session("imgs").as[List[Int]]
ids.foreach(id => ...)

An update to reflect the fact that the internal implementation is now a Vector, as OP has discovered:

val ids = session("imgs").as[Seq[Int]]


问:
Excel 2010 - Break Links
I have inherited an Excel 2010 file which, when I click on 'Edit Link', has two links to files I cannot access. These links cannot be updated and are no linger needed....but for the life of me I cannot delete, or break them!

I get the prompt:

'Breaking links permanently converts formulas and external references
  to their existing values. Because this cannot be undone, you may wish
  to save another copy of this file...Are you sure you want to break
  links?'

To which I most vehemently reply by clicking 'Break links'.

Yet they are still there!!!!

Any advice?

Thanks in advance

答:
Try copying the sheet to new workbook

Right click on Sheet name>Move or Copy>new book

and copy paste the whole values as "Values and Number" formatting.

next save it as new workbook and delete your old version.

Title: Excel 2010 - Break Links


问:
How to compile PHP to make it independend from system libraries?
I need a standalone independent-from-system-libraries version of PHP to be able to distribute it as a .zip file containing binaries. Previously the .zip was containing libxml2.so.2, libpng12.so.0, php.ini and php executable.
Recently I needed to add some functionalities and recompile the PHP. I did it with:

```<code>./configure \
    --prefix=/home/user/php/out \
    --libdir=. \
    --enable-static=YES \
    --enable-shared=NO \
    --with-pdo_mysql \
    --with-gd \
    --with-mysql \
    --enable-zip \
    --enable-zend-multibyte \
    --enable-cgi \
    --enable-fastcgi \
    --with-ldap=shared
make && make install
</code>```

Then I took php from out/bin and libmysqlclient.so.16 from /usr/lib/. But the new php doesn't want to pick up the library. Once I run it I get the following error:

```<code>./php: error while loading shared libraries: libmysqlclient.so.16: cannot open shared object file: No such file or directory
</code>```

libmysqlclient.so.16 and php are in the same directory. If i put libmysqlclient.so.16 to /usr/lib, php works fine.

Is there any additional option that I've forgotten about during compilation? Why isn't the "--libdir=." option working?

答:
First, the directive is --with-libdir not --libdir. Second, I think it is relative to /usr, so putting . there means you need to put the shared libraries into /usr.

If you have done any C coding with shared libraries, you must know about ld. The easiest way to handle shared libraries path is to use ld.

You can set the library path for the current (shell) session:

```<code>bash-4.1$ export LD_LIBRARY_PATH=/path/to/your/libs
</code>```

You can also configure ld to do it all the time:

```<code>bash-4.1$ echo /path/to/your/libs >> /etc/ld.so.conf
bash-4.1$ ldconfig
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need a standalone independent-from-system-libraries version of PHP to be able to distribute it as a .zip file containing binaries. Previously the .zip was containing libxml2.so.2, libpng12.so.0, php.ini and php executable.
Recently I needed to add some functionalities and recompile the PHP. I did it with:

./configure \
    --prefix=/home/user/php/out \
    --libdir=. \
    --enable-static=YES \
    --enable-shared=NO \
    --with-pdo_mysql \
    --with-gd \
    --with-mysql \
    --enable-zip \
    --enable-zend-multibyte \
    --enable-cgi \
    --enable-fastcgi \
    --with-ldap=shared
make && make install

Then I took php from out/bin and libmysqlclient.so.16 from /usr/lib/. But the new php doesn't want to pick up the library. Once I run it I get the following error:

./php: error while loading shared libraries: libmysqlclient.so.16: cannot open shared object file: No such file or directory

libmysqlclient.so.16 and php are in the same directory. If i put libmysqlclient.so.16 to /usr/lib, php works fine.

Is there any additional option that I've forgotten about during compilation? Why isn't the "--libdir=." option working?

Body:
First, the directive is --with-libdir not --libdir. Second, I think it is relative to /usr, so putting . there means you need to put the shared libraries into /usr.

If you have done any C coding with shared libraries, you must know about ld. The easiest way to handle shared libraries path is to use ld.

You can set the library path for the current (shell) session:

bash-4.1$ export LD_LIBRARY_PATH=/path/to/your/libs

You can also configure ld to do it all the time:

bash-4.1$ echo /path/to/your/libs >> /etc/ld.so.conf
bash-4.1$ ldconfig


问:
How to rout the URL in asp.net
I have a page in my asp.net application, using this page with an number of links to open it, now I have a new version of same page with different name and extra functionality.

I need both page should be serve by same links depend upon user permission, suppose user "A" have permission to access old version of page then he should get old one and if user "B" has permission to access newer version of page then he should get new page, the page access permission logic will be derived from database.

I have an idea to do it by using a common page that will be linked with every link in application, under that common page I can check which page access current user has and redirect him accordingly, but I do not want to change every link in my application to change the old page link with common page.

I need some concrete functionality of asp.net application like URL routing.

Please help if any one have any Idea on this.

答:
On the Page_Load of your login page, you'll want to check if the user is authenticated, and if they are to redirect them to your access denied page:</p>

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if(!User.IsInRole("A"))
    {
           Response.Redirect("~/NewPage.aspx");
    }
}
</code>```

Title: How to rout the URL in asp.net

Body:
On the Page_Load of your login page, you'll want to check if the user is authenticated, and if they are to redirect them to your access denied page:

protected void Page_Load(object sender, EventArgs e)
{
    if(!User.IsInRole("A"))
    {
           Response.Redirect("~/NewPage.aspx");
    }
}


问:
Calculator should accepting all operators
Can u please help on this on this calculator.

答:
The output is not coming for this. the text box can accept any operator continuously and should accept all operators at the time.
SimpleCalculadorajQuery.css
SimpleCalculadorajQuery.js</p>


问:
SSH2 Not Working On New Server
We have changed hosting companies and where ssh2 was working it no longer works. We have ssh2 enabled on the new server along with allow_url_fopen enabled.

The only difference I can see is that the old server used PHP 5.4.45 and the new server is using PHP 5.6.28.

However, I now get the following error.
Could not open remote file: ssh2.sftp://Resource id #337/my/directory/file.txt

Here is an example of my code:

```<code>$remote_host = "myhostinfohere";
$remote_port = 22;
$remote_user = "myuser";
$remote_pass = "mypassword";
$remote_dir = "/my/directory/";
$remote_file = 'file.txt';

try {
    $remote_conn = ssh2_connect($remote_host, $remote_port);
} catch (Exception $e) {
    die("could not connect to ".$remote_host);
}

try {
    ssh2_auth_password($remote_conn, $remote_user, $remote_pass);
} catch (Exception $e) {
    die("Password failed on ".$remote_host);
}

$sftp = ssh2_sftp($remote_conn);

$fetch_string = "ssh2.sftp://$sftp" . $remote_dir . $remote_file;

//If I add this it says it doesn't exists for some reason even though I can see the file if I log in remotely.
$fileExists = file_exists($fetch_string);
if (!$fileExists) {
    die('File does not exist');
}

$stream = fopen($fetch_string, 'r');

if (!$stream) {
    die("Could not open remote file: " . $fetch_string . "\n");
}
</code>```

Again, this same code works on the old server but doesn't on the new server. What am I missing? I can easily copy the file to my server with ssh2_scp_recv() which works fine so I'm not sure what is happening with the fopen() function.

答:
I also faced the same problem and I struggled a lot. For me its fixed now.

This is what I did:

My PHP version: 5.6.25

Downloaded the latest php_ssh2.dll from:  https://phpfashion.com/php-ssh2-dll-for-php-5-6-and-7-0 (php_ssh2.dll for PHP 5.6 x64)

Replaced the php_ssh2.dll in the following location : "C:\wamp64\bin\php\php5.6.25\ext" & restarted all my services.

Title: SSH2 Not Working On New Server

Body:
We have changed hosting companies and where ssh2 was working it no longer works. We have ssh2 enabled on the new server along with allow_url_fopen enabled.

The only difference I can see is that the old server used PHP 5.4.45 and the new server is using PHP 5.6.28.

However, I now get the following error.
Could not open remote file: ssh2.sftp://Resource id #337/my/directory/file.txt

Here is an example of my code:

$remote_host = "myhostinfohere";
$remote_port = 22;
$remote_user = "myuser";
$remote_pass = "mypassword";
$remote_dir = "/my/directory/";
$remote_file = 'file.txt';

try {
    $remote_conn = ssh2_connect($remote_host, $remote_port);
} catch (Exception $e) {
    die("could not connect to ".$remote_host);
}

try {
    ssh2_auth_password($remote_conn, $remote_user, $remote_pass);
} catch (Exception $e) {
    die("Password failed on ".$remote_host);
}

$sftp = ssh2_sftp($remote_conn);

$fetch_string = "ssh2.sftp://$sftp" . $remote_dir . $remote_file;

//If I add this it says it doesn't exists for some reason even though I can see the file if I log in remotely.
$fileExists = file_exists($fetch_string);
if (!$fileExists) {
    die('File does not exist');
}

$stream = fopen($fetch_string, 'r');

if (!$stream) {
    die("Could not open remote file: " . $fetch_string . "\n");
}

Again, this same code works on the old server but doesn't on the new server. What am I missing? I can easily copy the file to my server with ssh2_scp_recv() which works fine so I'm not sure what is happening with the fopen() function.


问:
Entity Framework 4: What causes .Take(10) to return 20 records?
I believe I am doing the following:

```<code> var myQuery = Products.Where( p => p.deptid = 3);
 var myCount = Products.Count();
 var myResult = myQuery.OrderBy( p => p.deptname).Skip(10).Take(10);
 //then return an object with a count property and a List<Product> property.
</code>```

Sometimes, this returns double the take amount.

There are a few layers to my solution, namely a Repository and a Service layer.  I am pretty sure that I am not ordering, skipping, nor taking in my repository, and this is the service layer code.  What could cause myResult to have more than 10 records when I take 10 records?

答:
I am fairly sure that I did an OrderBy() then did another OrderBy().Skip().Take().  The Skip().Take() probably used the inner ID to select records.

I went through all application layers to ensure that only one OrderBy().Skip().Take() occurred, and all was fixed.

However, I cannot recreate the problem to save my life.  I don't know if this was the solution.

Body:
I believe I am doing the following:

 var myQuery = Products.Where( p => p.deptid = 3);
 var myCount = Products.Count();
 var myResult = myQuery.OrderBy( p => p.deptname).Skip(10).Take(10);
 //then return an object with a count property and a List<Product> property.

Sometimes, this returns double the take amount.

There are a few layers to my solution, namely a Repository and a Service layer.  I am pretty sure that I am not ordering, skipping, nor taking in my repository, and this is the service layer code.  What could cause myResult to have more than 10 records when I take 10 records?


问:
What is the time complexity of leaflet function onEachFeature function here
What is the complexity of the leaflet function onEachFeature in general? is it the same as the complexity of a for loop when it comes to processing each key in a big geojson file?

答:
onEachFeature is a user-defined function, and thus its algorithmical complexity cannot be known beforehand.

It does get called once per GeoJSON Feature on initialization of a L.GeoJSON instance, and whenever the .addData() method of a L.GeoJSON is called.

Also take into account that instantiating any L.Circle, L.Polyline or L.Polygon has a complexity of O(n*log(n)), where n is the number of points in the geometry, due to usage of a Douglas-Peucker simplification.

Thus, complexity of adding features to a L.GeoJSON should be of a magnitude like

```<code> O( m * (n*log(n) + f ) )
</code>```

Where m is the number of features, n is the number of points/vertices per feature, and f is the complexity of the user-defined onEachFeature function.

Body:
onEachFeature is a user-defined function, and thus its algorithmical complexity cannot be known beforehand.

It does get called once per GeoJSON Feature on initialization of a L.GeoJSON instance, and whenever the .addData() method of a L.GeoJSON is called.

Also take into account that instantiating any L.Circle, L.Polyline or L.Polygon has a complexity of O(n*log(n)), where n is the number of points in the geometry, due to usage of a Douglas-Peucker simplification.

Thus, complexity of adding features to a L.GeoJSON should be of a magnitude like

 O( m * (n*log(n) + f ) )

Where m is the number of features, n is the number of points/vertices per feature, and f is the complexity of the user-defined onEachFeature function.


问:
Swift indexPathsForSelectedRows returns nil
I am working on a tableView, goal is to implement a expandible/collapsible tableView cells. The number of cells is completely dynamic.

I have things working, but with a small problem. I am using didSelectRowAtIndexPath to toggle expand/collapse cell. So what happens now is the toggle executes by tapping anywhere on the cell. :-(

Inside the cell, I have two UIViews (Header and Detail precisely). I need the toggle expand/collapse to work only when I tap on Header and not the whole cell.

For that, I am fetching the indexPath like here but that doesn't work since indexPathsForSelectedRows returns nil.

```<code>func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myVouchers.count
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if selectedIndex == indexPath.row {
            return 150.0
        }
        else {
            return 40.0
        }
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        cell = tableView.dequeueReusableCellWithIdentifier("CollapsedCell", forIndexPath: indexPath) as! CollapsedCell

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(VoucherDetailViewController.expandCell(_:)))
        (cell as! CollapsedCell).headerView.addGestureRecognizer(tapGestureRecognizer)

        return cell
    }

    func getIndexPathForSelectedCell() -> NSIndexPath? {

        var indexPath: NSIndexPath?

        if tableView.indexPathsForSelectedRows?.count > 0 {   //**nil is returned here**
            indexPath = (tableView.indexPathsForSelectedRows?[0])! as NSIndexPath
        }
        return indexPath
    }

    func expandCell(sender: UITapGestureRecognizer) {
        if let myIndexPath = getIndexPathForSelectedCell() {
            if selectedIndex == myIndexPath.row {
                selectedIndex = -1
            }
            else {
                selectedIndex = myIndexPath.row
            }

            self.tableView.beginUpdates()
            self.tableView.reloadRowsAtIndexPaths([myIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
            self.tableView.endUpdates()
        }
    }
</code>```

Could someone give me a clue why the indexPathsForSelectedRows returns nil?

Many Thanks!

UPDATE 1:
Current Working demo

When I add my expand cell logic in didSelectRowAtIndexPath and remove my tapGestureRecognizer for the view inside the cell - it looks like this -

```<code>func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        if selectedIndex == indexPath.row {
            selectedIndex = -1
        }
        else {
            selectedIndex = indexPath.row
        }

        self.tableView.beginUpdates()
        self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        self.tableView.endUpdates()
    }
</code>```

答:
You got this bug because

```<code>self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
</code>```

reloads and deselect your rows.

You just select row, after that, you reload row (this action will deselect this row) and later you want to get a selected rows using

```<code>tableView.indexPathsForSelectedRows
</code>```

but table view does not have any selected rows at this moment.

As a solution, you can store selected indexPath in new variable, and use this variable instead of

```<code>tableView.indexPathsForSelectedRows
</code>```

Body:
I am working on a tableView, goal is to implement a expandible/collapsible tableView cells. The number of cells is completely dynamic.

I have things working, but with a small problem. I am using didSelectRowAtIndexPath to toggle expand/collapse cell. So what happens now is the toggle executes by tapping anywhere on the cell. :-(

Inside the cell, I have two UIViews (Header and Detail precisely). I need the toggle expand/collapse to work only when I tap on Header and not the whole cell.

For that, I am fetching the indexPath like here but that doesn't work since indexPathsForSelectedRows returns nil.

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myVouchers.count
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if selectedIndex == indexPath.row {
            return 150.0
        }
        else {
            return 40.0
        }
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        cell = tableView.dequeueReusableCellWithIdentifier("CollapsedCell", forIndexPath: indexPath) as! CollapsedCell

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(VoucherDetailViewController.expandCell(_:)))
        (cell as! CollapsedCell).headerView.addGestureRecognizer(tapGestureRecognizer)

        return cell
    }

    func getIndexPathForSelectedCell() -> NSIndexPath? {

        var indexPath: NSIndexPath?

        if tableView.indexPathsForSelectedRows?.count > 0 {   //**nil is returned here**
            indexPath = (tableView.indexPathsForSelectedRows?[0])! as NSIndexPath
        }
        return indexPath
    }

    func expandCell(sender: UITapGestureRecognizer) {
        if let myIndexPath = getIndexPathForSelectedCell() {
            if selectedIndex == myIndexPath.row {
                selectedIndex = -1
            }
            else {
                selectedIndex = myIndexPath.row
            }

            self.tableView.beginUpdates()
            self.tableView.reloadRowsAtIndexPaths([myIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
            self.tableView.endUpdates()
        }
    }

Could someone give me a clue why the indexPathsForSelectedRows returns nil?

Many Thanks!

UPDATE 1:
Current Working demo

When I add my expand cell logic in didSelectRowAtIndexPath and remove my tapGestureRecognizer for the view inside the cell - it looks like this -

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        if selectedIndex == indexPath.row {
            selectedIndex = -1
        }
        else {
            selectedIndex = indexPath.row
        }

        self.tableView.beginUpdates()
        self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        self.tableView.endUpdates()
    }

Body:
You got this bug because

self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

reloads and deselect your rows.

You just select row, after that, you reload row (this action will deselect this row) and later you want to get a selected rows using

tableView.indexPathsForSelectedRows

but table view does not have any selected rows at this moment.

As a solution, you can store selected indexPath in new variable, and use this variable instead of

tableView.indexPathsForSelectedRows


问:
FeathersJS - How to cancel hook on error
In my registration service I've created a 'before' hook to check if the user is already registered to a tournament. If the user is found to be registered, I have it throwing an error.

Per feathersjs documentation:

If a promise fails, the error will be propagated immediately and will
  exit out of the promise chain.

The problem I'm having is the error is being "triggered" and showing the user has already registered, but the registration still takes place. Meaning, the hook is never "exited".

Here is my function

```<code>exports.checkRegistered = () => {
    return (hook) => {
        let tourneyId = hook.data.tourneyId
        let userId = hook.data.userId

        return hook.service.find({
            query: {
                tourneyId: tourneyId,
                userId: userId
            }
        }).then(reg => {
            // User already registered
            if (reg.data.length != 0) {
              // Also tried to return a promise with same result.
              // return Promise.reject(new Error('Already registered.'))
              throw new Error('Already registered');
            }
        }).catch(err => {})
    }
}
</code>```

Here is my "before hook" object

```<code>exports.before = {
  create: [
    api.checkRegistered()
  ]
};
</code>```

答: The problem is the .catch(err => {}). It will return a promise that just resolves successfully with undefined which will then continue the hook chain as if no error happened. Removing it should fix your issue.

Body:
In my registration service I've created a 'before' hook to check if the user is already registered to a tournament. If the user is found to be registered, I have it throwing an error.

Per feathersjs documentation:

If a promise fails, the error will be propagated immediately and will
  exit out of the promise chain.

The problem I'm having is the error is being "triggered" and showing the user has already registered, but the registration still takes place. Meaning, the hook is never "exited".

Here is my function

exports.checkRegistered = () => {
    return (hook) => {
        let tourneyId = hook.data.tourneyId
        let userId = hook.data.userId

        return hook.service.find({
            query: {
                tourneyId: tourneyId,
                userId: userId
            }
        }).then(reg => {
            // User already registered
            if (reg.data.length != 0) {
              // Also tried to return a promise with same result.
              // return Promise.reject(new Error('Already registered.'))
              throw new Error('Already registered');
            }
        }).catch(err => {})
    }
}

Here is my "before hook" object

exports.before = {
  create: [
    api.checkRegistered()
  ]
};


问:
Destroy a tk.Frame from a class that inherits from tk.Frame
I am trying to develop a program based on a calendar. In my calendar, every day of the month is a button and I can store information in it. Here is my code:

```<code>import numpy as np
import calendar
import tkinter as tk
import datetime

kalender =  tk.Tk()
kalender.title("Overtime Tracker")
kalender.resizable(0, 0)

year = int(str(datetime.datetime.now())[0:4])
month = int(str(datetime.datetime.now())[6:7])

monthmatrix = calendar.monthcalendar(year,month)

class GUI(tk.Frame):
    def __init__(self, kalender, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.createwidgets()

    def createwidgets(self):
        <all the widgets I need for my GUI>

class Application (GUI):
    def __init__(self, *args, **kwargs):
        self.year = year
        self.month = month
        self.monthmatrix = monthmatrix
        GUI.__init__(self, *args, **kwargs)

        self.previousmonth = tk.Button(self, font=("Helvetica", 15), text= "<", command=lambda: self.PrevMonth())
        self.previousmonth.grid(row=0, column=0, sticky="NWNESWSE")
        self.nextmonth = tk.Button(self, font=("Helvetica", 15), text= ">", command=lambda: self.NextMonth())
        self.nextmonth.grid(row=0, column=7, sticky="NWNESWSE")

    def PrevMonth(self):
        self.month = self.month-1
        self.monthmatrix = calendar.monthcalendar(self.year,self.month)
        GUI.destroy(self)
        GUI.__init__(self, kalender)

    def NextMonth(self):
        self.year = year
        self.month = self.month+1
        self.monthmatrix = calendar.monthcalendar(self.year,self.month)
        GUI.destroy(self)
        GUI.__init__(self, kalender)

app = Application(kalender).grid()
kalender.mainloop()
</code>```

The application itself is another class that inherits from GUI and features all the other functions to which the buttons of the GUI are connected, etc.

The thing is that the two buttons "self.previousmonth" and "self.nextmonth", which are located in the application class and not in the GUI, are supoosed to be there for browsing the months. Thus, my idea was to shift the month value +1 or -1 (depending on the button), remove the tk.Frame, and open the GUI again with the new month.

Internally, everything works fine, the arrays and everything the program works with switch properly to the corresponding to the month before/after, but the calendar of the corresponding month doesn't appear. Instead, the frame is removed along with all the widgets (I guess it is what happens. What can be seen is that the window in which the program was empties completely), but the next month doesnt appear. The window just stays empty. Besides that, the console does not yield any error.

First, I am not sure I am destroying the tk.Frame properly, although this is what visually seems to happen. In order to be sure I have tried to structure the GUI like:

```<code>kalender = tk.Tk()

class GUI():
    def __init__(self, kalender):
        self.kalender = kalender
        self.frame = tk.Frame(self.kalender)
</code>```

But then, obviously, the class Application does not have the tk attributes that it needs.

On the other side, it could be that, after properly destroying the tk.Frame, I am somehow doing a mistake in calling the GUI again.

Can someone spot the problem?

Edit after Brian's comment

I put here a simplified version of the problem:

```<code>import calendar
import tkinter as tk
import datetime

kalender =  tk.Tk()

year = int(str(datetime.datetime.now())[0:4]) # takes the year from datetime
month = int(str(datetime.datetime.now())[6:7]) # takes the month from datetime

class GUI(tk.Frame):
    def __init__(self, kalender, *args, **kwargs):
        self.kalender = kalender
        tk.Frame.__init__(self, *args, **kwargs)
        self.createwidgets()

    def createwidgets(self):
        self.kalendertitle = tk.Label(self, text=str(calendar.month_name[self.month])+" "+str(year)).grid(row=0, column=1)

class Application (GUI):
    def __init__(self, *args, **kwargs):
        self.year = year
        self.month = month
        GUI.__init__(self, *args, **kwargs)

        self.nextmonth = tk.Button(self, text= ">", command=lambda: self.NextMonth())
        self.nextmonth.grid(row=0, column=7)

    def NextMonth(self):
        self.year = year
        self.month = self.month+1
        GUI.destroy(self)
        GUI.__init__(self, kalender)

app = Application(kalender).grid()
kalender.mainloop()
</code>```

The year and the month are take read from datetime. Class GUI initializes and calls the function "createwidgets", which in this case displays just the current month and year. The application comes as another class that inherits from GUI. It also incorporates a button to switch to the next month. This is done via the function "NextMonth". The idea of the function is to increase the month index, destroy the GUI and retrieve it again with the month index one unit larger, i.e. the display should show "July 2017".

As mentioned before, either the destruction of the frame doesn't work or the retrieval of the GUI is not properly passed. The window in which the GUI was empties completely (which makes me think the "destroy" function works properly). The console does not give any error.

答:
I have solved the problem.

The problem was, mainly, that I was creating the widgets as follows:

```<code>self.randomWidget = tk.Widget(self, ....)
</code>```

This means that the destruction of the frame and its new retrieval was working. But since the widgets were not IN the frame, nothing happened visually.

I eventually solved the problem by doing something like:

```<code>import calendar
import tkinter as tk
import datetime

year = int(str(datetime.datetime.now())[0:4]) # takes the year from datetime
month = int(str(datetime.datetime.now())[6:7]) # takes the month from datetime

class GUI():
    def __init__(self, master, *args, **kwargs):
        self.frame = tk.Frame(master)
        self.frame.pack()
        self.createwidgets()

    def createwidgets(self):
        self.kalendertitle = tk.Label(self.frame, text=str(calendar.month_name[self.month])+" "+str(self.year))
        self.kalendertitle.grid(row=0, column=1)

        self.nextmonth = tk.Button(self.frame, text= ">", command=lambda: self.NextMonth())
        self.nextmonth.grid(row=0, column=7)

class Application (GUI):
    def __init__(self, master, *args, **kwargs):
        self.year = year
        self.month = month
        GUI.__init__(self, master, *args, **kwargs)

    def NextMonth(self):
        self.month = self.month+1
        self.frame.destroy()
        GUI.__init__(self, root)

root =  tk.Tk()
app = Application(root)
root.mainloop()
</code>```

As you see, I needed as well to pass "master", or root, which was previously not there (and I believe it is per default "None"). It is yet not clear to me how much part of the original problem this missing "master" was.

The widgets inserted in the "self.frame" makes the whole thing work properly. And another bad idea of the code before was putting the browsing buttons in the Application and not in the GUI. Because, of course, after the first frame refreshing the buttons were gone.

The whole thing I did by making the GUI class NOT to inherit from tk.Frame. I have researched a little bit on that and didn´t find major arguments for one or the other options besides esthetics and code readability (which is also important).

Body:
I am trying to develop a program based on a calendar. In my calendar, every day of the month is a button and I can store information in it. Here is my code:

import numpy as np
import calendar
import tkinter as tk
import datetime

kalender =  tk.Tk()
kalender.title("Overtime Tracker")
kalender.resizable(0, 0)

year = int(str(datetime.datetime.now())[0:4])
month = int(str(datetime.datetime.now())[6:7])

monthmatrix = calendar.monthcalendar(year,month)

class GUI(tk.Frame):
    def __init__(self, kalender, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.createwidgets()

    def createwidgets(self):
        <all the widgets I need for my GUI>

class Application (GUI):
    def __init__(self, *args, **kwargs):
        self.year = year
        self.month = month
        self.monthmatrix = monthmatrix
        GUI.__init__(self, *args, **kwargs)

        self.previousmonth = tk.Button(self, font=("Helvetica", 15), text= "<", command=lambda: self.PrevMonth())
        self.previousmonth.grid(row=0, column=0, sticky="NWNESWSE")
        self.nextmonth = tk.Button(self, font=("Helvetica", 15), text= ">", command=lambda: self.NextMonth())
        self.nextmonth.grid(row=0, column=7, sticky="NWNESWSE")

    def PrevMonth(self):
        self.month = self.month-1
        self.monthmatrix = calendar.monthcalendar(self.year,self.month)
        GUI.destroy(self)
        GUI.__init__(self, kalender)

    def NextMonth(self):
        self.year = year
        self.month = self.month+1
        self.monthmatrix = calendar.monthcalendar(self.year,self.month)
        GUI.destroy(self)
        GUI.__init__(self, kalender)

app = Application(kalender).grid()
kalender.mainloop()

The application itself is another class that inherits from GUI and features all the other functions to which the buttons of the GUI are connected, etc.

The thing is that the two buttons "self.previousmonth" and "self.nextmonth", which are located in the application class and not in the GUI, are supoosed to be there for browsing the months. Thus, my idea was to shift the month value +1 or -1 (depending on the button), remove the tk.Frame, and open the GUI again with the new month.

Internally, everything works fine, the arrays and everything the program works with switch properly to the corresponding to the month before/after, but the calendar of the corresponding month doesn't appear. Instead, the frame is removed along with all the widgets (I guess it is what happens. What can be seen is that the window in which the program was empties completely), but the next month doesnt appear. The window just stays empty. Besides that, the console does not yield any error.

First, I am not sure I am destroying the tk.Frame properly, although this is what visually seems to happen. In order to be sure I have tried to structure the GUI like:

kalender = tk.Tk()

class GUI():
    def __init__(self, kalender):
        self.kalender = kalender
        self.frame = tk.Frame(self.kalender)

But then, obviously, the class Application does not have the tk attributes that it needs.

On the other side, it could be that, after properly destroying the tk.Frame, I am somehow doing a mistake in calling the GUI again.

Can someone spot the problem?

Edit after Brian's comment

I put here a simplified version of the problem:

import calendar
import tkinter as tk
import datetime

kalender =  tk.Tk()

year = int(str(datetime.datetime.now())[0:4]) # takes the year from datetime
month = int(str(datetime.datetime.now())[6:7]) # takes the month from datetime

class GUI(tk.Frame):
    def __init__(self, kalender, *args, **kwargs):
        self.kalender = kalender
        tk.Frame.__init__(self, *args, **kwargs)
        self.createwidgets()

    def createwidgets(self):
        self.kalendertitle = tk.Label(self, text=str(calendar.month_name[self.month])+" "+str(year)).grid(row=0, column=1)

class Application (GUI):
    def __init__(self, *args, **kwargs):
        self.year = year
        self.month = month
        GUI.__init__(self, *args, **kwargs)

        self.nextmonth = tk.Button(self, text= ">", command=lambda: self.NextMonth())
        self.nextmonth.grid(row=0, column=7)

    def NextMonth(self):
        self.year = year
        self.month = self.month+1
        GUI.destroy(self)
        GUI.__init__(self, kalender)

app = Application(kalender).grid()
kalender.mainloop()

The year and the month are take read from datetime. Class GUI initializes and calls the function "createwidgets", which in this case displays just the current month and year. The application comes as another class that inherits from GUI. It also incorporates a button to switch to the next month. This is done via the function "NextMonth". The idea of the function is to increase the month index, destroy the GUI and retrieve it again with the month index one unit larger, i.e. the display should show "July 2017".

As mentioned before, either the destruction of the frame doesn't work or the retrieval of the GUI is not properly passed. The window in which the GUI was empties completely (which makes me think the "destroy" function works properly). The console does not give any error.

Body:
I have solved the problem.

The problem was, mainly, that I was creating the widgets as follows:

self.randomWidget = tk.Widget(self, ....)

This means that the destruction of the frame and its new retrieval was working. But since the widgets were not IN the frame, nothing happened visually.

I eventually solved the problem by doing something like:

import calendar
import tkinter as tk
import datetime

year = int(str(datetime.datetime.now())[0:4]) # takes the year from datetime
month = int(str(datetime.datetime.now())[6:7]) # takes the month from datetime

class GUI():
    def __init__(self, master, *args, **kwargs):
        self.frame = tk.Frame(master)
        self.frame.pack()
        self.createwidgets()

    def createwidgets(self):
        self.kalendertitle = tk.Label(self.frame, text=str(calendar.month_name[self.month])+" "+str(self.year))
        self.kalendertitle.grid(row=0, column=1)

        self.nextmonth = tk.Button(self.frame, text= ">", command=lambda: self.NextMonth())
        self.nextmonth.grid(row=0, column=7)

class Application (GUI):
    def __init__(self, master, *args, **kwargs):
        self.year = year
        self.month = month
        GUI.__init__(self, master, *args, **kwargs)

    def NextMonth(self):
        self.month = self.month+1
        self.frame.destroy()
        GUI.__init__(self, root)

root =  tk.Tk()
app = Application(root)
root.mainloop()

As you see, I needed as well to pass "master", or root, which was previously not there (and I believe it is per default "None"). It is yet not clear to me how much part of the original problem this missing "master" was.

The widgets inserted in the "self.frame" makes the whole thing work properly. And another bad idea of the code before was putting the browsing buttons in the Application and not in the GUI. Because, of course, after the first frame refreshing the buttons were gone.

The whole thing I did by making the GUI class NOT to inherit from tk.Frame. I have researched a little bit on that and didn´t find major arguments for one or the other options besides esthetics and code readability (which is also important).


问:
ng-content and textarea compatibility issue
I have a custom my-textarea component with the following template:

```<code><textarea>
  <ng-content></ng-content>
</textarea>
</code>```

When I test the component and try to inject some text in it (as we do with a normal textarea html element):

```<code><my-textarea>some text</my-textarea>
</code>```

I get an empty component without the expected injected string, some text.

Any idea why could this be happening? I tried to do the same thing with a button and it works. (<button><ng-content></ng-content></button>).

Is there a compatibility issue between ng-content and textarea?

Thanks

答:
You can use the @Input() annotation in your component.ts

For example:

```<code>@Input() someText: string;
</code>```

And now you can "inject" the text you want in the component like:

```<code><my-textarea [someText]="'sometext'"></my-textarea>
</code>```

Or when you have the text in a variable in another component

```<code><my-textarea [someText]="someVariableWithText"></my-textarea>
</code>```

edit

app.component.ts

```<code>@Component({
  selector: 'my-app',
  templateUrl: 'app/app.component.html',
})
export class AppComponent {
   text:string = "textToINsertINAnothercomponent";
}
</code>```

app.component.html

```<code><my-textarea [textInCustom]="text"></my-textarea>
</code>```

my-texarea.component.ts:

```<code>@Component({
    selector: "my-textarea",
    templateUrl: "app/my-textarea/my-textarea.component.html"
})
export class ReviewList {
    @Input() textInCustom: string;
}
</code>```

my-textarea.component.html:

```<code><text-area>{{textInCustom}}</text-area>
</code>```

Body:
I have a custom my-textarea component with the following template:

<textarea>
  <ng-content></ng-content>
</textarea>

When I test the component and try to inject some text in it (as we do with a normal textarea html element):

<my-textarea>some text</my-textarea>

I get an empty component without the expected injected string, some text.

Any idea why could this be happening? I tried to do the same thing with a button and it works. (<button><ng-content></ng-content></button>).

Is there a compatibility issue between ng-content and textarea?

Thanks

Body:
You can use the @Input() annotation in your component.ts

For example:

@Input() someText: string;

And now you can "inject" the text you want in the component like:

<my-textarea [someText]="'sometext'"></my-textarea>

Or when you have the text in a variable in another component

<my-textarea [someText]="someVariableWithText"></my-textarea>

edit

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.component.html',
})
export class AppComponent {
   text:string = "textToINsertINAnothercomponent";
}

app.component.html

<my-textarea [textInCustom]="text"></my-textarea>

my-texarea.component.ts:

@Component({
    selector: "my-textarea",
    templateUrl: "app/my-textarea/my-textarea.component.html"
})
export class ReviewList {
    @Input() textInCustom: string;
}

my-textarea.component.html:

<text-area>{{textInCustom}}</text-area>


问:
Query which inserts then Updates SQL
Is it possible to have an insert statement and once that is complete straight away run an update statement?

So Here are my statements:

Insert

```<code>truncate table table1;
INSERT INTO table2 (name,value, ATY)
SELECT table1.name,table1.Value,table1.ATY
FROM table1;
</code>```

As soon as that is complete, I need the following update to run:

Update

```<code>update table2
   SET value=TRIM( BOTH '+' FROM REPLACE( '+' || value || '+', '++', '+000+' ) )
</code>```

Is this possible?

答:
Why not do both in one statement?

```<code>truncate table table2;

INSERT INTO table2 (name, value, ATY)
    SELECT t1.name,
           TRIM( BOTH '+' FROM REPLACE( '+' || t1.value || '+', '++', '+000+' ) ),
           t1.ATY
    FROM table1 t1;
</code>```

Note:  I assume that you intend to truncate table2, not table1.  If you truncate table1, then the insert will not do anything because the table will be empty.

Title: Query which inserts then Updates SQL

Body:
Is it possible to have an insert statement and once that is complete straight away run an update statement?

So Here are my statements:

Insert

truncate table table1;
INSERT INTO table2 (name,value, ATY)
SELECT table1.name,table1.Value,table1.ATY
FROM table1;

As soon as that is complete, I need the following update to run:

Update

update table2
   SET value=TRIM( BOTH '+' FROM REPLACE( '+' || value || '+', '++', '+000+' ) )

Is this possible?

Body:
Why not do both in one statement?

truncate table table2;

INSERT INTO table2 (name, value, ATY)
    SELECT t1.name,
           TRIM( BOTH '+' FROM REPLACE( '+' || t1.value || '+', '++', '+000+' ) ),
           t1.ATY
    FROM table1 t1;

Note:  I assume that you intend to truncate table2, not table1.  If you truncate table1, then the insert will not do anything because the table will be empty.


问:
IIS FTP 7.5: Custom Auth Provider not working Error 530
I have recently install Server 2008 R2 on a new server and want to use the FTP capabilities that are now shipped with IIS 7.5.

Since my users are not windows users, I was using IISAuthManager but this prodiver does not offers home directory on a user basis.

I found this sample http://learn.iis.net/page.aspx/669/how-to-use-managed-code-c-to-create-an-ftp-authentication-provider-using-an-xml-database/ to get going with a simple xml based user config. But i can't make it work. It's always gving me

```<code>Response:   530-User cannot log in.
Response:    Win32 error:   The system cannot find the file specified.
Response:    Error details: An error occured during the authentication process.
</code>```

I used procmon to get if the xml config file was read with no luck. I don't even think my assembly is being used.

Anybody ever had the same issue ? Basicly, any tips would be apreciated.

答:
The IIS FTP custom providers are a nightmare to debug. In this case sounds like a config error, check that you followed the set up instructions (or manually checking applicationHost.config).  Or post your code (inc config) if you still need help.

Barry

Body:
I have recently install Server 2008 R2 on a new server and want to use the FTP capabilities that are now shipped with IIS 7.5.

Since my users are not windows users, I was using IISAuthManager but this prodiver does not offers home directory on a user basis.

I found this sample http://learn.iis.net/page.aspx/669/how-to-use-managed-code-c-to-create-an-ftp-authentication-provider-using-an-xml-database/ to get going with a simple xml based user config. But i can't make it work. It's always gving me

Response:   530-User cannot log in.
Response:    Win32 error:   The system cannot find the file specified.
Response:    Error details: An error occured during the authentication process.

I used procmon to get if the xml config file was read with no luck. I don't even think my assembly is being used.

Anybody ever had the same issue ? Basicly, any tips would be apreciated.


问:
How to convert Excel file to text file in php?
I want to convert an excel file to a text file. I have tried this code but it doesn't work:

```<code>    $destination = 'products.xls';
    $section = file_get_contents($destination);
    $File = "file.txt";
    $File = str_replace(';','#',$File);
    $Handle = fopen($File, 'w');
    $Data = $section;
    fwrite($Handle, $Data);
    print "Data Written"; die;
</code>```

When I open the text file it shows me special characters and when I convert csv to text it shows me the right result. Please provide any helpful links.

答: You cannot read the Excel file that way. Excel file is binary file that follows the XLS format while file_get_contents is for pure text file. You need a library (like https://github.com/PHPOffice/PHPExcel) to read the content then write to text.</p>

Body:
I want to convert an excel file to a text file. I have tried this code but it doesn't work:

    $destination = 'products.xls';
    $section = file_get_contents($destination);
    $File = "file.txt";
    $File = str_replace(';','#',$File);
    $Handle = fopen($File, 'w');
    $Data = $section;
    fwrite($Handle, $Data);
    print "Data Written"; die;

When I open the text file it shows me special characters and when I convert csv to text it shows me the right result. Please provide any helpful links.


问:
Using jenkins wanted to copy some script file to /bin/
Using jenkins I have created one job and I have script files in git and i wanted to copy in /bin/. I have tried using sudo. I have tried to copy from jenkins workspace to bin but unable to copy

```<code>echo 'password'|sudo cp -S /var/lib/jenkins/workspace/WiCheck_project/sample.sh /bin/
</code>```

but it it giving following error.

```<code>[sudo] password for jenkins: Sorry, try again.
[sudo] password for jenkins:
sudo: 1 incorrect password attempt
Build step 'Execute shell' marked build as failure
</code>```

Please help me how to use sudo to copy files.

答:
it's asking for your password to run sudo. you could use expect to inject it if you hate yourself.

or, if you have access to the slave, you could read about sudoers and update the sudoers file or add a file to sudoers.d to allow the jenkins user to run sudo cp passwordless.

or you could chown the /bin directory to the jenkins user so you don't have to use sudo.

or, the best option, just use ./WiCHeck_project/sample.sh to run your script instead of sample.sh, so it won't have to be in /bin.

Body:
Using jenkins I have created one job and I have script files in git and i wanted to copy in /bin/. I have tried using sudo. I have tried to copy from jenkins workspace to bin but unable to copy

echo 'password'|sudo cp -S /var/lib/jenkins/workspace/WiCheck_project/sample.sh /bin/

but it it giving following error.

[sudo] password for jenkins: Sorry, try again.
[sudo] password for jenkins:
sudo: 1 incorrect password attempt
Build step 'Execute shell' marked build as failure

Please help me how to use sudo to copy files.


问:
Does JSONModel have $top and $skip like OData?
In my app I'm reading data from a JSON file and creating a model from it like this

```<code>var myModel = new sap.ui.model.JSONMOdel("pathToJson");
</code>```

I have 300 values but I only want to read 50, is there a way to do that. I know I can use $top and $skip to select a specific set of values using OData. The API provides the function myModel.loadData() which contains a parameter oParameters but I don't know what I can pass in. Does anyone know if this possible?

答:
The JSON model is a client-side model. This means that all the data is loaded at once with a single request. In the standard implementation, it has no methods for reading paged JSON contents (with top / skip or any other name you might give them).

You have said that you have a JSON file that you are loading. So such a paging does not even make sense from a technical point of view. This is because you cannot (easily) load a portion of a static file with client-only code (especially JSON, which is not valid if you are reading a fragment of it).

If you actually just want to store a segment of the file in the model, you can simply read the whole file with jQuery.ajax and then slice the array.

If you actually have a RESTful web service, then the paging mechanism should be part of this service (e..g it should have some path or query parameters for specifying the paging parameters). This service should return a valid JSON document for each call. On the client side, you can use such a service with the help of some functions (e.g. in the controller):

```<code>onInit: function () {
    this.setModel(new JSONModel([])); // initially an emty array
},

//call this method when you want to read a page
onReadDataPage: function (iTop, iSkip) {
    // use jQuery.ajax or jQuery.get to read a "page" of data; e.g.
    jQuery.ajax({
        url: "your service path",
        data: {
            top: iTop,
            skip: iSkip || 0
        },
        success: this.onDataReceived.bind(this)
    });
},

onDataReceived: function (aData) {
    var oModel = this.getModel();
    oModel.setData(oModel.getData().concat(aData);
}
</code>```

If you want to use this in combination with a List with the growing feature, then you will need to create a new type of model - which is not trivial.

Body:
In my app I'm reading data from a JSON file and creating a model from it like this

var myModel = new sap.ui.model.JSONMOdel("pathToJson");

I have 300 values but I only want to read 50, is there a way to do that. I know I can use $top and $skip to select a specific set of values using OData. The API provides the function myModel.loadData() which contains a parameter oParameters but I don't know what I can pass in. Does anyone know if this possible?

Body:
The JSON model is a client-side model. This means that all the data is loaded at once with a single request. In the standard implementation, it has no methods for reading paged JSON contents (with top / skip or any other name you might give them).

You have said that you have a JSON file that you are loading. So such a paging does not even make sense from a technical point of view. This is because you cannot (easily) load a portion of a static file with client-only code (especially JSON, which is not valid if you are reading a fragment of it).

If you actually just want to store a segment of the file in the model, you can simply read the whole file with jQuery.ajax and then slice the array.

If you actually have a RESTful web service, then the paging mechanism should be part of this service (e..g it should have some path or query parameters for specifying the paging parameters). This service should return a valid JSON document for each call. On the client side, you can use such a service with the help of some functions (e.g. in the controller):

onInit: function () {
    this.setModel(new JSONModel([])); // initially an emty array
},

//call this method when you want to read a page
onReadDataPage: function (iTop, iSkip) {
    // use jQuery.ajax or jQuery.get to read a "page" of data; e.g.
    jQuery.ajax({
        url: "your service path",
        data: {
            top: iTop,
            skip: iSkip || 0
        },
        success: this.onDataReceived.bind(this)
    });
},

onDataReceived: function (aData) {
    var oModel = this.getModel();
    oModel.setData(oModel.getData().concat(aData);
}

If you want to use this in combination with a List with the growing feature, then you will need to create a new type of model - which is not trivial.


问:
Can't init bootstrap-datepicker
I can't get bootstrap-datepicker (https://github.com/uxsolutions/bootstrap-datepicker) to initialize the proper way or call any methods or events on it.

I'm using Laravel 5.4.7 / Vue 2.3.3 / jQuery 3.1.0

My html look like this:

<input type="text" data-provide="datepicker" />

But when I try to initialize the datepicker using the "official" way it doesn't set any of the properties (no errors either):

```<code>    $('.datepicker').datepicker({
        todayHighlight: true
    });
</code>```

It doesn't matter where I place the code (beginning, end, vue created-method, vue mounted-method, $nextTick).

However setting the values like this works:

$.fn.datepicker.defaults.todayHighlight = true;

Unfortunately since non of the other methods or events seem to work either just using the $.fn.datepicker.defaults is not enough.

Does anyone have a clue on what might be wrong?

答:
Change your input field code to this:

<input type="text" data-provider="datepicker" class="datepicker" />

The issue was of CSS selector i.e. you were searching for an element with datepicker class but their was no such element.

So just add the class attribute to it.

Title: Can't init bootstrap-datepicker

Body:
I can't get bootstrap-datepicker (https://github.com/uxsolutions/bootstrap-datepicker) to initialize the proper way or call any methods or events on it.

I'm using Laravel 5.4.7 / Vue 2.3.3 / jQuery 3.1.0

My html look like this:

<input type="text" data-provide="datepicker" />

But when I try to initialize the datepicker using the "official" way it doesn't set any of the properties (no errors either):

    $('.datepicker').datepicker({
        todayHighlight: true
    });

It doesn't matter where I place the code (beginning, end, vue created-method, vue mounted-method, $nextTick).

However setting the values like this works:

$.fn.datepicker.defaults.todayHighlight = true;

Unfortunately since non of the other methods or events seem to work either just using the $.fn.datepicker.defaults is not enough.

Does anyone have a clue on what might be wrong?


问:
Why does my Windows system service which saves running application names to a text file not create the file?
I have to write a system service which allows me save to a text file the names of running applications every minute.

```<code>static void Main(string[] args)
{
    Timer t = new Timer(TimeSpan.FromMinutes((double)60).TotalMilliseconds); //Every minute
    t.AutoReset = true;
    t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
    t.Start();
}

private static void your_method(object sender, ElapsedEventArgs e)
{
    Process[] processlist = Process.GetProcesses();
    foreach (Process theprocess in processlist)
    {
        string s = " Process:  " + theprocess.ProcessName;
        File.AppendAllText("RunningAplications.txt", s);
    }
}
</code>```

Is this the correct way? (I don't think so because that doesn't create a file.) How can I create a system service from this?

答:
```<code>static void Main(string[] args)
{
    Timer t = new Timer(TimerCallback, null, 0, 2000);
}

private static void TimerCallback(Object o)
{
    //I have tried this and it wrote my name.
    System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\report.txt", true);
    SaveFile.WriteLine("saumil");
    SaveFile.Flush();
    SaveFile.Close();

    ////Process[] processlist = Process.GetProcesses();
    ////foreach (Process theprocess in processlist)
    ////{
    ////    string s = " Process:  " + theprocess.ProcessName;
    ////    SaveFile.WriteLine("saumil");
    ////    SaveFile.Flush();
    ////    SaveFile.Close();
    ////    //SaveFile.WriteLine(s);
    ////}
}
</code>```

Body:
I have to write a system service which allows me save to a text file the names of running applications every minute.

static void Main(string[] args)
{
    Timer t = new Timer(TimeSpan.FromMinutes((double)60).TotalMilliseconds); //Every minute
    t.AutoReset = true;
    t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
    t.Start();
}

private static void your_method(object sender, ElapsedEventArgs e)
{
    Process[] processlist = Process.GetProcesses();
    foreach (Process theprocess in processlist)
    {
        string s = " Process:  " + theprocess.ProcessName;
        File.AppendAllText("RunningAplications.txt", s);
    }
}

Is this the correct way? (I don't think so because that doesn't create a file.) How can I create a system service from this?


问:
SQL Server refactor a column from varchar(50) to uniqueidentifier and surrounding issues
I have a table message in a database that has almost a million rows. It has a externalId column which is varchar(50). The values stored in it are guid but I want to update this column to be uniqueidentifier.

So I think I am going to add a new column which is uniqueidentifier. Copy all the values across to this column and then drop the original column. Then I will rename this column to externalId.

My problem is there are hundreds of stored procs etc and I need to make sure that I don't break anything. I also have to grep through all the code and make changes so that we expect a Guid and not a string. (I am using C#)

Does anyone have some tips or recommendations?

Would I be better do just duplicate this column and not touch the existing column and make any code that does a select on it use the guid column instead of the string (currently it sometimes times-out!). I would also have to update any code then that inserts into this table to also insert a guid...)

I love legacy crap .......................

答:
I wouldn't do this at all. Yes it would have been better if it had been a Uniqueidentifier to begin with but unless you have a specific problem that can't be overcome without changing it what's the value that you're users are getting.

If you do decide to do it. You can query the sys.procedures. Its better than using syscomments or INFORMATION_SCHEMA.ROUTINES


问:
Starter Theme Prestashop 1.7 is blank
I've installed PS 1.7 on local ubuntu env with php 5.6 and I wanted to check out starter theme, but it isn't working.

Could it be some permissions problem or what? Default theme works no sweat.

Here's topic on prestashop forums for more detailed information: https://www.prestashop.com/forums/topic/573994-cant-get-starter-theme-to-work/

答: Make sure Cache folder inside theme/assets exists. If not create it and and 7777 permissions on it. You should see the theme now</p>

Title: Starter Theme Prestashop 1.7 is blank


问:
Why does the "+" operator consider the number as string when added
Why does the + operator consider the number as string when added

Ex :

```<code>'3' + 4 + 5;  // "345"
 3 + 4 + '5'; // "75"
</code>```

答:
Regarding the "why", you've already gotten answers, the way to fix it, in case you don't know or if it can help somebody else:</p>

```<code>var x = parseInt('3') + 4 + 5;
</code>```

Body:
Why does the + operator consider the number as string when added

Ex :

'3' + 4 + 5;  // "345"
 3 + 4 + '5'; // "75"

Body:
Regarding the "why", you've already gotten answers, the way to fix it, in case you don't know or if it can help somebody else:

var x = parseInt('3') + 4 + 5;


问:
Changing an Image in UIImageView at runtime
I've declared a UIImageView property programmatically in a UIScrollView

```<code>var scrollView: UIScrollView!
var imageView = UIImageView(image: UIImage(named: "OPA_farm.png"))
let drawView = UIView()
</code>```

The reason I initialised it with "OPA_farm.png" is it's the only way I can get an oversized image that scrolls properly

In viewDidLoad they get added as subviews

```<code>    // other stuff here
    myView.addSubview(scrollView)
    myView.addSubview(drawView)
    scrollView.addSubview(imageView)
</code>```

but changing a UISegmentedControl sender is supposed to change the image ( among other things )

```<code>@IBAction func chooseFarm(_ sender: UISegmentedControl) {
        switch farmSegment.selectedSegmentIndex {
        case 1:
            imageView = UIImageView(image: UIImage(named: "OF_farm.png"))
            // other things
            break
        default:
            imageView = UIImageView(image: UIImage(named: "OPA_farm.png"))
            // other things
      }
}
</code>```

The other things change but the .png image doesn't. Things I've searched on before ( and during ) posting and tried have been

imageView.reloadInputViews()

imageView.setNeedsDisplay()

These things didn't seem to apply

DispatchQueue.main.async related

parsing for a tableView related

Following the QuickHelp Inspector to the Apple docs gives sparse info and in Objective C. I know I can use the conversion function to current Swift syntax in XCode 8 and it agrees with other posts along the way in that I seem to be doing everything correctly. I'm Beat. Can someone de-mystify?

答:
Once you have an image view, you don't need to create new ones (every time you hit your button).

You could declare these at the top of your class (with the imageView)

```<code>let ofImage = UIImage(named: "OF_farm.png")
let opaImage = UIImage(named: "OPA_farm.png")
</code>```

and in your case statement just reassign either image to your imageView

```<code>    switch farmSegment.selectedSegmentIndex {
    case 1:
        imageView.image = ofImage
        // other things
        break
    default:
        imageView.image = opaImage
        // other things
  }
</code>```

In viewDidLoad, after adding the imageView to the scrollView you can add auto layout constraints if they are needed. Just be sure to set this first:

```<code> imageView.translatesAutoresizingMaskIntoConstraints = false
</code>```

One last note: Don't forget to view your work in the simulator along the way using the 7+ and the SE settings (and others) to ensure that you have something that will work for everyone.

Body:
I've declared a UIImageView property programmatically in a UIScrollView

var scrollView: UIScrollView!
var imageView = UIImageView(image: UIImage(named: "OPA_farm.png"))
let drawView = UIView()

The reason I initialised it with "OPA_farm.png" is it's the only way I can get an oversized image that scrolls properly

In viewDidLoad they get added as subviews

    // other stuff here
    myView.addSubview(scrollView)
    myView.addSubview(drawView)
    scrollView.addSubview(imageView)

but changing a UISegmentedControl sender is supposed to change the image ( among other things )

@IBAction func chooseFarm(_ sender: UISegmentedControl) {
        switch farmSegment.selectedSegmentIndex {
        case 1:
            imageView = UIImageView(image: UIImage(named: "OF_farm.png"))
            // other things
            break
        default:
            imageView = UIImageView(image: UIImage(named: "OPA_farm.png"))
            // other things
      }
}

The other things change but the .png image doesn't. Things I've searched on before ( and during ) posting and tried have been

imageView.reloadInputViews()

imageView.setNeedsDisplay()

These things didn't seem to apply

DispatchQueue.main.async related

parsing for a tableView related

Following the QuickHelp Inspector to the Apple docs gives sparse info and in Objective C. I know I can use the conversion function to current Swift syntax in XCode 8 and it agrees with other posts along the way in that I seem to be doing everything correctly. I'm Beat. Can someone de-mystify?

Body:
Once you have an image view, you don't need to create new ones (every time you hit your button).

You could declare these at the top of your class (with the imageView)

let ofImage = UIImage(named: "OF_farm.png")
let opaImage = UIImage(named: "OPA_farm.png")

and in your case statement just reassign either image to your imageView

    switch farmSegment.selectedSegmentIndex {
    case 1:
        imageView.image = ofImage
        // other things
        break
    default:
        imageView.image = opaImage
        // other things
  }

In viewDidLoad, after adding the imageView to the scrollView you can add auto layout constraints if they are needed. Just be sure to set this first:

 imageView.translatesAutoresizingMaskIntoConstraints = false

One last note: Don't forget to view your work in the simulator along the way using the 7+ and the SE settings (and others) to ensure that you have something that will work for everyone.