问:
How do I find all the modules used by a Perl script?
I'm getting ready to try to deploy some code to multiple machines. As far as I know, using a Makefile.pm to track dependencies is the best way to ensure they are installed everywhere.  The problem I have is I'm not sure our Makefile.pm has been updated as this application has passed through a few different developers.

Is there any way to automatically parse through either my source or a few full runs of my program to determine exactly what versions of what modules my application is depending on?  On top of that, is there any way to filter it based on CPAN packages? (So that I only depend on Moose instead of every single module that comes with Moose.)

A third related question is, if you depend on a version of a module that is not the latest, what is the best way to have someone else install it? Should I start including entire localized Perl installations with my application?

答: You could look at %INC, see http://www.perlmonks.org/?node_id=681911 which also mentions Devel::Modlist</p>


来源: stackexchange

问:
How to get popup window using ng2-bootstrap?

Company Management

 <md-card>
   <button class="md-fab md-mini add-task" md-mini-fab title="Add" (click)="addCompany.show()">
    <md-icon style="color:white;">add</md-icon>
   </button>

         Name
         Email
         country
         Action

           {{company.user_name}}
           {{company.email}}
           {{company.country}}

               <button class="btn" md-raised-button>Guide</button>
               <button class="btn" md-raised-button>Pin</button>
               <button class="iconBtn first">

               </button>
               <button class="iconBtn second">

               </button>

 </md-card>

       <button md-raised-button class="md-raised cancel color-white" (click)="addCompany.hide()">Cancel
       </button>
       <button md-raised-button class="md-raised save color-white">Save</button>

```

this my html code where i used ngmodal for popup window but im not getting any kind of popup model.
i have imported import { ModalModule } from 'ng2-bootstrap'; in the app.module.ts file
can u please help me out to fix this problem

答:
Your code is 100% fine, there is no issue on template side.

But The Possible issues might be:

1) Imported just ModalModule rather than ModalModule.forRoot()

```<code>import { ModalModule } from 'ngx-bootstrap';

@NgModule({
  imports:      [ ... , ModalModule.forRoot() ],
  ...
})
</code>```

2) Forgot to add css

Here is the working example of static modal, you can compare your code wiht this :

https://stackblitz.com/edit/angular-ngx-bootstrap

ContentLicense: CC BY-SA 3.0

Body:
Company Management

 <md-card>
   <button class="md-fab md-mini add-task" md-mini-fab title="Add" (click)="addCompany.show()">
    <md-icon style="color:white;">add</md-icon>
   </button>

         Name
         Email
         country
         Action

           {{company.user_name}}
           {{company.email}}
           {{company.country}}

               <button class="btn" md-raised-button>Guide</button>
               <button class="btn" md-raised-button>Pin</button>
               <button class="iconBtn first">

               </button>
               <button class="iconBtn second">

               </button>

 </md-card>

       <button md-raised-button class="md-raised cancel color-white" (click)="addCompany.hide()">Cancel
       </button>
       <button md-raised-button class="md-raised save color-white">Save</button>

this my html code where i used ngmodal for popup window but im not getting any kind of popup model.
i have imported import { ModalModule } from 'ng2-bootstrap'; in the app.module.ts file
can u please help me out to fix this problem

Body:
Your code is 100% fine, there is no issue on template side.

But The Possible issues might be:

1) Imported just ModalModule rather than ModalModule.forRoot()

import { ModalModule } from 'ngx-bootstrap';

@NgModule({
  imports:      [ ... , ModalModule.forRoot() ],
  ...
})

2) Forgot to add css

Here is the working example of static modal, you can compare your code wiht this :

https://stackblitz.com/edit/angular-ngx-bootstrap


问:
cannot find pthread.c in linux folder
I have downloaded kernel and the kernel resides in folder called Linux-2.6.32.28 in which I can find /Kernel/Kthread.c
I found Kthread.c but I cannot find pthread.c in Linux-2.6.32.28
I found Kthread.c in Linux-3.13/Kernel and Linux-4.7.2/Kernel

locate pthread.c finds file pthread.c in Computer/usr folder that comes when I install Ubuntu but pthread.c is not available in downloaded folders Linux-2.6.32.28, Linux-3.13, Linux-4.7.2

MORE: There are two sets of function calls. 1. System Calls 2. Library Calls.

For a computer to do any task it has to use hardware resources. So, how library calls differ from system calls?

System calls always use kernel which means hardware.
Library calls means no usage of kernel or hardware?

I know that library calls sometimes may resolve to system call.

What I want to know is that, if every set of function calls uses hardware then to what degree system calls will use hardware resources when compared with library calls and vice-versa.

Whether a function call is System or Library, at least hardware resource like RAM has to be utilized. Right?

答:
Read first pthreads(7). It explains you that pthreads are implemented in the C standard library as nptl(7).

The C standard library is the cornerstone of Linux systems, and you might have several variants of it; however, most Linux distributions have only one libc, often the GNU glibc, which contains the NPTL. You might use another C standard library (such as musl-libc or dietlibc). With care, you can have several C standard libraries co-existing on your system.

The C standard library (and every user-space program) is using system calls to interact with the kernel. They are listed in syscalls(2). BTW most C standard library implementations on Linux are free software, so you can study (or even improve) their source code if you want to. You often use a system call thru the small wrapper C function (e.g. write(2)) for it in your C standard library, and even more often thru some higher-level function (e.g. fprintf(3)) provided by your C standard library.

Pthreads are implemented (in the NPTL layer of glibc) using low-level stuff like clone(2) and futex(7) and a bit of assembler code. But you generally won't use these directly unless you are implementing a thread library (like NPTL).

Most programs are using the libc and linking with it (and also with crt0) as a shared library, which is /lib/x86_64-linux-gnu/libc.so.6 on my Debian/Sid/x86-64. However, you might (but you usually don't) invoke system calls directly thru some assembler code (e.g. using a SYSCALL or SYSENTER machine instruction). See also this.

The question was edited to also ask

What I want to know is that, if every set of function calls uses hardware then to what degree system calls will use hardware resources

Please read a lot more about operating systems. So read carefully Operating Systems: Three Easy pieces (a freely downloadable textbook) and read about Instruction Set Architecture and Computer Architecture. Study several of them, e.g. x86-64 and RISC-V (or ARM, PowerPC, etc...). Read about CPU modes and virtual memory.

You'll find out that the OS manages physical resources (including RAM and cores of processors). Each process has its own virtual address space. So from a user-space point of view, a process don't use directly hardware (e.g. it runs in virtual address space, not in RAM), it runs in some virtual machine (provided by the OS kernel) defined by the system calls and the ISA (the unpriviledged machine instructions).

Whether a function call is System or Library, at least hardware resource like RAM has to be utilized. Right?

Wrong, from a user-space point of view. All hardware resources are (by definition) managed by the operating system (which provides abstractions thru system calls). An ordinary application executable program uses the abstractions and software resources (files, processes, file descriptors, sockets, memory mappings, virtual address space, etc etc...) provided by the OS.

(so several books are required to really answer your questions; I gave some references, please follow them and read a lot more; we can't explain everything here)

Title: cannot find pthread.c in linux folder


问:
How to convert epoch seconds to normal time in perl?
I have a string of epoch seconds "1510652305" which when i convert to normal time on unix command line using

```<code>`date -d @1510652305`
</code>```

i get
Tue Nov 14 15:08:25 IST 2017

But when i tried it in perl using something like this

```<code>use POSIX qw(strftime);
use Time::Local;
use Time::localtime;

$kickoff_time=1510652305;
$kickoff_time=ctime($kickoff_time);
</code>```

i get

Thu Jan  1 05:30:00 1970

How can i achieve the result i am getting in linux in perl?

Thanks!!

答:
Don't overthink it!

```<code>my $kickoff_time = localtime 1510652305;
say $kickoff_time; # Tue Nov 14 15:08:25 2017
</code>```

If you absolutely, positively need the timezone in there:

```<code>use POSIX qw{strftime};

my $kickoff_time = strftime '%a %b %e %H:%M:%S %Z %Y', localtime 1510652305;
say $kickoff_time; # Tue Nov 14 15:08:25 IST 2017
</code>```

Note that this is locale-dependent.

Body:
I have a string of epoch seconds "1510652305" which when i convert to normal time on unix command line using

`date -d @1510652305`

i get
Tue Nov 14 15:08:25 IST 2017

But when i tried it in perl using something like this

use POSIX qw(strftime);
use Time::Local;
use Time::localtime;

$kickoff_time=1510652305;
$kickoff_time=ctime($kickoff_time);

i get

Thu Jan  1 05:30:00 1970

How can i achieve the result i am getting in linux in perl?

Thanks!!

Body:
Don't overthink it!

my $kickoff_time = localtime 1510652305;
say $kickoff_time; # Tue Nov 14 15:08:25 2017

If you absolutely, positively need the timezone in there:

use POSIX qw{strftime};

my $kickoff_time = strftime '%a %b %e %H:%M:%S %Z %Y', localtime 1510652305;
say $kickoff_time; # Tue Nov 14 15:08:25 IST 2017

Note that this is locale-dependent.


问:
Node: Wait for python script to run
I have the following code. Where i upload the file first and then i read the file and console the output like console.log(obj). But the response comes first and the python scripts runs behind the scene. How can i make code to wait for the python script to run then proceed?

```<code>router.post(`${basePath}/file`, (req, res) => {

    //Upload file first

    PythonShell.run('calculations.py', { scriptPath: '/Path/to/python/script' }, function (err) {
        console.log(err);
        let obj = fs.readFileSync('Path/to/file', 'utf8');
        console.log(obj);
    });

    return res.status(200).send({
        message : 'Success',
    });
});
</code>```

I cannot get console.log(obj); output because it runs after the response. How can i make it wait for the python script to run and get console.log(obj) output on console.

答:
To return the result after some async operation, you should call res.send inside the done-callback.

```<code>router.post(`${basePath}/file`, (req, res) => {

    //Upload file first

    PythonShell.run('calculations.py', { scriptPath: '/Path/to/python/script' }, function (err) {
        console.log('The script work has been finished.'); // (*)
        if(err) {
          res.status(500).send({
            error: err,
          });
          console.log(err);
          return;
        }
        let obj = fs.readFileSync('Path/to/file', 'utf8');
        console.log(obj); // (**)
        res.status(200).send({
            message : 'Success',
        });
    });
});
</code>```

Then if you will not see the log (*) in the console, then it would mean that the script does not work or works improperly. The callback is not being called. First of all, you need to be sure that the script (PythonShell.run) works and the callback is being called. The POST handler will wait until you call res.send (with no matter of delay value), so that callback is the main point.

Also readFileSync could fail. In case of readFileSync failure you should see an exception. If it's ok then you'll see the next log (**) and the response will be sent.

I see PythonShell in your code. I have no experience with it, but after some reading I think that the problem could be in how you are using it. It seems the python-shell npm package, so following it's documentation you may try to to instantiate a python shell for your script and then to use listeners:

```<code>let pyshell = new PythonShell('calculations.py');

router.post(`${basePath}/file`, (req, res) => {
  pyshell.send(settings); // path, args etc
  pyshell.end(function (err) {
    console.log('The script work has been finished.');
    if(err) { res.status(200).send({ error: err }); }
    else { res.status(200).send({ message : 'Success' }); }
  });
});
</code>```

This approach could be more appropriate because the pyton shell is kept open between different POST requests. This depends on your needs. But I guess it does not solve the problem of script running. If you are sure that the script itself is fine, then you need just to run it properly in the Node environment. There are some points:

path to script

arguments

other settings

Try to remove all arguments (create some new test script), cleanup settings object (keep only path) and execute it from Node. Handle its result in Node. You should be able to run the simplest script by correct path! Research how to setup correct scriptPath. Then add an argument to your script and run it with an argument. Hanlde the result again. There are not so many options, but each of them could be the cause of improper call.

Title: Node: Wait for python script to run

Body:
I have the following code. Where i upload the file first and then i read the file and console the output like console.log(obj). But the response comes first and the python scripts runs behind the scene. How can i make code to wait for the python script to run then proceed?

router.post(`${basePath}/file`, (req, res) => {

    //Upload file first

    PythonShell.run('calculations.py', { scriptPath: '/Path/to/python/script' }, function (err) {
        console.log(err);
        let obj = fs.readFileSync('Path/to/file', 'utf8');
        console.log(obj);
    });

    return res.status(200).send({
        message : 'Success',
    });
});

I cannot get console.log(obj); output because it runs after the response. How can i make it wait for the python script to run and get console.log(obj) output on console.

Body:
To return the result after some async operation, you should call res.send inside the done-callback.

router.post(`${basePath}/file`, (req, res) => {

    //Upload file first

    PythonShell.run('calculations.py', { scriptPath: '/Path/to/python/script' }, function (err) {
        console.log('The script work has been finished.'); // (*)
        if(err) {
          res.status(500).send({
            error: err,
          });
          console.log(err);
          return;
        }
        let obj = fs.readFileSync('Path/to/file', 'utf8');
        console.log(obj); // (**)
        res.status(200).send({
            message : 'Success',
        });
    });
});

Then if you will not see the log (*) in the console, then it would mean that the script does not work or works improperly. The callback is not being called. First of all, you need to be sure that the script (PythonShell.run) works and the callback is being called. The POST handler will wait until you call res.send (with no matter of delay value), so that callback is the main point.

Also readFileSync could fail. In case of readFileSync failure you should see an exception. If it's ok then you'll see the next log (**) and the response will be sent.

I see PythonShell in your code. I have no experience with it, but after some reading I think that the problem could be in how you are using it. It seems the python-shell npm package, so following it's documentation you may try to to instantiate a python shell for your script and then to use listeners:

let pyshell = new PythonShell('calculations.py');

router.post(`${basePath}/file`, (req, res) => {
  pyshell.send(settings); // path, args etc
  pyshell.end(function (err) {
    console.log('The script work has been finished.');
    if(err) { res.status(200).send({ error: err }); }
    else { res.status(200).send({ message : 'Success' }); }
  });
});

This approach could be more appropriate because the pyton shell is kept open between different POST requests. This depends on your needs. But I guess it does not solve the problem of script running. If you are sure that the script itself is fine, then you need just to run it properly in the Node environment. There are some points:

path to script

arguments

other settings

Try to remove all arguments (create some new test script), cleanup settings object (keep only path) and execute it from Node. Handle its result in Node. You should be able to run the simplest script by correct path! Research how to setup correct scriptPath. Then add an argument to your script and run it with an argument. Hanlde the result again. There are not so many options, but each of them could be the cause of improper call.


问:
JavaScript stops working after I load another page
I am new to JavaScript and trying to see why my on event listeners are not working. I have found similar posts on stackoverflow however the solutions are not working for me.

```<code>var search = function( event ) {
    alert("bobo")
   $.get("http://localhost:3000/search", {"search" : $("#Search-Bar").val()}, function(data, status){
        if(status == "success")
           $(".centering.text-center").html(data)
    })
}

var attachListeners = function(){
    $("#Search").on("click", search)
    $("#SearchIcon").click( () => search() )
    $("#Search-Bar").keypress( event => (event.KeyCode == 13 || event.which == 13) ? search() : undefined )
}

$(document).ready( function(){
    attachListeners()
})
</code>```

My website is not a single page application. I have attached the listeners to my navigation search bar where I load a different view through the nav links and my server(ruby back end) uploads a new html page.

On the first load I have noticed that document ready gets called and everything else works. The on and click. After I use my navigation and load a different html page my events disappear. In my html views my searchbar, searchicon, and a search text have consistent id's through out. I have tried using window.load() and putting an onload attribute for my body  but neither worked(perhaps I didn't use them properly). I also noticed that when I render the next html views my docment.ready does not get called. However, if I forcefully refresh the page with an F5 the listeners are active again for that one html page. What am I missing here that I don't understand?

答:
It looks like you might be using Turbolinks, from the Readme for the project:

When you follow a link, Turbolinks automatically fetches the page, swaps in its , and merges its , all without incurring the cost of a full page load.

Since this library makes it so the page ever only loads once, normal javascript window.onload, DOMContentLoaded, and jQuery ready events don't function after the initial page load and you have to use

```<code>document.addEventListener("turbolinks:load", function() {
</code>```

instead of those. If you're new to turbo links, I suggest reading through that README to see what it's all about.

I've never understood why the Rails team would put something like this in rails and enable it by default, and in every single project I've made since they made that change the first thing I do is uninstall it, and when I forgot to do so, I spend several hours later in the project wondering why my javascript is broken.

Body:
I am new to JavaScript and trying to see why my on event listeners are not working. I have found similar posts on stackoverflow however the solutions are not working for me.

var search = function( event ) {
    alert("bobo")
   $.get("http://localhost:3000/search", {"search" : $("#Search-Bar").val()}, function(data, status){
        if(status == "success")
           $(".centering.text-center").html(data)
    })
}

var attachListeners = function(){
    $("#Search").on("click", search)
    $("#SearchIcon").click( () => search() )
    $("#Search-Bar").keypress( event => (event.KeyCode == 13 || event.which == 13) ? search() : undefined )
}

$(document).ready( function(){
    attachListeners()
})

My website is not a single page application. I have attached the listeners to my navigation search bar where I load a different view through the nav links and my server(ruby back end) uploads a new html page.

On the first load I have noticed that document ready gets called and everything else works. The on and click. After I use my navigation and load a different html page my events disappear. In my html views my searchbar, searchicon, and a search text have consistent id's through out. I have tried using window.load() and putting an onload attribute for my body  but neither worked(perhaps I didn't use them properly). I also noticed that when I render the next html views my docment.ready does not get called. However, if I forcefully refresh the page with an F5 the listeners are active again for that one html page. What am I missing here that I don't understand?

Body:
It looks like you might be using Turbolinks, from the Readme for the project:

When you follow a link, Turbolinks automatically fetches the page, swaps in its <body>, and merges its <head>, all without incurring the cost of a full page load.

Since this library makes it so the page ever only loads once, normal javascript window.onload, DOMContentLoaded, and jQuery ready events don't function after the initial page load and you have to use

document.addEventListener("turbolinks:load", function() {

instead of those. If you're new to turbo links, I suggest reading through that README to see what it's all about.

I've never understood why the Rails team would put something like this in rails and enable it by default, and in every single project I've made since they made that change the first thing I do is uninstall it, and when I forgot to do so, I spend several hours later in the project wondering why my javascript is broken.


问:
Checking for presence of .NET remoting server - is my approach correct?
It's not possible to set a connection timeout on a .NET remoting call.  Documentation occasionally refers to TcpChannel properties that allegedly do this, but discussions and the most recent docs I've found indicate that this is not possible.  One may set a timeout on the remoting call itself, but not on the initial connection attempt.  You're stuck with the default 45-second timeout.

For various reasons I can't use WCF.

This causes a problem when the remoting server goes away.  If I attempt to make a remoting call, I'm stuck for those 45 seconds.  That's not good.  I want to check for the presence of the remoting server.  Pinging it with a PingTimeout is the simplest approach, but I want to check specifically for the remoting server, as opposed to just the machine being up.

After some experimentation, I've come up with this approach:

Asynchronously begin a TCP socket
connection to the remoting port.

Wait for the connection to complete,
or a timeout to expire (using a
ManualResetEvent).

If the connection
async callback succeeded, return
success.  Otherwise, return failure.

This works, but I'm unsure about my use of my WaitHandle and socket.  I'd also like to assure thread-safety WRT concurrent checks, which I think I've done. My code's below.  Do you see any problems with my approach?

```<code>private static bool IsChannelOpen(string ip, int port, int timeout)
{
    IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ip), port);
    Socket client = new Socket(endpoint.AddressFamily,
              SocketType.Stream, ProtocolType.Tcp);
    SocketTestData data = new SocketTestData()
              { Socket = client, ConnectDone = new ManualResetEvent(false) };
    IAsyncResult ar = client.BeginConnect
              (endpoint, new AsyncCallback(TestConnectionCallback), data);

    // wait for connection success as signaled from callback, or timeout
    data.ConnectDone.WaitOne(timeout);
    client.Close();
    return data.Connected;
}

private static void TestConnectionCallback(IAsyncResult ar)
{
    SocketTestData data = (SocketTestData)ar.AsyncState;
    data.Connected = data.Socket.Connected;
    if (data.Socket.Connected)
    {
        data.Socket.EndConnect(ar);
    }
    data.ConnectDone.Set(); // signal completion
}

public class SocketTestData
{
    public Socket Socket { get; set; }
    public ManualResetEvent ConnectDone { get; set; }
    public bool Connected { get; set; }
}
</code>```

答:
I couldn't believe .NET remoting doesn't support timeout. I found a tip in Stack Overflow question Remoting set timeout. There, somebody claims the property is "connectionTimeout", but based on my testing, it is the "timeout" property. It is working, just not to exact amount of the time you specified. Roughly, if you specify 2000 millisec, it times out at 4000 millisec. Here is my code:

```<code>   IDictionary dic = new Hashtable();
   dic["timeout"] = 2000;
   ChannelServices.RegisterChannel(new HttpChannel(dic, null, null), false);
   ...
</code>```

Body:
It's not possible to set a connection timeout on a .NET remoting call.  Documentation occasionally refers to TcpChannel properties that allegedly do this, but discussions and the most recent docs I've found indicate that this is not possible.  One may set a timeout on the remoting call itself, but not on the initial connection attempt.  You're stuck with the default 45-second timeout.

For various reasons I can't use WCF.

This causes a problem when the remoting server goes away.  If I attempt to make a remoting call, I'm stuck for those 45 seconds.  That's not good.  I want to check for the presence of the remoting server.  Pinging it with a PingTimeout is the simplest approach, but I want to check specifically for the remoting server, as opposed to just the machine being up.

After some experimentation, I've come up with this approach:

Asynchronously begin a TCP socket
connection to the remoting port.

Wait for the connection to complete,
or a timeout to expire (using a
ManualResetEvent).

If the connection
async callback succeeded, return
success.  Otherwise, return failure.

This works, but I'm unsure about my use of my WaitHandle and socket.  I'd also like to assure thread-safety WRT concurrent checks, which I think I've done. My code's below.  Do you see any problems with my approach?

private static bool IsChannelOpen(string ip, int port, int timeout)
{
    IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ip), port);
    Socket client = new Socket(endpoint.AddressFamily,
              SocketType.Stream, ProtocolType.Tcp);
    SocketTestData data = new SocketTestData()
              { Socket = client, ConnectDone = new ManualResetEvent(false) };
    IAsyncResult ar = client.BeginConnect
              (endpoint, new AsyncCallback(TestConnectionCallback), data);

    // wait for connection success as signaled from callback, or timeout
    data.ConnectDone.WaitOne(timeout);
    client.Close();
    return data.Connected;
}

private static void TestConnectionCallback(IAsyncResult ar)
{
    SocketTestData data = (SocketTestData)ar.AsyncState;
    data.Connected = data.Socket.Connected;
    if (data.Socket.Connected)
    {
        data.Socket.EndConnect(ar);
    }
    data.ConnectDone.Set(); // signal completion
}

public class SocketTestData
{
    public Socket Socket { get; set; }
    public ManualResetEvent ConnectDone { get; set; }
    public bool Connected { get; set; }
}

Body:
I couldn't believe .NET remoting doesn't support timeout. I found a tip in Stack Overflow question Remoting set timeout. There, somebody claims the property is "connectionTimeout", but based on my testing, it is the "timeout" property. It is working, just not to exact amount of the time you specified. Roughly, if you specify 2000 millisec, it times out at 4000 millisec. Here is my code:

   IDictionary dic = new Hashtable();
   dic["timeout"] = 2000;
   ChannelServices.RegisterChannel(new HttpChannel(dic, null, null), false);
   ...


问:
keypress on datagridview only character "abcde" and convert to uppercase
How to limit keypress on datagridview only character abcde and convert to uppercase at vb.net?

```<code>Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
        If DataGridView1.CurrentCell.ColumnIndex = 3 Then
                AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBoxabcde_keyPress
        End If
End Sub

Private Sub TextBoxabcde_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
        If Not Char.IsControl(e.KeyChar) And Not Char.IsLetter(e.KeyChar) And e.KeyChar <> "." Then
                e.Handled = True
        End If
End Sub
</code>```

答:
Try this</p>

```<code>Dim txtEC As DataGridViewTextBoxEditingControl = Nothing
Private Sub DGV_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DGV.EditingControlShowing

If TypeOf e.Control Is DataGridViewTextBoxEditingControl Then
    If DGV.CurrentCell.ColumnIndex =1  Then
        txtEC = DirectCast(e.Control, DataGridViewTextBoxEditingControl)
        txtEC.CharacterCasing = CharacterCasing.Upper
    End If
End If
End Sub

Private Sub DGV_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DGV.CellEndEdit

If txtEC IsNot Nothing Then
      txtEC.CharacterCasing = CharacterCasing.Normal
      txtEC = Nothing
End If
End Sub
</code>```

Body:
How to limit keypress on datagridview only character abcde and convert to uppercase at vb.net?

Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
        If DataGridView1.CurrentCell.ColumnIndex = 3 Then
                AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBoxabcde_keyPress
        End If
End Sub

Private Sub TextBoxabcde_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
        If Not Char.IsControl(e.KeyChar) And Not Char.IsLetter(e.KeyChar) And e.KeyChar <> "." Then
                e.Handled = True
        End If
End Sub

Body:
Try this

Dim txtEC As DataGridViewTextBoxEditingControl = Nothing
Private Sub DGV_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DGV.EditingControlShowing

If TypeOf e.Control Is DataGridViewTextBoxEditingControl Then
    If DGV.CurrentCell.ColumnIndex =1  Then
        txtEC = DirectCast(e.Control, DataGridViewTextBoxEditingControl)
        txtEC.CharacterCasing = CharacterCasing.Upper
    End If
End If
End Sub

Private Sub DGV_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DGV.CellEndEdit

If txtEC IsNot Nothing Then
      txtEC.CharacterCasing = CharacterCasing.Normal
      txtEC = Nothing
End If
End Sub


问:
c++ deep copy constructor
this is my code:

```<code>#include<iostream>
#include<cstring>
using namespace std;

class String
{
private:
    char *s;
    int size;
public:
    String(const char *str = NULL); // constructor
    String& operator=(String &c){
        size = strlen(c.s);
        s = new char[size+1];
        strcpy(s, c.s);
    }
    ~String() { delete [] s; }// destructor
    void print() { cout << s << endl; }
    void change(const char *); // Function to change
};

String::String(const char *str)
{
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

void String::change(const char *str)
{
    delete [] s;
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

int main()
{
    String str1("learnc++");
    String str2 = str1;

    str1.print(); // what is printed ?
    str2.print();

    str2.change("learnjava");

    str1.print(); // what is printed now ?
    str2.print();
    return 0;
}
</code>```

it can be compiled, and the result is:

```<code>learnc++
learnc++
learnjava
learnjava
</code>```

in addition to that,there is:

```<code>*** Error in `./code': double free or corruption (fasttop): 0x0000000000f7f010 ***
</code>```

BTY, if I delete "delete [] s;" in String::change,the result just becomes:

```<code>learnc++
learnc++
learnc++
learnjava
</code>```

and no error appers, and why ?
the code is from geek foe feeks, I have changes some strings, and the code can be run in its IDE, but in my ubuntu 14.04, it cannot.

答:
Your class is not following the Rule of Three because it is missing a proper copy constructor.

String str2 = str1; is just syntax sugar for String str2(str1);, so it uses the copy constructor, not your operator= (which has a memory leak, BTW).

Since you did not provide a copy constructor, the compiler provided one for you, but it does not make a deep copy of the char* data. It just copies the pointer itself, which causes the behaviors you are seeing.

A proper implementation would look more like this:

```<code>#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

class String
{
private:
    char *s;
    int size;
public:
    String(const char *str = NULL);
    String(const String &src);
    ~String();
    String& operator=(const String &rhs);
    void print() const;
};

String::String(const char *str)
{
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

String::String(const String &src)
{
    size = src.size;
    s = new char[size+1];
    strcpy(s, src.s);
}

String::~String()
{
    delete [] s;
}

void String::print() const
{
    cout << s << endl;
}

String& String::operator=(const String &rhs)
{
    if (&rhs != this)
    {
        String tmp(rhs);
        swap(s, tmp.s);
        swap(size, tmp.size);
    }
    return *this;
}

int main()
{
    String str1("learnc++");
    String str2 = str1;

    str1.print();
    str2.print();

    //str2.change("learnjava");
    str2 = "learnjava";

    str1.print();
    str2.print();

    return 0;
}
</code>```

If you are using C++11 or later, you can use this implementation instead, which follows the Rule of Five by adding move semantics:

```<code>#include <iostream>
#include <cstring>
#include <utility>
using namespace std;

class String
{
private:
    char *s;
    int size;
public:
    String(const char *str = nullptr);
    String(const String &src);
    String(String &&src);
    ~String();
    String& operator=(String rhs);
    void print() const;
};

String::String(const char *str)
{
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

String::String(const String &src)
{
    size = src.size;
    s = new char[size+1];
    strcpy(s, src.s);
}

String::String(String &&src)
{
    size = src.size;
    s = src.s;
    src.s = nullptr;
    src.size = 0;
}

String::~String()
{
    delete [] s;
}

void String::print() const
{
    cout << s << endl;
}

String& String::operator=(String rhs)
{
    swap(s, rhs.s);
    swap(size, rhs.size);
    return *this;
}
</code>```

Title: c++ deep copy constructor

Body:
this is my code:

#include<iostream>
#include<cstring>
using namespace std;

class String
{
private:
    char *s;
    int size;
public:
    String(const char *str = NULL); // constructor
    String& operator=(String &c){
        size = strlen(c.s);
        s = new char[size+1];
        strcpy(s, c.s);
    }
    ~String() { delete [] s; }// destructor
    void print() { cout << s << endl; }
    void change(const char *); // Function to change
};

String::String(const char *str)
{
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

void String::change(const char *str)
{
    delete [] s;
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

int main()
{
    String str1("learnc++");
    String str2 = str1;

    str1.print(); // what is printed ?
    str2.print();

    str2.change("learnjava");

    str1.print(); // what is printed now ?
    str2.print();
    return 0;
}

it can be compiled, and the result is:

learnc++
learnc++
learnjava
learnjava

in addition to that,there is:

*** Error in `./code': double free or corruption (fasttop): 0x0000000000f7f010 ***

BTY, if I delete "delete [] s;" in String::change,the result just becomes:

learnc++
learnc++
learnc++
learnjava

and no error appers, and why ?
the code is from geek foe feeks, I have changes some strings, and the code can be run in its IDE, but in my ubuntu 14.04, it cannot.

Body:
Your class is not following the Rule of Three because it is missing a proper copy constructor.

String str2 = str1; is just syntax sugar for String str2(str1);, so it uses the copy constructor, not your operator= (which has a memory leak, BTW).

Since you did not provide a copy constructor, the compiler provided one for you, but it does not make a deep copy of the char* data. It just copies the pointer itself, which causes the behaviors you are seeing.

A proper implementation would look more like this:

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

class String
{
private:
    char *s;
    int size;
public:
    String(const char *str = NULL);
    String(const String &src);
    ~String();
    String& operator=(const String &rhs);
    void print() const;
};

String::String(const char *str)
{
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

String::String(const String &src)
{
    size = src.size;
    s = new char[size+1];
    strcpy(s, src.s);
}

String::~String()
{
    delete [] s;
}

void String::print() const
{
    cout << s << endl;
}

String& String::operator=(const String &rhs)
{
    if (&rhs != this)
    {
        String tmp(rhs);
        swap(s, tmp.s);
        swap(size, tmp.size);
    }
    return *this;
}

int main()
{
    String str1("learnc++");
    String str2 = str1;

    str1.print();
    str2.print();

    //str2.change("learnjava");
    str2 = "learnjava";

    str1.print();
    str2.print();

    return 0;
}

If you are using C++11 or later, you can use this implementation instead, which follows the Rule of Five by adding move semantics:

#include <iostream>
#include <cstring>
#include <utility>
using namespace std;

class String
{
private:
    char *s;
    int size;
public:
    String(const char *str = nullptr);
    String(const String &src);
    String(String &&src);
    ~String();
    String& operator=(String rhs);
    void print() const;
};

String::String(const char *str)
{
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

String::String(const String &src)
{
    size = src.size;
    s = new char[size+1];
    strcpy(s, src.s);
}

String::String(String &&src)
{
    size = src.size;
    s = src.s;
    src.s = nullptr;
    src.size = 0;
}

String::~String()
{
    delete [] s;
}

void String::print() const
{
    cout << s << endl;
}

String& String::operator=(String rhs)
{
    swap(s, rhs.s);
    swap(size, rhs.size);
    return *this;
}


问:
Silverlight Combobox ItemTemplate Stuck Displaying First Selected Item
I've got a Combobox whose ItemTemplate is bound to a DataTemplate containing one of my custom label controls. All the custom control does is localize the content assigned to it.

The Combobox (when closed) will display the text of the first item selected. However when the selected item is changed, the display of the closed Combobox will not update. I know the actual selected item is updated because it's bound to a property that changes correctly. The only problem is the display text.

So for instance if I select the item with text 'Item 1' the closed Combobox will display 'Item 1'. Then if I select 'Item 2' the closed Combobox will still display 'Item 1'.

Here's how it's set up ('Name' is a property of the items being bound in the ItemsSource):

```<code><Grid.Resources>
    <DataTemplate x:Key="MyTemplate">
        <MyCustomLabel Content="{Binding Name}" />
    <DataTemplate>
</Grid.Resources>

<Combobox ItemsSource="{Binding MyItems}" ItemTemplate="{StaticResource MyTemplate}" />
</code>```

Below is the code for my label control:

```<code>public class MyLabel : Label
{
    /// <summary>
    ///   When reassigning content in the OnContentChanged method, this will prevent an infinite loop.
    /// </summary>
    private bool _overrideOnContentChanged;

    protected override void OnContentChanged(object oldContent, object newContent)
    {
        // if this method has been called recursively (since this method assigns content)
        // break out to avoid an infinite loop
        if (_overrideOnContentChanged)
        {
            _overrideOnContentChanged = false;
            return;
        }

        base.OnContentChanged(oldContent, newContent);

        var newContentString = newContent as string;
        if (newContentString != null)
        {
            // convert the string using localization
            newContentString = LocalizationConverter.Convert(newContentString);

            // override the content changed method
            // will prevent infinite looping when this method causes itself to be called again
            _overrideOnContentChanged = true;
            Content = newContentString;
        }
    }
}
</code>```

Any advice would be greatly appreciated. Thanks!

答:
Perform a 2-way databinding on the SelectedItem property of the combo box.

The target property that you're binding the combo-box to - should raise a PropertyChanged event.

```<code><ComboBox ItemsSource={Binding Path=Source} SelectedItem={Binding Path=CurrentItem, Mode=TwoWay}/>

class ComboContext : INotifyPropertyChanged
{
public List<object> Source { get; set; } // attach your source here
public object CurrentItem { get { return mCurrentItem; } set { mCurrentItem = value; OnPropertyChanged("CurrentItem"); } } // bind to this property
private object mCurrentItem;

void OnPropertyChanged(string name)
{
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
</code>```

The code sample might not be "complete" - it's 1am and I'm kinda tired, but it should put you on the right track.

Edit2.

Just noticed your template, it's wrong, the whole idea is wrong.

```<code><ComboBox ItemsSource={Binding Path=Source} SelectedItem={Binding Path=CurrentItem, Mode=TwoWay}>
    <ComboBox.ItemTemplate>
        <DataTemplate>
        <Grid>
            <TextBlock Text={Binding}/>
        </Grid>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
</code>```

Notice that the texblock's text is a binding with no path, (and it's a default binding too.) the no-path binding means that this textblock will bind to whatever is directly "underneath".

ContentLicense: CC BY-SA 2.5

Body:
I've got a Combobox whose ItemTemplate is bound to a DataTemplate containing one of my custom label controls. All the custom control does is localize the content assigned to it.

The Combobox (when closed) will display the text of the first item selected. However when the selected item is changed, the display of the closed Combobox will not update. I know the actual selected item is updated because it's bound to a property that changes correctly. The only problem is the display text.

So for instance if I select the item with text 'Item 1' the closed Combobox will display 'Item 1'. Then if I select 'Item 2' the closed Combobox will still display 'Item 1'.

Here's how it's set up ('Name' is a property of the items being bound in the ItemsSource):

<Grid.Resources>
    <DataTemplate x:Key="MyTemplate">
        <MyCustomLabel Content="{Binding Name}" />
    <DataTemplate>
</Grid.Resources>

<Combobox ItemsSource="{Binding MyItems}" ItemTemplate="{StaticResource MyTemplate}" />

Below is the code for my label control:

public class MyLabel : Label
{
    ///
    ///   When reassigning content in the OnContentChanged method, this will prevent an infinite loop.
    ///
    private bool _overrideOnContentChanged;

    protected override void OnContentChanged(object oldContent, object newContent)
    {
        // if this method has been called recursively (since this method assigns content)
        // break out to avoid an infinite loop
        if (_overrideOnContentChanged)
        {
            _overrideOnContentChanged = false;
            return;
        }

        base.OnContentChanged(oldContent, newContent);

        var newContentString = newContent as string;
        if (newContentString != null)
        {
            // convert the string using localization
            newContentString = LocalizationConverter.Convert(newContentString);

            // override the content changed method
            // will prevent infinite looping when this method causes itself to be called again
            _overrideOnContentChanged = true;
            Content = newContentString;
        }
    }
}

Any advice would be greatly appreciated. Thanks!

Body:
Perform a 2-way databinding on the SelectedItem property of the combo box.

The target property that you're binding the combo-box to - should raise a PropertyChanged event.

<ComboBox ItemsSource={Binding Path=Source} SelectedItem={Binding Path=CurrentItem, Mode=TwoWay}/>

class ComboContext : INotifyPropertyChanged
{
public List<object> Source { get; set; } // attach your source here
public object CurrentItem { get { return mCurrentItem; } set { mCurrentItem = value; OnPropertyChanged("CurrentItem"); } } // bind to this property
private object mCurrentItem;

void OnPropertyChanged(string name)
{
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}

The code sample might not be "complete" - it's 1am and I'm kinda tired, but it should put you on the right track.

Edit2.

Just noticed your template, it's wrong, the whole idea is wrong.

<ComboBox ItemsSource={Binding Path=Source} SelectedItem={Binding Path=CurrentItem, Mode=TwoWay}>
    <ComboBox.ItemTemplate>
        <DataTemplate>
        <Grid>
            <TextBlock Text={Binding}/>
        </Grid>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Notice that the texblock's text is a binding with no path, (and it's a default binding too.) the no-path binding means that this textblock will bind to whatever is directly "underneath".


问:
Assign a value to a parameter in application properties before use
I have a property in my application.properties file in a SpringBoot project -

```<code>app.module.service.url=http://localhost:8090/{DOCID}
</code>```

I have injected it into my Java file as below -

```<code>@Value("${app.module.service.url}")
private String url;
</code>```

Now I need to replace DOCID with some value in my function(i.e-dynamic). How do I get to do this or am I completely missing it?
I am aware that we can do this in case of message properties in Spring. But here I have nothing to do with Locales.

Edit:

There is some value which I need to put in place of {DOCID} when using it within my Java implementation.

```<code>...
public class Sample{

@Value("${app.module.service.url}")
private String url;

public void sampleFunc(){

String str = "random Value" //some dynamic value goes in here
...
</code>```

Now I need to replace {DOCID} with str in url

答:
Two way binding is not possible in Spring Properties.It can only read run time and environmental variables.

Please refer following link for more information.

https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding

Body:
I have a property in my application.properties file in a SpringBoot project -

app.module.service.url=http://localhost:8090/{DOCID}

I have injected it into my Java file as below -

@Value("${app.module.service.url}")
private String url;

Now I need to replace DOCID with some value in my function(i.e-dynamic). How do I get to do this or am I completely missing it?
I am aware that we can do this in case of message properties in Spring. But here I have nothing to do with Locales.

Edit:

There is some value which I need to put in place of {DOCID} when using it within my Java implementation.

...
public class Sample{

@Value("${app.module.service.url}")
private String url;

public void sampleFunc(){

String str = "random Value" //some dynamic value goes in here
...

Now I need to replace {DOCID} with str in url


问:
How to print the return value of a function using printf()?

Update:

The original code looked a lot like this:

```<code>// printf(printf(););

#include <string>

int main()
{
   printf(printf("Hello, WORLD!"););
}
</code>```

However, in the original post, printf("Hello, WORLD!") was assigned to a variable, x.

Intended questions:

How do I call the return value of a function within a function?  As a beginner, learning to reference a string variable using %s, I wondered how to reference a the return value of a function (for example, if the return value were a string, would I still use %s).

What does "called to print" mean?  I think a simplistic explanation is: the string is put into memory and assigned an address, and the class definition tells the compiler to look up the location in memory based on the class's input-argument definition; so, the address in memory is called to print by the compiler.

Is the first argument of printf() also the return value of printf() such that x == "Hello, World!" is true in x = printf("Hello, World!")?

Original post:

I'm looking at http://www.cplusplus.com/reference/cstdio/printf/

it says: int printf ( const char * format, ... );, but it doesn't define ....  So, I don't know what ... is referencing.  I wrongly assumed that meant ( const char * format, const char * format, const char * format, ~.  But in fact, I can't decipher the meaning based on guessing and reading.

Using this program:

```<code>#include <stdio.h>
int main(int argc, char ** argv)
{
    str x = printf("Hello, World!\n");
    printf("x has %d characters.\n", x);
    //"x has %d characters.\n" appears first, x appears second.

    return 0;
}
</code>```

We see the result:

```<code>Hello, World!
x has 14 characters.
</code>```

When I expected:

```<code>x has 14 characters.  //because this appears first.
Hello, World!         //because this appear second.
</code>```

Because x comes after x has 14 characters..

Someone please explain why ./a.out is giving me the results in backwards order (using gcc and shell in Ubuntu); furthermore, eclipse is shown to give the results in this same backward order.

Perhaps another way to rephrase the question would be: where is "Hello, World!\n" being called to print?

答:
Consider this little program:

```<code>#include <stdio.h>

int foo(int bar)
{
  printf("Foo %d\n", bar);
  return 42;
}

int main() {
  int x = foo(12);           // we call the foo function which prints "Foo 12"
                             // the return value of foo is assigned to x"
  printf("Hello World.\n");  // we print "Hello World"
  printf("x = %d\n", x);     // we print "x = 42"
}
</code>```

The output is:

```<code>Foo 12
Hello World.
x = 42
</code>```

If you understand this little program, you should understand also the output of your program.

In your program:

```<code>#include <stdio.h>
int main(int argc, char ** argv)
{
    int x = printf("Hello, World!\n");   // you call printf which prints ("Hello World!")
                                         // and the return value of printf is assigned to x

    printf("x has %d characters.\n", x); // then we print "x has 14 characters"

    return 0;
}
</code>```

Hence the output is

```<code>Hello, World!
x has 14 characters.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Update:

The original code looked a lot like this:

// printf(printf(););

#include <string>

int main()
{
   printf(printf("Hello, WORLD!"););
}

However, in the original post, printf("Hello, WORLD!") was assigned to a variable, x.

Intended questions:

How do I call the return value of a function within a function?  As a beginner, learning to reference a string variable using %s, I wondered how to reference a the return value of a function (for example, if the return value were a string, would I still use %s).

What does "called to print" mean?  I think a simplistic explanation is: the string is put into memory and assigned an address, and the class definition tells the compiler to look up the location in memory based on the class's input-argument definition; so, the address in memory is called to print by the compiler.

Is the first argument of printf() also the return value of printf() such that x == "Hello, World!" is true in x = printf("Hello, World!")?

Original post:

I'm looking at http://www.cplusplus.com/reference/cstdio/printf/

it says: int printf ( const char * format, ... );, but it doesn't define ....  So, I don't know what ... is referencing.  I wrongly assumed that meant ( const char * format, const char * format, const char * format, ~.  But in fact, I can't decipher the meaning based on guessing and reading.

Using this program:

#include <stdio.h>
int main(int argc, char ** argv)
{
    str x = printf("Hello, World!\n");
    printf("x has %d characters.\n", x);
    //"x has %d characters.\n" appears first, x appears second.

    return 0;
}

We see the result:

Hello, World!
x has 14 characters.

When I expected:

x has 14 characters.  //because this appears first.
Hello, World!         //because this appear second.

Because x comes after x has 14 characters..

Someone please explain why ./a.out is giving me the results in backwards order (using gcc and shell in Ubuntu); furthermore, eclipse is shown to give the results in this same backward order.

Perhaps another way to rephrase the question would be: where is "Hello, World!\n" being called to print?

Body:
Consider this little program:

#include <stdio.h>

int foo(int bar)
{
  printf("Foo %d\n", bar);
  return 42;
}

int main() {
  int x = foo(12);           // we call the foo function which prints "Foo 12"
                             // the return value of foo is assigned to x"
  printf("Hello World.\n");  // we print "Hello World"
  printf("x = %d\n", x);     // we print "x = 42"
}

The output is:

Foo 12
Hello World.
x = 42

If you understand this little program, you should understand also the output of your program.

In your program:

#include <stdio.h>
int main(int argc, char ** argv)
{
    int x = printf("Hello, World!\n");   // you call printf which prints ("Hello World!")
                                         // and the return value of printf is assigned to x

    printf("x has %d characters.\n", x); // then we print "x has 14 characters"

    return 0;
}

Hence the output is

Hello, World!
x has 14 characters.


问:
C# Which Event should I use to display data in a textbox when I select an item in a listbox?
C# Which Event should I use to display data in a textbox when I select an item in a listbox?

I want to select an item in a list box (winforms) and then a textbox near by show some data related to that item but I don't know which event to use. I'll need to be able to click down the list and watch the textbox text update with each click.

Thanks

答:
Assuming you have a form with a TextBox and a ListBox.</p>

```<code>    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        textBox1.Text = listBox1.SelectedItem.ToString();
    }
}
</code>```

OwnerDisplayName: Steve

Body:
Assuming you have a form with a TextBox and a ListBox.

    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        textBox1.Text = listBox1.SelectedItem.ToString();
    }
}

OwnerDisplayName: Gerrie Schenck


问:
Appengine Datastore Advantages
I have used sql databases a fair bit and can see a lot of benefit in normalised databases that can be joined and searched and relationships built in them.

What are the advantages to the sort of 'object database' that google has in Appengine's datastore?

答: GAE's BigTable datastore is not object-oriented or even object-relational. It has more in common with a Hashmap than with a standard relational database like MySQL or Oracle. The main advantage is scalability and a tighter guarantee on the amount of time a query will take (sort of like CPU time). The scalability comes from the way records are distributed, if you setup your keys correctly then the data associated with those keys will be closer together physically (the data is distributed so there is no single point of failure).</p>

Title: Appengine Datastore Advantages


问:
Regular Expression for Validating Bitcoin Addresses
I'm trying to write a function that returns true or false if it's a valid bitcoin address.

I currently have a QR Code Scanner that returns a string like this:

bitcoin:18YCdhPsd5gdf6WD4ioMZZJKTNdajUJyTM

Here's my function:

```<code>func isValidBitcoinAddress() -> Bool {
    var fullAddress = self.components(separatedBy: ":")
    let r = fullAddress[1].startIndex..<fullAddress[1].endIndex
    let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
    let r2 = self.range(of: pattern, options: .regularExpression)
    if r2 == r {
        return true
    } else {
        return false
    }
}
</code>```

Unfortunately this is returning false every time.

I got the RegEx patter from this site: http://mokagio.github.io/tech-journal/2014/11/21/regex-bitcoin.html

Is the format perhaps different in Swift?

Thanks!

答:
You need to match the regex on only the part after the ::

```<code>extension String {
    func isValidBitcoinAddress() -> Bool {
        let addressComponents = self.components(separatedBy: ":")
        guard addressComponents.count == 2,
              addressComponents[0] == "bitcoin" else {
            return false
        }

        let address = addressComponents[1]

        let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
        let range = address.range(of: pattern, options: .regularExpression)
        return range == address.indices
    }
}
</code>```

Body:
I'm trying to write a function that returns true or false if it's a valid bitcoin address.

I currently have a QR Code Scanner that returns a string like this:

bitcoin:18YCdhPsd5gdf6WD4ioMZZJKTNdajUJyTM

Here's my function:

func isValidBitcoinAddress() -> Bool {
    var fullAddress = self.components(separatedBy: ":")
    let r = fullAddress[1].startIndex..<fullAddress[1].endIndex
    let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
    let r2 = self.range(of: pattern, options: .regularExpression)
    if r2 == r {
        return true
    } else {
        return false
    }
}

Unfortunately this is returning false every time.

I got the RegEx patter from this site: http://mokagio.github.io/tech-journal/2014/11/21/regex-bitcoin.html

Is the format perhaps different in Swift?

Thanks!

Body:
You need to match the regex on only the part after the ::

extension String {
    func isValidBitcoinAddress() -> Bool {
        let addressComponents = self.components(separatedBy: ":")
        guard addressComponents.count == 2,
              addressComponents[0] == "bitcoin" else {
            return false
        }

        let address = addressComponents[1]

        let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
        let range = address.range(of: pattern, options: .regularExpression)
        return range == address.indices
    }
}


答:
You are comparing self to the pattern instead of fullAddress[1].

Use the following:

```<code>func isValidBitcoinAddress() -> Bool {
    let fullAddress = self.components(separatedBy: ":")
    if fullAddress.count == 2 && fullAddress[0] == "bitcoin" {
        let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
        let r = fullAddress[1].startIndex..<fullAddress[1].endIndex
        let r2 = fullAddress[1].range(of: pattern, options: .regularExpression)
        return r == r2
    } else {
        return false
    }
}
</code>```

Title: Regular Expression for Validating Bitcoin Addresses

Body:
You are comparing self to the pattern instead of fullAddress[1].

Use the following:

func isValidBitcoinAddress() -> Bool {
    let fullAddress = self.components(separatedBy: ":")
    if fullAddress.count == 2 && fullAddress[0] == "bitcoin" {
        let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
        let r = fullAddress[1].startIndex..<fullAddress[1].endIndex
        let r2 = fullAddress[1].range(of: pattern, options: .regularExpression)
        return r == r2
    } else {
        return false
    }
}


问:
How can I make this Oracle SQL query More efficient and less redundant to avoid a "snapshot" error on large datasets?
I'm trying to improve my skills querying large data sets.

I want payments during a specific date range with an 'xyz' paycode,
where the "id1" is not 0 and not null, and if there are more than 13 payments to a specific "id1" This should be in the result of my query.

I feel like I'm being redundant querying the payment table twice, but I'm not sure how to get the id1 count and the payments with the specific paycode in a single query.

If I run this on a lot of data it's extremely slow and will not complete. I get a "snapshot" error.

All the table / data relations are indicated correctly in my joins / queries below, but how can I make this more elegant and more performant?

```<code>SELECT
    emp.emp_fname first_name,
    emp.emp_lname last_name,
    pmt.id1,
    pmt.id2,
    pmt.pay_date,
    pmt.pay_key,
    pmt.check_num,
    case.file_num
FROM

/*query to collect all valid id1s that occur more than 13 times */
    (
        SELECT
            id1
        FROM
            (
                SELECT
                    id1,
                    COUNT(*) AS cnt
                FROM
                    payment pmt
                WHERE
                        pay_key IN (
                            SELECT DISTINCT
                                pay_key
                            FROM
                                allotment
                            WHERE
                                pay_code = 'xyz'
                        )
                    AND
                        id1 <> 0
                    AND
                        id1 IS NOT NULL
                    AND
                        trunc(pmt.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
                    AND
                        upper(TRIM(deleted) ) = 'N'
                GROUP BY
                    id1
            )
        WHERE
            cnt > 13
    ) ptxids

    /*join these to full-payment records with matchinig id1s during this time*/
    INNER JOIN (
        SELECT
            *
        FROM
            payment
        WHERE
                upper(TRIM(deleted) ) = 'N'
            AND
                id1 <> 0
            AND
                id1 IS NOT NULL
            AND
                trunc(payment.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
    ) pmt ON pmt.id1 = ptxids.id1

    /*join on allotments where pay_key matches and allotment pay_code is xyz*/
    INNER JOIN allotment alt ON
        upper(TRIM(alt.deleted) ) = 'N'
    AND
        alt.pay_code = 'xyz'
    AND
        alt.pay_key = pmt.pay_key
   /*join on case to return the requested file-num*/
    INNER JOIN case ON case.event_num = alt.event_num
  /*join on emp to return payee / employee name */
    INNER JOIN  emp ON emp.event_num = case.event_num;
</code>```

答:
You can try this select :

```<code>SELECT *
FROM (
  SELECT
      COUNT(pmt.id1) OVER(PARTITION BY pmt.id1) cnt,
      emp.emp_fname first_name,
      emp.emp_lname last_name,
      pmt.id1,
      pmt.id2,
      pmt.pay_date,
      pmt.pay_key,
      pmt.check_num,
      case.file_num
  FROM payment pmt
  INNER JOIN allotment alt ON alt.pay_key = pmt.pay_key
        AND UPPER(TRIM(alt.deleted) ) = 'N'
        AND alt.pay_code = 'xyz'
  INNER JOIN case ON case.event_num = alt.event_num
  INNER JOIN  emp ON emp.event_num = case.event_num
WHERE     pmt.id1 <> 0
      AND
          pmt.id1 IS NOT NULL
      AND
          TRUNC(pmt.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
      AND
          UPPER(TRIM(pmt.deleted)) = 'N'
) A
WHERE A.cnt > 13;
</code>```

TRUNC(pmt.pay_date) and UPPER(TRIM(pmt.deleted)) in where clause are not use the index(es), If they are exist on pay_date and pmt.deleted columns.

Body:
I'm trying to improve my skills querying large data sets.

I want payments during a specific date range with an 'xyz' paycode,
where the "id1" is not 0 and not null, and if there are more than 13 payments to a specific "id1" This should be in the result of my query.

I feel like I'm being redundant querying the payment table twice, but I'm not sure how to get the id1 count and the payments with the specific paycode in a single query.

If I run this on a lot of data it's extremely slow and will not complete. I get a "snapshot" error.

All the table / data relations are indicated correctly in my joins / queries below, but how can I make this more elegant and more performant?

SELECT
    emp.emp_fname first_name,
    emp.emp_lname last_name,
    pmt.id1,
    pmt.id2,
    pmt.pay_date,
    pmt.pay_key,
    pmt.check_num,
    case.file_num
FROM

/*query to collect all valid id1s that occur more than 13 times */
    (
        SELECT
            id1
        FROM
            (
                SELECT
                    id1,
                    COUNT(*) AS cnt
                FROM
                    payment pmt
                WHERE
                        pay_key IN (
                            SELECT DISTINCT
                                pay_key
                            FROM
                                allotment
                            WHERE
                                pay_code = 'xyz'
                        )
                    AND
                        id1 <> 0
                    AND
                        id1 IS NOT NULL
                    AND
                        trunc(pmt.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
                    AND
                        upper(TRIM(deleted) ) = 'N'
                GROUP BY
                    id1
            )
        WHERE
            cnt > 13
    ) ptxids

    /*join these to full-payment records with matchinig id1s during this time*/
    INNER JOIN (
        SELECT
            *
        FROM
            payment
        WHERE
                upper(TRIM(deleted) ) = 'N'
            AND
                id1 <> 0
            AND
                id1 IS NOT NULL
            AND
                trunc(payment.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
    ) pmt ON pmt.id1 = ptxids.id1

    /*join on allotments where pay_key matches and allotment pay_code is xyz*/
    INNER JOIN allotment alt ON
        upper(TRIM(alt.deleted) ) = 'N'
    AND
        alt.pay_code = 'xyz'
    AND
        alt.pay_key = pmt.pay_key
   /*join on case to return the requested file-num*/
    INNER JOIN case ON case.event_num = alt.event_num
  /*join on emp to return payee / employee name */
    INNER JOIN  emp ON emp.event_num = case.event_num;

Body:
You can try this select :

SELECT *
FROM (
  SELECT
      COUNT(pmt.id1) OVER(PARTITION BY pmt.id1) cnt,
      emp.emp_fname first_name,
      emp.emp_lname last_name,
      pmt.id1,
      pmt.id2,
      pmt.pay_date,
      pmt.pay_key,
      pmt.check_num,
      case.file_num
  FROM payment pmt
  INNER JOIN allotment alt ON alt.pay_key = pmt.pay_key
        AND UPPER(TRIM(alt.deleted) ) = 'N'
        AND alt.pay_code = 'xyz'
  INNER JOIN case ON case.event_num = alt.event_num
  INNER JOIN  emp ON emp.event_num = case.event_num
WHERE     pmt.id1 <> 0
      AND
          pmt.id1 IS NOT NULL
      AND
          TRUNC(pmt.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
      AND
          UPPER(TRIM(pmt.deleted)) = 'N'
) A
WHERE A.cnt > 13;

TRUNC(pmt.pay_date) and UPPER(TRIM(pmt.deleted)) in where clause are not use the index(es), If they are exist on pay_date and pmt.deleted columns.


问:
PHP Automated Deployment and Testing
I asked a question here on automated deployment of automatically deploying java code.

Our back-end Java API is accessed by a PHP web app. It would be nice to be able to automatically deploy this web app (along with static files like CSS, JS and images) to our web server while performing automatic testing on PHP code. Is there something similar to this for PHP?

I also wonder if as part of this automated testing you can check that each actual page loads without a fatal error. I am sure I read about a google project which allows you to write page tests e.g. click on link a, go to page b etc etc.

Thanks

答: You may want to look into using Phing for deployment which has features that allow testing with PHPUnit and/or SimpleTest</p>

Title: PHP Automated Deployment and Testing


答:
because you called x = printf("Hello, World!\n") first;
the system will do the printf in output and also assign x = 14

therefore you have your second printf.

Title: How to print the return value of a function using printf()?


问:
Getting config.eager_load is set to nil while trying to run rails c in test
I'm trying to run the rails (4.1.2) console

```<code>rails c RAILS_ENV=test
</code>```

And I'm getting this:

```<code>> config.eager_load is set to nil. Please update your
> config/environments/*.rb files accordingly:
>
>   * development - set it to false   * test - set it to false (unless
> you use a tool that preloads your test environment)   * production -
> set it to true
>
> /Users/xxxxxx/.rvm/gems/ruby-2.2.2/gems/activerecord-4.1.12/lib/active_record/connection_adapters/connection_specification.rb:257:in
> `resolve_symbol_connection': 'RAILS_ENV=test' database is not
> configured. Available: ["development", "test", "production"]
> (ActiveRecord::AdapterNotSpecified)
</code>```

Yet in my test.rb I have config.eager_load = false and my database.yml is ok (I ran rake db:schema:load RAILS_ENV=test without issues.

How can I solve this?

答:
On Windows there is a glitch with RAILS_ENV. If you run

```<code>SET RAILS_ENV=development<SPACE>   <- with a space symbol after word "development"
</code>```

then you will get the error:

config.eager_load is set to nil. Please update your
  config/environments/*.rb fil es accordingly:

when doing rails server webrick.

So make sure you do type without a trailing space (and no quotes)

```<code>SET RAILS_ENV=development<ENTER>
</code>```

The same applies to all environments: test, production and development.

Body:
I'm trying to run the rails (4.1.2) console

rails c RAILS_ENV=test

And I'm getting this:

> config.eager_load is set to nil. Please update your
> config/environments/*.rb files accordingly:
>
>   * development - set it to false   * test - set it to false (unless
> you use a tool that preloads your test environment)   * production -
> set it to true
>
> /Users/xxxxxx/.rvm/gems/ruby-2.2.2/gems/activerecord-4.1.12/lib/active_record/connection_adapters/connection_specification.rb:257:in
> `resolve_symbol_connection': 'RAILS_ENV=test' database is not
> configured. Available: ["development", "test", "production"]
> (ActiveRecord::AdapterNotSpecified)

Yet in my test.rb I have config.eager_load = false and my database.yml is ok (I ran rake db:schema:load RAILS_ENV=test without issues.

How can I solve this?

Body:
On Windows there is a glitch with RAILS_ENV. If you run

SET RAILS_ENV=development<SPACE>   <- with a space symbol after word "development"

then you will get the error:

config.eager_load is set to nil. Please update your
  config/environments/*.rb fil es accordingly:

when doing rails server webrick.

So make sure you do type without a trailing space (and no quotes)

SET RAILS_ENV=development<ENTER>

The same applies to all environments: test, production and development.


问:
Unable to change to landscape mode in android
Since I made a lot of changes to the app, I am starting this thread to reflect them.  I am still having problems changing orientation.

Here's the code

```<code>Activity

    package com.flash;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

public class QuizActivity extends Activity {

private static final String TAG = "QuizActivity";

private Button mTrueButton;
private Button mFalseButton;
private ImageButton mPrevButton;
private ImageButton mNextButton;
private TextView mQuestionTextView;

private TrueFalse[] mQuestionBank;
private int mCurrentIndex = 0;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate(Bundle)");
    setQuestionBank();
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.activity_quiz);
        ProcessPortrait();
    } else {
        if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
        }
    }
}

private void ProcessPortrait() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mPrevButton = (ImageButton) findViewById(R.id.prev_button);
    mPrevButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mCurrentIndex == 0) {
                mCurrentIndex = mQuestionBank.length - 1;
            } else {
                mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
            }
            updateQuestion();
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void ProcessLandscape() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void setQuestionBank() {
    mQuestionBank = new TrueFalse[]{
        new TrueFalse(R.string.question_oceans, true),
        new TrueFalse(R.string.question_mideast, false),
        new TrueFalse(R.string.question_africa, false),
        new TrueFalse(R.string.question_americas, true),
        new TrueFalse(R.string.question_asia, true)
    };
}

private void updateQuestion() {
    int question = mQuestionBank[mCurrentIndex].getmQuestion();
    mQuestionTextView.setText(question);
}

private void checkAnswer(boolean userPressedTrue) {
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].ismTrueQuestion();

    int messageResId = 0;

    if (userPressedTrue == answerIsTrue) {
        messageResId = R.string.correct_Toast;
    } else {
        messageResId = R.string.incorrect_Toast;
    }

    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}

@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart() called");
}

@Override
public void onPause() {
    super.onPause();
    Log.d(TAG, "onStart() called");
}

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "onResume() called");
}

@Override
public void onStop() {
    super.onStop();
    Log.d(TAG, "onStop() called");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy() called");
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.main);
        ProcessPortrait();
    } else if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
    }
}
</code>```

}

```<code>XML

Portrait

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center"
          android:orientation="vertical">

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/prev_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/prev_button"
            android:src="@drawable/arrow_left"/>

        <ImageButton
            android:id="@+id/next_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/next_button"
            android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </LinearLayout>
</code>```

Landscape

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical|center_horizontal"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/next_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="10sp"
                android:contentDescription="@string/next_button"
                android:gravity="bottom|right"
                android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </FrameLayout>

Manifest

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.flash"
        android:versionCode="1"
        android:versionName="1.0"
    >
        <application android:label="@string/app_name"
                 android:icon="@drawable/ic_launcher" >
            <activity android:name=".QuizActivity"
                  android:label="@string/app_name"
                  android:configChanges="orientation|
        keyboardHidden|screenSize">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>
</code>```

When I debug using my phone, landscape works, although it may by my phone that is adjusting to the new orientation and not the app.

I am currently unable to get the debugger to work when using the emulator, so that is an issue I need help with as well.

When I run/debug the app, the home page displays and I have to press the recent apps button on the emulator and then double click on the app to bring it forward, hmmm, yet another issue.

Anyway, any help will be greatly appreciated

答:
```<code>The best way for you scenario would be to remove
android:configChanges="orientation" from your manifest since you just want to change layouts during orientation.

    If you use android:configChanges="orientation"
    then you must implement in activity like:

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // Handle Lanscape codes here
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            // Handle portrait codes here
        }
    }
</code>```

Body:
Since I made a lot of changes to the app, I am starting this thread to reflect them.  I am still having problems changing orientation.

Here's the code

Activity

    package com.flash;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

public class QuizActivity extends Activity {

private static final String TAG = "QuizActivity";

private Button mTrueButton;
private Button mFalseButton;
private ImageButton mPrevButton;
private ImageButton mNextButton;
private TextView mQuestionTextView;

private TrueFalse[] mQuestionBank;
private int mCurrentIndex = 0;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate(Bundle)");
    setQuestionBank();
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.activity_quiz);
        ProcessPortrait();
    } else {
        if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
        }
    }
}

private void ProcessPortrait() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mPrevButton = (ImageButton) findViewById(R.id.prev_button);
    mPrevButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mCurrentIndex == 0) {
                mCurrentIndex = mQuestionBank.length - 1;
            } else {
                mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
            }
            updateQuestion();
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void ProcessLandscape() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void setQuestionBank() {
    mQuestionBank = new TrueFalse[]{
        new TrueFalse(R.string.question_oceans, true),
        new TrueFalse(R.string.question_mideast, false),
        new TrueFalse(R.string.question_africa, false),
        new TrueFalse(R.string.question_americas, true),
        new TrueFalse(R.string.question_asia, true)
    };
}

private void updateQuestion() {
    int question = mQuestionBank[mCurrentIndex].getmQuestion();
    mQuestionTextView.setText(question);
}

private void checkAnswer(boolean userPressedTrue) {
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].ismTrueQuestion();

    int messageResId = 0;

    if (userPressedTrue == answerIsTrue) {
        messageResId = R.string.correct_Toast;
    } else {
        messageResId = R.string.incorrect_Toast;
    }

    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}

@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart() called");
}

@Override
public void onPause() {
    super.onPause();
    Log.d(TAG, "onStart() called");
}

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "onResume() called");
}

@Override
public void onStop() {
    super.onStop();
    Log.d(TAG, "onStop() called");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy() called");
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.main);
        ProcessPortrait();
    } else if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
    }
}

}

XML

Portrait

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center"
          android:orientation="vertical">

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/prev_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/prev_button"
            android:src="@drawable/arrow_left"/>

        <ImageButton
            android:id="@+id/next_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/next_button"
            android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </LinearLayout>

Landscape

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical|center_horizontal"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/next_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="10sp"
                android:contentDescription="@string/next_button"
                android:gravity="bottom|right"
                android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </FrameLayout>

Manifest

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.flash"
        android:versionCode="1"
        android:versionName="1.0"
    >
        <application android:label="@string/app_name"
                 android:icon="@drawable/ic_launcher" >
            <activity android:name=".QuizActivity"
                  android:label="@string/app_name"
                  android:configChanges="orientation|
        keyboardHidden|screenSize">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>

When I debug using my phone, landscape works, although it may by my phone that is adjusting to the new orientation and not the app.

I am currently unable to get the debugger to work when using the emulator, so that is an issue I need help with as well.

When I run/debug the app, the home page displays and I have to press the recent apps button on the emulator and then double click on the app to bring it forward, hmmm, yet another issue.

Anyway, any help will be greatly appreciated


问:
SQL Query to find out specific column from all database
I wanted to find out the columns which contains the word "VAP" or cancellation. but the problem is we have several number of databases in our server. I wanted to know in which database/table contains the columns name which consist these words. Can anyone let us know if there is any query which can be used to search column name from all databases? I have tried below query but it will only help to find from a single database.</p>

```<code>select distinct
    t.name as TableName,
    SCHEMA_NAME(t.schema_id)   as TableSchema,
    c.name as ColumnName,
    ct.name as ColumnDataType,
    c.is_nullable as IsNullable
from
    sys.tables t with(nolock)
inner join
    sys.columns c with(nolock) on t.object_id = c.object_id
inner join
    sys.types ct with(nolock) on ct.system_type_id = c.system_type_id
where
    c.name like '%VAP%'
order by
    t.name
</code>```

答:
If you need to find database objects (e.g. tables, columns, triggers) by name - have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).

It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??

Body:
I wanted to find out the columns which contains the word "VAP" or cancellation. but the problem is we have several number of databases in our server. I wanted to know in which database/table contains the columns name which consist these words. Can anyone let us know if there is any query which can be used to search column name from all databases? I have tried below query but it will only help to find from a single database.

select distinct
    t.name as TableName,
    SCHEMA_NAME(t.schema_id)   as TableSchema,
    c.name as ColumnName,
    ct.name as ColumnDataType,
    c.is_nullable as IsNullable
from
    sys.tables t with(nolock)
inner join
    sys.columns c with(nolock) on t.object_id = c.object_id
inner join
    sys.types ct with(nolock) on ct.system_type_id = c.system_type_id
where
    c.name like '%VAP%'
order by
    t.name


问:
alternate optimized query of sub query
```<code>select * from solar_park where solar_park_uid
in
(select distinct solar_park from solar_park_pooling_station where pooling_station
in
(select distinct pooling_station_uid FROM solar_inverter where solar_generator_uid in (:solarGeneratorUid));
</code>```

I am using this query but for certain reasons i want alter query of this plz help

答:
Please try with below query where table it's left outer join:</p>

```<code>select * from solar_park  as SP
left outer join (
select distinct solar_park from solar_park_pooling_station
) as SPPS on SPPS.solar_park = SP.solar_park_uid
left outer join (
select distinct pooling_station_uid FROM solar_inverter where solar_generator_uid in (:solarGeneratorUid)
) as  SI on SI.pooling_station_uid= SPPS.pooling_station
where SPPS.solar_park  is not null and SI.pooling_station_uid is not null
</code>```

Title: alternate optimized query of sub query

Body:
select * from solar_park where solar_park_uid
in
(select distinct solar_park from solar_park_pooling_station where pooling_station
in
(select distinct pooling_station_uid FROM solar_inverter where solar_generator_uid in (:solarGeneratorUid));

I am using this query but for certain reasons i want alter query of this plz help

Body:
Please try with below query where table it's left outer join:

select * from solar_park  as SP
left outer join (
select distinct solar_park from solar_park_pooling_station
) as SPPS on SPPS.solar_park = SP.solar_park_uid
left outer join (
select distinct pooling_station_uid FROM solar_inverter where solar_generator_uid in (:solarGeneratorUid)
) as  SI on SI.pooling_station_uid= SPPS.pooling_station
where SPPS.solar_park  is not null and SI.pooling_station_uid is not null