问:
Can i update an existing ec2 instance with terraform
Is it possible to edit an existing resource example: an ec2 instance with the terraform template.
Ex: I have a ec2 instance created with aws console, can i add that ec2 instance to add a new security group using the instance id in terraform template. I know this can't be done with cloud formation. Currently I can do this with Ansible, but i don't see a way to do it with terraform or cloudformation</p>

答:
Yes, you can! However you have to then manage the instance with Terraform. There's no way to just "Do this to a running instance" and call it a day - that's what the various SDKs are for and the AWS CLI.

What you're looking for is terraform import - to use this, you'll want to define a resource in your Terraform configuration, map up everything how you want, and then import that resource.

Since you're using an EC2 instance, it will look something like:

```<code>terraform import aws_instance.web i-12345678
</code>```

Once this is done; if you do a terraform plan you can see what attributes you forgot to add to your configuration you setup for this - add those in, and then you can start managing this resource.

Body:
Yes, you can! However you have to then manage the instance with Terraform. There's no way to just "Do this to a running instance" and call it a day - that's what the various SDKs are for and the AWS CLI.

What you're looking for is terraform import - to use this, you'll want to define a resource in your Terraform configuration, map up everything how you want, and then import that resource.

Since you're using an EC2 instance, it will look something like:

terraform import aws_instance.web i-12345678

Once this is done; if you do a terraform plan you can see what attributes you forgot to add to your configuration you setup for this - add those in, and then you can start managing this resource.


来源: stackexchange

问:
Is Reactive Programming bounded to Functional programming?
I'd like to know how Reactive Programming is tied to Functional-Programming.

Most papers refer "Reactive Programming" as "Functional Reactive Programming".

Does Reactive Programming can be implemented outside Functional Programming?

Is it easier to write Reactive Programs with Functional Language?

答: No it is not both are independent programming paradigms, reactive being stream based approach and functional based on the philosophy of pure functions for all.</p>

ContentLicense: CC BY-SA 3.0


问:
HTML datalist keeps crashing when dynamically loaded with Vue
I'm using Vue.js to load an HTML datalist. Whenever I type in my input box that is connected to my datalist, my page freezes (using Chrome). I'm using jQuery to make an AJAX call to initially get all of my users when the page loads, then using the JavaScript filter function to make a new array that has indexOf whatever is typed in my input box, then putting that new filtered array of objects into the datalist element.

Here is my HTML:

```<code><div id="my-app">
  <input list="user-search" type="text" id="find-user" name="find-user" v-model="findUser">
    <datalist id="user-search">
      <option v-for="user in findUserList">{{ user.vendorName }}</option>
    </datalist>
</div>
</code>```

Here is my Vue JavaScript:

```<code>var myApp = new Vue({
  el: '#my-app',
  data: {
    users: [],
    findUser: '',
    findUserList: '',
  },
  watch: {
    findUser: function(val) {
      this.findUserResults();
    }
  },
  methods: {
    findUserResults: function() {
      var lookFor = this.findUser.toLowerCase();
      this.findUserList = this.users.filter(function(user) {
        return (user.vendorName.toLowerCase().indexOf(myApp.findUser.toLowerCase()) > -1 || user.email.toLowerCase().indexOf(myApp.findUser.toLowerCase()) > -1);
      });
    },
    loadUsers: function() {
      $.ajax({
        method: 'GET',
        url: '/users',
        success: function(data) {
          myApp.users = JSON.parse(data);
        },
        error: function() {
                console.log('error...');
        }
      });
    }
  },
  mounted: function() {
    this.loadUsers();
  }
})
</code>```

The users load fine when the page loads. No problems there. I even commented out the v-for and just console.log'd the results of the filter with no problem either. The issue comes in when I implement dynamically adding the <option> values in the <datalist>. I've tried wrapping the options in the vue <template> tag and moving the v-for there with no success.

I have this working fine on another page, but instead I'm populating a table with
 and  instead of <datalist> and <option>.

What could be causing my page to crash? Is <datalist> not good enough to handle all of this? Maybe I'm missing something that a second set of eyes could help solve.

EDIT

The data that is being populated into users looks like this (it's an array of objects):

```<code>[{id:1, vendorName:'john'}, {id:2, vendorName:'Rachel', {id:3, vendorName:'Steve'}]
</code>```

ANSWER

This was actually just an example of someone overthinking (me). B.Fleming's answer about this being recursive clued me into why my approach above was incorrect. There is no need to keep reloading the datalist options every time the user types. That's exactly what <datalist> being linked to <input> does; no JavaScript needed. All I need(ed) to do was load all ~3,000 of my users into the <datalist> tag as <option>s on page load (or whenever I want the input and datalist to show up), and let the datalist and input handle the rest. I haven't tested this with the app in the example above because I'm not near that computer, but just as a proof of concept that a datalist can handle thousands of option elements, I wrote this and ran it locally with no issue (not sure why the snippet console keeps saying there is an error when it works):

window.onload = function() {
    var datalistElement = document.getElementById('datalist-test');
    var datalistString = '';
    for (var i = 0; i < 3000; i++) {
        datalistString += '<option>' + Math.random().toString(36).substring(7); + '</option>';
    }
    datalistElement.innerHTML = datalistString;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>Datalist Test</title>
</head>

<body>
 <input list="datalist-test" type="text">
 <datalist id="datalist-test">
 </datalist>
</body>
</html></code>```

3,000 datalist option elements, and it's fine.

答:
Typically you would use a computed property for this. I also made a few other changes. For one, referencing the Vue itself from inside it is a bad practice; just use this. Also datalist options have a value property that you need to specify.

console.clear()

const users = [
  {vendorName: "Vendor One", email: "bob@example.com"},
  {vendorName: "Vendor Two", email: "mary@example.com"},
  {vendorName: "Vendor Three", email: "jim@example.com"},
  {vendorName: "Vendor Four", email: "joe@vendor.com"},
  {vendorName: "Vendor Five", email: "sara@vendor.com"},

]
var myApp = new Vue({
  el: '#my-app',
  data: {
    users: [],
    findUser: '',
  },
  computed:{
    vendors(){
      return this.users.filter(u => {
        return u.vendorName.toLowerCase().indexOf(this.findUser) > -1 ||
          u.email.toLowerCase().indexOf(this.findUser) > -1
      })
    }
  },
  methods: {
    loadUsers: function() {
      // obviously, this is different for example purposes
      this.users = users
    }
  },
  mounted: function() {
    this.loadUsers();
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@2.4.2"></script>
<div id="my-app">
  <h3>Type "V"</h3>
  <input list="user-search" name="find-user" v-model="findUser">
  <datalist id="user-search">
    <option v-for="user in vendors" :value="user.vendorName">
  </datalist>
</div></code>```

Body:
I'm using Vue.js to load an HTML datalist. Whenever I type in my input box that is connected to my datalist, my page freezes (using Chrome). I'm using jQuery to make an AJAX call to initially get all of my users when the page loads, then using the JavaScript filter function to make a new array that has indexOf whatever is typed in my input box, then putting that new filtered array of objects into the datalist element.

Here is my HTML:

  <input list="user-search" type="text" id="find-user" name="find-user" v-model="findUser">
    <datalist id="user-search">
      <option v-for="user in findUserList">{{ user.vendorName }}</option>
    </datalist>

Here is my Vue JavaScript:

var myApp = new Vue({
  el: '#my-app',
  data: {
    users: [],
    findUser: '',
    findUserList: '',
  },
  watch: {
    findUser: function(val) {
      this.findUserResults();
    }
  },
  methods: {
    findUserResults: function() {
      var lookFor = this.findUser.toLowerCase();
      this.findUserList = this.users.filter(function(user) {
        return (user.vendorName.toLowerCase().indexOf(myApp.findUser.toLowerCase()) > -1 || user.email.toLowerCase().indexOf(myApp.findUser.toLowerCase()) > -1);
      });
    },
    loadUsers: function() {
      $.ajax({
        method: 'GET',
        url: '/users',
        success: function(data) {
          myApp.users = JSON.parse(data);
        },
        error: function() {
                console.log('error...');
        }
      });
    }
  },
  mounted: function() {
    this.loadUsers();
  }
})

The users load fine when the page loads. No problems there. I even commented out the v-for and just console.log'd the results of the filter with no problem either. The issue comes in when I implement dynamically adding the <option> values in the <datalist>. I've tried wrapping the options in the vue <template> tag and moving the v-for there with no success.

I have this working fine on another page, but instead I'm populating a table with
 and  instead of <datalist> and <option>.

What could be causing my page to crash? Is <datalist> not good enough to handle all of this? Maybe I'm missing something that a second set of eyes could help solve.

EDIT

The data that is being populated into users looks like this (it's an array of objects):

[{id:1, vendorName:'john'}, {id:2, vendorName:'Rachel', {id:3, vendorName:'Steve'}]

ANSWER

This was actually just an example of someone overthinking (me). B.Fleming's answer about this being recursive clued me into why my approach above was incorrect. There is no need to keep reloading the datalist options every time the user types. That's exactly what <datalist> being linked to <input> does; no JavaScript needed. All I need(ed) to do was load all ~3,000 of my users into the <datalist> tag as <option>s on page load (or whenever I want the input and datalist to show up), and let the datalist and input handle the rest. I haven't tested this with the app in the example above because I'm not near that computer, but just as a proof of concept that a datalist can handle thousands of option elements, I wrote this and ran it locally with no issue (not sure why the snippet console keeps saying there is an error when it works):

window.onload = function() {
    var datalistElement = document.getElementById('datalist-test');
    var datalistString = '';
    for (var i = 0; i < 3000; i++) {
        datalistString += '<option>' + Math.random().toString(36).substring(7); + '</option>';
    }
    datalistElement.innerHTML = datalistString;
}

<!DOCTYPE html>

 <title>Datalist Test</title>

 <input list="datalist-test" type="text">
 <datalist id="datalist-test">
 </datalist>

3,000 datalist option elements, and it's fine.

Body:
Typically you would use a computed property for this. I also made a few other changes. For one, referencing the Vue itself from inside it is a bad practice; just use this. Also datalist options have a value property that you need to specify.

console.clear()

const users = [
  {vendorName: "Vendor One", email: "bob@example.com"},
  {vendorName: "Vendor Two", email: "mary@example.com"},
  {vendorName: "Vendor Three", email: "jim@example.com"},
  {vendorName: "Vendor Four", email: "joe@vendor.com"},
  {vendorName: "Vendor Five", email: "sara@vendor.com"},

]
var myApp = new Vue({
  el: '#my-app',
  data: {
    users: [],
    findUser: '',
  },
  computed:{
    vendors(){
      return this.users.filter(u => {
        return u.vendorName.toLowerCase().indexOf(this.findUser) > -1 ||
          u.email.toLowerCase().indexOf(this.findUser) > -1
      })
    }
  },
  methods: {
    loadUsers: function() {
      // obviously, this is different for example purposes
      this.users = users
    }
  },
  mounted: function() {
    this.loadUsers();
  }
})

<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="my-app">
  <h3>Type "V"</h3>
  <input list="user-search" name="find-user" v-model="findUser">
  <datalist id="user-search">
    <option v-for="user in vendors" :value="user.vendorName">
  </datalist>
</div>

ContentLicense: CC BY-SA 4.0


问:
How to read form post data in angular4?As we can read posted params in .net using Request.Form["key"] ,how to do it in Angular 4?
How to read post parameters posted from .aspx page in angular 4? Like we can read post params in .net using Request.Form["key"] ,is there any way we can do it in Angular 4?</p>

答:
I think you have some misunderstanding.

You can send post, get, put, delete, patch request to .net, php, Java (server)

You can not handle post request.

You can submit the form.


问:
SQL Server Query Store: [sys.query_store_query_text].[query_sql_text] is truncated?
I'm working with the following query against the Query Store:

```<code>SELECT
TOP 100
    qp.last_execution_time [qp__last_execution_time],
    qt.query_sql_text,
    len(qt.query_sql_text) sql_length,
    round(rs.avg_duration ,5) avg_duration
    ,max_rowcount,avg_rowcount,last_rowcount
FROM
    sys.query_store_plan qp
    INNER JOIN sys.query_store_query         [q]        ON qp.query_id = q.query_id
    INNER JOIN sys.query_store_query_text    [qt]       ON q.query_text_id = qt.query_text_id
    INNER JOIN sys.query_store_runtime_stats [rs]       ON qp.plan_id = rs.plan_id
WHERE
order by len(qt.query_sql_text) desc
</code>```

What I'm noticing is that it seems the [query_sql_text] is being truncated, for example a typical statement will end with:

```<code>CAST( '20170920 00:00:00' AS datetime),CAST( '20140701 00:00:
</code>```

Possibly relevant:

The SQL in this case is being generated by Power BI.

The len(qt.query_sql_text) is not maxed out at the same value when text is truncated.

I am viewing the SQL by copy/pasting from SSMS results pane into notepad.

SQL Version:  Microsoft SQL Azure (RTM) - 12.0.2000.8   Aug 29 2017 13:06:11

I recall in some other "system tables" that SQL Server truncates SQL.

So the question is:  can anyone say definitively whether [sys.query_store_query_text].[query_sql_text] can in some cases be truncated by SQL Server itself?

The alternative possibility, truncation happening in the client application, doesn't make any sense as it has to send a complete, valid SQL statement to SQL Server, otherwise how could it be executed?  And yet, the variance in len(query_sql_text) rules out exceeding a column length limitation.

What might be going on here?

答:
SSMS will truncate blob results when returning data to the data grid.  You can modify the length in the Query Options, or return the data as XML.  EG

```<code>SELECT
TOP 100
    qp.last_execution_time [qp__last_execution_time],
    qt.query_sql_text,
    len(qt.query_sql_text) sql_length,
    round(rs.avg_duration ,5) avg_duration
    ,max_rowcount,avg_rowcount,last_rowcount
FROM
    sys.query_store_plan qp
    INNER JOIN sys.query_store_query         [q]        ON qp.query_id = q.query_id
    INNER JOIN sys.query_store_query_text    [qt]       ON q.query_text_id = qt.query_text_id
    INNER JOIN sys.query_store_runtime_stats [rs]       ON qp.plan_id = rs.plan_id
order by len(qt.query_sql_text) desc
for xml path
</code>```

Or to get each query in a separate XML column:

```<code>SELECT
TOP 100
    qp.last_execution_time [qp__last_execution_time],
    ( select qt.query_sql_text for xml path, type ) query_sql_text,
    len(qt.query_sql_text) sql_length,
    round(rs.avg_duration ,5) avg_duration
    ,max_rowcount,avg_rowcount,last_rowcount
FROM
    sys.query_store_plan qp
    INNER JOIN sys.query_store_query         [q]        ON qp.query_id = q.query_id
    INNER JOIN sys.query_store_query_text    [qt]       ON q.query_text_id = qt.query_text_id
    INNER JOIN sys.query_store_runtime_stats [rs]       ON qp.plan_id = rs.plan_id

order by len(qt.query_sql_text) desc
</code>```

Or get the query text from the XEvents UI in SSMS.

Body:
I'm working with the following query against the Query Store:

SELECT
TOP 100
    qp.last_execution_time [qp__last_execution_time],
    qt.query_sql_text,
    len(qt.query_sql_text) sql_length,
    round(rs.avg_duration ,5) avg_duration
    ,max_rowcount,avg_rowcount,last_rowcount
FROM
    sys.query_store_plan qp
    INNER JOIN sys.query_store_query         [q]        ON qp.query_id = q.query_id
    INNER JOIN sys.query_store_query_text    [qt]       ON q.query_text_id = qt.query_text_id
    INNER JOIN sys.query_store_runtime_stats [rs]       ON qp.plan_id = rs.plan_id
WHERE
order by len(qt.query_sql_text) desc

What I'm noticing is that it seems the [query_sql_text] is being truncated, for example a typical statement will end with:

CAST( '20170920 00:00:00' AS datetime),CAST( '20140701 00:00:

Possibly relevant:

The SQL in this case is being generated by Power BI.

The len(qt.query_sql_text) is not maxed out at the same value when text is truncated.

I am viewing the SQL by copy/pasting from SSMS results pane into notepad.

SQL Version:  Microsoft SQL Azure (RTM) - 12.0.2000.8   Aug 29 2017 13:06:11

I recall in some other "system tables" that SQL Server truncates SQL.

So the question is:  can anyone say definitively whether [sys.query_store_query_text].[query_sql_text] can in some cases be truncated by SQL Server itself?

The alternative possibility, truncation happening in the client application, doesn't make any sense as it has to send a complete, valid SQL statement to SQL Server, otherwise how could it be executed?  And yet, the variance in len(query_sql_text) rules out exceeding a column length limitation.

What might be going on here?

Body:
SSMS will truncate blob results when returning data to the data grid.  You can modify the length in the Query Options, or return the data as XML.  EG

SELECT
TOP 100
    qp.last_execution_time [qp__last_execution_time],
    qt.query_sql_text,
    len(qt.query_sql_text) sql_length,
    round(rs.avg_duration ,5) avg_duration
    ,max_rowcount,avg_rowcount,last_rowcount
FROM
    sys.query_store_plan qp
    INNER JOIN sys.query_store_query         [q]        ON qp.query_id = q.query_id
    INNER JOIN sys.query_store_query_text    [qt]       ON q.query_text_id = qt.query_text_id
    INNER JOIN sys.query_store_runtime_stats [rs]       ON qp.plan_id = rs.plan_id
order by len(qt.query_sql_text) desc
for xml path

Or to get each query in a separate XML column:

SELECT
TOP 100
    qp.last_execution_time [qp__last_execution_time],
    ( select qt.query_sql_text for xml path, type ) query_sql_text,
    len(qt.query_sql_text) sql_length,
    round(rs.avg_duration ,5) avg_duration
    ,max_rowcount,avg_rowcount,last_rowcount
FROM
    sys.query_store_plan qp
    INNER JOIN sys.query_store_query         [q]        ON qp.query_id = q.query_id
    INNER JOIN sys.query_store_query_text    [qt]       ON q.query_text_id = qt.query_text_id
    INNER JOIN sys.query_store_runtime_stats [rs]       ON qp.plan_id = rs.plan_id

order by len(qt.query_sql_text) desc

Or get the query text from the XEvents UI in SSMS.


问:
how to keep program running after .mainloop()?
I'm trying to create a program which displays images using tkinter. The code I've written so far displays the image perfectly, however the program does not continue until the tkinter window is closed. I was wondering if there was any function instead of .mainloop() to keep the program running alongside the tkinter window? Any help much appreciated

```<code>window = Tk()
canvas1 = Canvas(window,height=600,width=600)
file = PhotoImage(file = 'GoogleDrive.png')
image = canvas1.create_image(300, 300, anchor = CENTER, image = file)
canvas1.pack()
canvas1.mainloop()

print ('\nA: Google Drive')
time.sleep(1)
print ('B: Google Slides')
time.sleep(1)
print ('C: Google Photos')
</code>```

答:
The mainloop needs to be the last logical line of code. The mainloop should also be called on the Tk object, in your case window.

In order for your code to run, you either need to move the print and sleep statements before the mainloop, or move them to a function and instead call that function, before the mainloop.

It is also worth noting that in Tkinter, you can use after for timings instead of sleep.

Body:
I'm trying to create a program which displays images using tkinter. The code I've written so far displays the image perfectly, however the program does not continue until the tkinter window is closed. I was wondering if there was any function instead of .mainloop() to keep the program running alongside the tkinter window? Any help much appreciated

window = Tk()
canvas1 = Canvas(window,height=600,width=600)
file = PhotoImage(file = 'GoogleDrive.png')
image = canvas1.create_image(300, 300, anchor = CENTER, image = file)
canvas1.pack()
canvas1.mainloop()

print ('\nA: Google Drive')
time.sleep(1)
print ('B: Google Slides')
time.sleep(1)
print ('C: Google Photos')


问:
How to move/copy files locally with Chef
I haven't yet come across a Chef resource that will copy/move files locally. For example, I want to download jetty hightide and unzip it. Once done, copy all the files into a particular folder, like this:

```<code># mv /var/tmp/jetty-hightide-7.4.5.v20110725/* /opt/jetty/
</code>```

BTW, jettyhightide when unzipped, gives you a folder and inside that folder rest of the files are located.  Hence unzip jetty-hightide-7.4.5.v20110725.zip -d /opt/jetty/ is useless because it will create a directory /opt/jetty/jetty-hightide-7.4.5.v20110725/* whereas what I really want is /opt/jetty/*. Hence I am looking for a local copy/move resource in Chef.

答:
If your recipe is already tied to Windows, you can use embedded PowerShell scripts, like this:</p>

```<code># Copy files from "C:/foo/lib" to "C:/foo"
powershell_script "copy_lib" do
  code <<-EOH
    $ErrorActionPreference = "Stop"
      Get-ChildItem -Path "C:/foo/lib" -File | Foreach-Object {
        Copy-Item -Path $_.Fullname -Destination "C:/foo" -Force
      }
  EOH
end

# Delete "C:/foo/lib" folder
powershell_script "delete_lib" do
  code <<-EOH
    $ErrorActionPreference = "Stop"
    Remove-Item -Path "C:/foo/lib" -Recurse
  EOH
end
</code>```

Body:
I haven't yet come across a Chef resource that will copy/move files locally. For example, I want to download jetty hightide and unzip it. Once done, copy all the files into a particular folder, like this:

# mv /var/tmp/jetty-hightide-7.4.5.v20110725/* /opt/jetty/

BTW, jettyhightide when unzipped, gives you a folder and inside that folder rest of the files are located.  Hence unzip jetty-hightide-7.4.5.v20110725.zip -d /opt/jetty/ is useless because it will create a directory /opt/jetty/jetty-hightide-7.4.5.v20110725/* whereas what I really want is /opt/jetty/*. Hence I am looking for a local copy/move resource in Chef.

Body:
If your recipe is already tied to Windows, you can use embedded PowerShell scripts, like this:

# Copy files from "C:/foo/lib" to "C:/foo"
powershell_script "copy_lib" do
  code <<-EOH
    $ErrorActionPreference = "Stop"
      Get-ChildItem -Path "C:/foo/lib" -File | Foreach-Object {
        Copy-Item -Path $_.Fullname -Destination "C:/foo" -Force
      }
  EOH
end

# Delete "C:/foo/lib" folder
powershell_script "delete_lib" do
  code <<-EOH
    $ErrorActionPreference = "Stop"
    Remove-Item -Path "C:/foo/lib" -Recurse
  EOH
end


问:
Trouble trying to use CmdArgs in Haskell (Failed to load interface for ‘CmdArgs’)
I am currently trying to use CmdArgs and I am running into some trouble.

The code is here on github and the error I am getting is this:

```<code> $ stack build

 gc2-0.1.0.0: configure (lib + exe) Configuring
 gc2-0.1.0.0... gc2-0.1.0.0: build (lib + exe) Preprocessing library
 gc2-0.1.0.0... Preprocessing executable 'gc2-exe' for gc2-0.1.0.0...
 [1 of 1] Compiling Main             ( app/Main.hs,
 .stack-work/dist/x86_64-linux-nopie/Cabal-1.24.2.0/build/gc2-exe/gc2-exe-tmp/Main.o )

 /home/kuwze/src/haskell/gc2/app/Main.hs:6:1: error:
     Failed to load interface for ‘CmdArgs’
     Use -v to see a list of the files searched for.

 --  While building package gc2-0.1.0.0 using:
       /home/kuwze/.stack/setup-exe-cache/x86_64-linux-nopie/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux-nopie/Cabal-1.24.2.0 build lib:gc2 exe:gc2-exe --ghc-options " -ddump-hi -ddump-to-file"
     Process exited with code: ExitFailure 1
</code>```

Any help would be greatly appreciated.

答:
It turns out like usual I am an idiot.

The correct thing to do is to check the full path of a library; for my example the page for CmdArgs specifies that the library path for the module is System.Console.CmdArgs.

Body:
I am currently trying to use CmdArgs and I am running into some trouble.

The code is here on github and the error I am getting is this:

 $ stack build

 gc2-0.1.0.0: configure (lib + exe) Configuring
 gc2-0.1.0.0... gc2-0.1.0.0: build (lib + exe) Preprocessing library
 gc2-0.1.0.0... Preprocessing executable 'gc2-exe' for gc2-0.1.0.0...
 [1 of 1] Compiling Main             ( app/Main.hs,
 .stack-work/dist/x86_64-linux-nopie/Cabal-1.24.2.0/build/gc2-exe/gc2-exe-tmp/Main.o )

 /home/kuwze/src/haskell/gc2/app/Main.hs:6:1: error:
     Failed to load interface for ‘CmdArgs’
     Use -v to see a list of the files searched for.

 --  While building package gc2-0.1.0.0 using:
       /home/kuwze/.stack/setup-exe-cache/x86_64-linux-nopie/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux-nopie/Cabal-1.24.2.0 build lib:gc2 exe:gc2-exe --ghc-options " -ddump-hi -ddump-to-file"
     Process exited with code: ExitFailure 1

Any help would be greatly appreciated.


问:
mysql query returns false, mysql insert works but echo statement doesn't show up
I am making a text-based online game, in my game, there is a battle system. After defeating the enemy you can be awarded a badge if you do not already have said badge. However, for some strange reason that I can not wrap my head around, the badge is added to the database as it should be (if the table row for the badge does not exist on the MySQL database) but the text that should accompany earning the badge shows up sometimes. I would say the echo shows 50% of the time or less. Here is my code:

```<code>$gettrainerbadge = mysqli_query($conn, "SELECT * FROM t_badges where
badge='$badge' AND trainer='$getuser3[username]'");
$gettrainerbadge2 = mysqli_fetch_assoc($gettrainerbadge);

if(!$gettrainerbadge2)
{
    //This echo shows up maybe 50% of the time the form is submitted.

    echo "<font face='verdana' size='2'><br><br><br><img src='images/badges/$get_gym_leader3[badge].png' style='padding: 10px;'><br>By defeating $getuser3[battle_trainer] you have also earned a(n) $get_gym_leader3[badge] Badge!";

    //This INSERT works as expected when the badge doesn't exist it adds the badge to the database if the badge already exists it does nothing

    $addbadge = "INSERT INTO t_badges (`trainer`, `badge`) VALUES ('$getuser3[username]', '$get_gym_leader3[badge]')";
    mysqli_query($conn, $addbadge);

}
</code>```

As I've said the echo statement works half the time, it should work every time and I can not figure out why the badge is being added but the text that accompanies it doesn't show. Any help is appreciated.

After playing with the code some more I've noticed that sometimes I can see a VERY fast flash of the page with the image of the badge, so I don't think the above code is to blame. I think it has to do with the following scripts I am using to submit the forms automatically without user feedback. I don't know why they would interfere with each other, but I'm almost certain that there is a double post submission going on somewhere. If anyone could help point out what I might be doing wrong here I would appreciate it.

```<code>if($get_remaining_opponents3 > '0')
{

print "<form action='index.php?action=battle' method='POST'
name='attackselect' id='attackselect' style='margin: 0px;'><td width='100%'
height='50px' style='background: #e6e6e6; border:2px solid #e6e6e6; border-
radius: 25px;'>

<center>

<font face='verdana' size='2'>

<label style='margin-top: 0px;' id='battle_text'>

<input type='radio' name='continue' value='continue' checked>

<i>Resuming battle ... (<span id='continue'> </span>)</i>
</input>
</label>
</form>
";
?>

<script>

var milisec= 0;
var seconds=4;

document.getElementById("continue").innerHTML ='4';
continue_battle() ;

function continue_battle(){
if (milisec<=0){
milisec=9;
seconds-=1;
}
if (seconds<=-1){
milisec=0;
seconds+=1;
}
else
{
milisec-=1;
document.getElementById("continue").innerHTML =seconds;
setTimeout("continue_battle()",100);
}
if(document.getElementById("continue").innerHTML == '0')
{
document.getElementById("attackselect").submit();
}
}
</script>

<?php
print "</form>";
}
else
{

print "<form action='index.php?action=battle' method='POST' name='victory'
id='victorious' style='margin: 0px;'><td width='100%' height='50px'
style='background: #e6e6e6; border:2px solid #e6e6e6; border-radius: 25px;'>

<center>

<font face='verdana' size='2'>

<label style='margin-top: 0px;' id='battle_text'>

<input type='radio' name='victory' value='$getuser3[opp_level]' checked>

<i>Resuming battle ... (<span id='victory'> </span>)</i>
</input>
</label>
</form>
";
?>

<script>

var milisec= 0;
var seconds=4;

document.getElementById("victory").innerHTML ='4';
victorious() ;

function victorious(){
if (milisec<=0){
milisec=9;
seconds-=1;
}
if (seconds<=-1){
milisec=0;
seconds+=1;
}
else
{
milisec-=1;
document.getElementById("victory").innerHTML =seconds;
setTimeout("victorious()",100);
}
if(document.getElementById("victory").innerHTML == '0')
{
document.getElementById("victorious").submit();
}
}
</script>

<?php
print "</form>";
}
</code>```

答:
I fixed my issues with the following code.

```<code><script type="text/javascript">

window.onload=function(){
window.setTimeout('document.victorious.submit()', 4000)
  }
</script>
</code>```

As I suspected my form submit scripts were interfering with each other, this fixed it right up.

Body:
I am making a text-based online game, in my game, there is a battle system. After defeating the enemy you can be awarded a badge if you do not already have said badge. However, for some strange reason that I can not wrap my head around, the badge is added to the database as it should be (if the table row for the badge does not exist on the MySQL database) but the text that should accompany earning the badge shows up sometimes. I would say the echo shows 50% of the time or less. Here is my code:

$gettrainerbadge = mysqli_query($conn, "SELECT * FROM t_badges where
badge='$badge' AND trainer='$getuser3[username]'");
$gettrainerbadge2 = mysqli_fetch_assoc($gettrainerbadge);

if(!$gettrainerbadge2)
{
    //This echo shows up maybe 50% of the time the form is submitted.

    echo "

By defeating $getuser3[battle_trainer] you have also earned a(n) $get_gym_leader3[badge] Badge!";

    //This INSERT works as expected when the badge doesn't exist it adds the badge to the database if the badge already exists it does nothing

    $addbadge = "INSERT INTO t_badges (`trainer`, `badge`) VALUES ('$getuser3[username]', '$get_gym_leader3[badge]')";
    mysqli_query($conn, $addbadge);

}

As I've said the echo statement works half the time, it should work every time and I can not figure out why the badge is being added but the text that accompanies it doesn't show. Any help is appreciated.

After playing with the code some more I've noticed that sometimes I can see a VERY fast flash of the page with the image of the badge, so I don't think the above code is to blame. I think it has to do with the following scripts I am using to submit the forms automatically without user feedback. I don't know why they would interfere with each other, but I'm almost certain that there is a double post submission going on somewhere. If anyone could help point out what I might be doing wrong here I would appreciate it.

if($get_remaining_opponents3 > '0')
{

print "<form action='index.php?action=battle' method='POST'
name='attackselect' id='attackselect' style='margin: 0px;'>

<input type='radio' name='continue' value='continue' checked>

Resuming battle ... ( )
</input>

</form>
";
?>

<?php
print "</form>";
}
else
{

print "<form action='index.php?action=battle' method='POST' name='victory'
id='victorious' style='margin: 0px;'>

<input type='radio' name='victory' value='$getuser3[opp_level]' checked>

Resuming battle ... ( )
</input>

</form>
";
?>

<?php
print "</form>";
}

Body:
I fixed my issues with the following code.

<script type="text/javascript">

window.onload=function(){
window.setTimeout('document.victorious.submit()', 4000)
  }
</script>

As I suspected my form submit scripts were interfering with each other, this fixed it right up.


问:
Reactjs: Unhandled Rejection (TypeError): Cannot read property 'map' of undefined
Whats wrong with my code?

```<code>import React, { Component } from "react";
// import {connect} from 'react-redux';
// import List_items from './list_items';

// @connect(item => ({data: state.example.data}))
class Home extends React.Component {

  constructor(){
    super();
    this.state = {
      dataOperations: [],
    };
  }

  componentDidMount(){

    fetch('http://127.0.0.1:8000/Selectallbarang/?format=json')
   .then(results => {
    return results.json();
      }).then(data => {
          let dataOperations = data.results.map((idk) => {
            return(
              <h1 key={idk.results}>

              {idk.harga_satuan}

              </h1>
              )
          })
         this.setState({dataOperations: dataOperations});
         console.log("state", this.state.id);
        })
      }
</code>```

I get the error code like below

Unhandled Rejection (TypeError): Cannot read property 'map' of undefined
(anonymous function)

```<code>C:/Users/kurniawan/django/shemura/frontend/src/home/Home.js:23
  20 |   .then(results => {
  21 |    return results.json();
  22 |      }).then(data => {
> 23 |          let dataOperations = data.results.map((idk) => {
  24 |            return(
  25 |              <h1 key={idk.results}>
  26 |
</code>```

View compiled
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.

答:
Replace data.results.map by (data.results || []).map

Because this error means data.results is undefined, then data.results.map is property (method) cannot be read from that undefined.

There are many ways to handle that, however, I assume I gave you the most elegant way.

Body:
Whats wrong with my code?

import React, { Component } from "react";
// import {connect} from 'react-redux';
// import List_items from './list_items';

// @connect(item => ({data: state.example.data}))
class Home extends React.Component {

  constructor(){
    super();
    this.state = {
      dataOperations: [],
    };
  }

  componentDidMount(){

    fetch('http://127.0.0.1:8000/Selectallbarang/?format=json')
   .then(results => {
    return results.json();
      }).then(data => {
          let dataOperations = data.results.map((idk) => {
            return(

              {idk.harga_satuan}

              )
          })
         this.setState({dataOperations: dataOperations});
         console.log("state", this.state.id);
        })
      }

I get the error code like below

Unhandled Rejection (TypeError): Cannot read property 'map' of undefined
(anonymous function)

C:/Users/kurniawan/django/shemura/frontend/src/home/Home.js:23
  20 |   .then(results => {
  21 |    return results.json();
  22 |      }).then(data => {
> 23 |          let dataOperations = data.results.map((idk) => {
  24 |            return(
  25 |

  26 |

View compiled
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.


问:
How can I refer to the nth area in a non-contigious Excel range?
Assume I selected the range A1:B2,C3:C5.

Using VBA, I can loop through each area like this:

```<code>Dim iArea As Range
For Each iArea In Application.Selection.Areas
    Debug.Print iArea.Address
Next iArea
</code>```

I am able to return each range's address, in this case $A$1:$B$2 and $C$3:$C$5.

How can I refer to the 2nd area in a range, or better yet, the nth area?  I can refer to the nth cell in a range using Range.Cells(cellNumberToReturn).  Is something similar for ranges?

答:
Just use indexer:</p>

```<code>Sub F()

    Dim rng As Range
    Dim rngArea As Range

    Set rng = Range("A1:B2,D3:E5")
    Set rngArea = rng.Areas(2)
    MsgBox rngArea.Address(0, 0) 'Shows D3:E5

End Sub
</code>```

Body:
Assume I selected the range A1:B2,C3:C5.

Using VBA, I can loop through each area like this:

Dim iArea As Range
For Each iArea In Application.Selection.Areas
    Debug.Print iArea.Address
Next iArea

I am able to return each range's address, in this case $A$1:$B$2 and $C$3:$C$5.

How can I refer to the 2nd area in a range, or better yet, the nth area?  I can refer to the nth cell in a range using Range.Cells(cellNumberToReturn).  Is something similar for ranges?

Body:
Just use indexer:

Sub F()

    Dim rng As Range
    Dim rngArea As Range

    Set rng = Range("A1:B2,D3:E5")
    Set rngArea = rng.Areas(2)
    MsgBox rngArea.Address(0, 0) 'Shows D3:E5

End Sub


问:
How to use netcat as compressing proxy
I have a server that receives messages in a text-based protocol. The server doesn't send back anything. These messages eat up network bandwidth a lot since the protocol is not binary and doesn't have any compression. To fix this I want to run a compressing proxy on the client and on the server side. On the client side, the proxy should receive the data over TCP, compress it, and send to the server-side proxy. The server-side proxy should receive data, decompress it, and send to the server application.

The client-side code should be something like this:

```<code>cd /tmp
mknod backpipe p
nc localhost 7171 0<backpipe | gzip | nc server-ip 7272 | tee backpipe
</code>```

And on the server side:

```<code>cd /tmp
mknod backpipe p
nc -l -p 7272 0<backpipe | gunzip | nc -l -p 7171 | tee backpipe
</code>```

The server application works on 7171 port and the compressing proxy uses the 7272 port to transfer data. But this is not working for me for some reason.

答:
You have almost got there.

client side, listen on local port 7171, forward to remote server at server-ip:7272:

```<code>mkfifo client_rely
nc -l 7171 < client_rely | gzip -c | nc server-ip 7272 > client_rely
</code>```

server side, listen on port 7272, forward to real server on port 7171:

```<code>mkfifo server_rely
nc -l 7272 < server_rely | gzip -d -c | nc 7171 > server_rely
</code>```

note that this example uses nc shipped with macOS.

Title: How to use netcat as compressing proxy

Body:
I have a server that receives messages in a text-based protocol. The server doesn't send back anything. These messages eat up network bandwidth a lot since the protocol is not binary and doesn't have any compression. To fix this I want to run a compressing proxy on the client and on the server side. On the client side, the proxy should receive the data over TCP, compress it, and send to the server-side proxy. The server-side proxy should receive data, decompress it, and send to the server application.

The client-side code should be something like this:

cd /tmp
mknod backpipe p
nc localhost 7171 0<backpipe | gzip | nc server-ip 7272 | tee backpipe

And on the server side:

cd /tmp
mknod backpipe p
nc -l -p 7272 0<backpipe | gunzip | nc -l -p 7171 | tee backpipe

The server application works on 7171 port and the compressing proxy uses the 7272 port to transfer data. But this is not working for me for some reason.

Body:
You have almost got there.

client side, listen on local port 7171, forward to remote server at server-ip:7272:

mkfifo client_rely
nc -l 7171 < client_rely | gzip -c | nc server-ip 7272 > client_rely

server side, listen on port 7272, forward to real server on port 7171:

mkfifo server_rely
nc -l 7272 < server_rely | gzip -d -c | nc 7171 > server_rely

note that this example uses nc shipped with macOS.


问:
load data from s3 to mySQL running EC2 instance (not RDS)
I want to able able to use the load data infile command in mySQL, but instead of loading the data from a local file I want to load it from a CSV file.

I.e., if the file is in local storage it'd look like:

```<code>LOAD DATA INFILE'C:\\abc.csv' INTO TABLE abc
</code>```

But if it's in S3, not sure how I could do something like this.

Is this possible?

NOTE: this is not an RDS machine, so this command does not seem to work:
http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-template-copys3tords.html

答:
The mysql CLI allows you to execute STDIN as a stream of SQL statements.

Using a combination of the s3 CLI and mkfifo, you can stream data out of s3.

Then it's a simple matter of connecting the streams with something that re-formats the CSV into valid SQL.

```<code>mkfifo /tmp/mypipe
s3 cp s3://your/s3/object /tmp/mypipe
python transform_csv_to_sql.py < /tmp/mypipe | mysql target_database
</code>```

You might be able to remove the python step and use MySQL's CSV code if you tell MySQL to load the data directly from your fifo:

```<code>mkfifo /tmp/mypipe
s3 cp s3://your/s3/object /tmp/mypipe
mysql target_database --execute "LOAD DATA INFILE '/tmp/mypipe'"
</code>```

Good luck!

Body:
I want to able able to use the load data infile command in mySQL, but instead of loading the data from a local file I want to load it from a CSV file.

I.e., if the file is in local storage it'd look like:

LOAD DATA INFILE'C:\\abc.csv' INTO TABLE abc

But if it's in S3, not sure how I could do something like this.

Is this possible?

NOTE: this is not an RDS machine, so this command does not seem to work:
http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-template-copys3tords.html

Body:
The mysql CLI allows you to execute STDIN as a stream of SQL statements.

Using a combination of the s3 CLI and mkfifo, you can stream data out of s3.

Then it's a simple matter of connecting the streams with something that re-formats the CSV into valid SQL.

mkfifo /tmp/mypipe
s3 cp s3://your/s3/object /tmp/mypipe
python transform_csv_to_sql.py < /tmp/mypipe | mysql target_database

You might be able to remove the python step and use MySQL's CSV code if you tell MySQL to load the data directly from your fifo:

mkfifo /tmp/mypipe
s3 cp s3://your/s3/object /tmp/mypipe
mysql target_database --execute "LOAD DATA INFILE '/tmp/mypipe'"

Good luck!


问:
Bridge for logging systems
I'am developing simple Java event library and I want to support more than one logging system.
I have an idea with using own class named LoggerBridge.

```<code>public void setLogger(LoggerBridge bridge){

}

public class LoggerBridge{

    public void log(Level, String){}

    ...

}
</code>```

But this solution is not practical at all, is there some other option how to achieve this result ?
Some bridge, which it supports all types of logging system ?

答:
This is an age old problem and several logging facades were made to allow you to log things in for example libraries, without forcing the user to use the same logging framework you chose (or try to make multiple logging frameworks work nicely together).

One of the earliest ones was commons-logging which is considered outdated these days, but there are a lot of older libraries that use it. It can be bridged to your actual logging system (see below).

Newer ones include SLF4J. These should be used when you're writing a library, so you'd be programming to the SLF4J API instead of an actual logging implementation.

A logging bridge is when you have a library that uses for example log4J, but your other code is using let's say SLF4J with Logback (a quite common combination). The bridge "fakes" being the log4J library, when it actually just redirects the logging to your SLF4J+Logback combination.

Title: Bridge for logging systems

Body:
I'am developing simple Java event library and I want to support more than one logging system.
I have an idea with using own class named LoggerBridge.

public void setLogger(LoggerBridge bridge){

}

public class LoggerBridge{

    public void log(Level, String){}

    ...

}

But this solution is not practical at all, is there some other option how to achieve this result ?
Some bridge, which it supports all types of logging system ?


问:
Using python regex with backreference matches
I have a doubt about regex with backreference.

I need to match strings, I try this regex (\w)\1{1,} to capture repeated values of my string, but this regex only capture consecutive repeated strings; I'm stuck to improve my regex to capture all repeated values, below some examples:

```<code>import re

str = 'capitals'

re.search(r'(\w)\1{1,}', str)
</code>```

Output None

```<code>import re

str = 'butterfly'

re.search(r'(\w)\1{1,}', str)
</code>```

<_sre.SRE_Match object; span=(2, 4), match='tt'>

答:
I would use r'(\w).*\1 so that it allows any repeated character even if there are special characters or spaces in between.

However this wont work for strings with repeated characters overlapping the contents of groups like the string abcdabcd, in which it only recognizes the first group, ignoring the other repeated characters enclosed in the first group (b,c,d)

Check the demo: https://regex101.com/r/m5UfAe/1

So an alternative (and depending on your needs) is to sort the string analyzed:

```<code>import re
str = 'abcdabcde'
re.findall(r'(\w).*\1', ''.join(sorted(str)))
</code>```

returning the array with the repeated characters ['a','b','c','d']

Body:
I have a doubt about regex with backreference.

I need to match strings, I try this regex (\w)\1{1,} to capture repeated values of my string, but this regex only capture consecutive repeated strings; I'm stuck to improve my regex to capture all repeated values, below some examples:

import re

str = 'capitals'

re.search(r'(\w)\1{1,}', str)

Output None

import re

str = 'butterfly'

re.search(r'(\w)\1{1,}', str)

<_sre.SRE_Match object; span=(2, 4), match='tt'>

Body:
I would use r'(\w).*\1 so that it allows any repeated character even if there are special characters or spaces in between.

However this wont work for strings with repeated characters overlapping the contents of groups like the string abcdabcd, in which it only recognizes the first group, ignoring the other repeated characters enclosed in the first group (b,c,d)

Check the demo: https://regex101.com/r/m5UfAe/1

So an alternative (and depending on your needs) is to sort the string analyzed:

import re
str = 'abcdabcde'
re.findall(r'(\w).*\1', ''.join(sorted(str)))

returning the array with the repeated characters ['a','b','c','d']


问:
BCrypt says long, similar passwords are equivalent - problem with me, the gem, or the field of cryptography?
I've been experimenting with BCrypt, and found the following. If it matters, I'm running ruby 1.9.2dev (2010-04-30 trunk 27557) [i686-linux]

```<code>require 'bcrypt' # bcrypt-ruby gem, version 2.1.2

@long_string_1 = 'f287ed6548e91475d06688b481ae8612fa060b2d402fdde8f79b7d0181d6a27d8feede46b833ecd9633b10824259ebac13b077efb7c24563fce0000670834215'
@long_string_2 = 'f6ebeea9b99bcae4340670360674482773a12fd5ef5e94c7db0a42800813d2587063b70660294736fded10217d80ce7d3b27c568a1237e2ca1fecbf40be5eab8'

def salted(string)
  @long_string_1 + string + @long_string_2
end

encrypted_password = BCrypt::Password.create(salted('password'), :cost => 10)
puts encrypted_password #=> $2a$10$kNMF/ku6VEAfLFEZKJ.ZC.zcMYUzvOQ6Dzi6ZX1UIVPUh5zr53yEu

password = BCrypt::Password.new(encrypted_password)

puts password.is_password?(salted('password')) #=> true
puts password.is_password?(salted('passward')) #=> true
puts password.is_password?(salted('75747373')) #=> true
puts password.is_password?(salted('passwor')) #=> false
</code>```

At first I thought that once the passwords got to a certain length, the dissimilarities would just be lost in all the hashing, and only if they were very dissimilar (i.e. a different length) would they be recognized as different. That didn't seem very plausible to me, from what I know of hash functions, but I didn't see a better explanation.

Then, I tried shortening each of the long_strings to see where BCrypt would start being able to tell them apart, and I found that if I shortened each of the long strings to 100 characters or so, the final attempt ('passwor') would start returning true as well. So now I don't know what to think.

What's the explanation for this?

答:
Blowfish's P-array is 18 4-byte integers long. BCrypt XORs this array by the password + null, then repeats the procedure until it gets to the end. Say my password was 12345, it would XOR the P-array by 12345(null)12345(null)12345(null), etc...

A full description of EksBlowfish is here. The short version is, BCrypt only uses the first 72 bytes.

ContentLicense: CC BY-SA 2.5

Body:
I've been experimenting with BCrypt, and found the following. If it matters, I'm running ruby 1.9.2dev (2010-04-30 trunk 27557) [i686-linux]

require 'bcrypt' # bcrypt-ruby gem, version 2.1.2

@long_string_1 = 'f287ed6548e91475d06688b481ae8612fa060b2d402fdde8f79b7d0181d6a27d8feede46b833ecd9633b10824259ebac13b077efb7c24563fce0000670834215'
@long_string_2 = 'f6ebeea9b99bcae4340670360674482773a12fd5ef5e94c7db0a42800813d2587063b70660294736fded10217d80ce7d3b27c568a1237e2ca1fecbf40be5eab8'

def salted(string)
  @long_string_1 + string + @long_string_2
end

encrypted_password = BCrypt::Password.create(salted('password'), :cost => 10)
puts encrypted_password #=> $2a$10$kNMF/ku6VEAfLFEZKJ.ZC.zcMYUzvOQ6Dzi6ZX1UIVPUh5zr53yEu

password = BCrypt::Password.new(encrypted_password)

puts password.is_password?(salted('password')) #=> true
puts password.is_password?(salted('passward')) #=> true
puts password.is_password?(salted('75747373')) #=> true
puts password.is_password?(salted('passwor')) #=> false

At first I thought that once the passwords got to a certain length, the dissimilarities would just be lost in all the hashing, and only if they were very dissimilar (i.e. a different length) would they be recognized as different. That didn't seem very plausible to me, from what I know of hash functions, but I didn't see a better explanation.

Then, I tried shortening each of the long_strings to see where BCrypt would start being able to tell them apart, and I found that if I shortened each of the long strings to 100 characters or so, the final attempt ('passwor') would start returning true as well. So now I don't know what to think.

What's the explanation for this?


问:
Setting the Highchart theme
I'm developing a .NET mvc based website in which I use the Highchart library for graphic representation. I successfully managed to build the Chart, however, the customization part takes too much space in the chart declaration + there is a lot of useless copy and paste, making my code unreadable. I have tried to move the "design" part in a separate file, I also tried to declare it only once in the file in which I'm constructing the charts, but with no success.

Is there a way, in which I can actually call the theme (defined in the Highchart/Js/Theme) folder? I tried with the setOption option, but failed again. (No matter what I've tried, my chart was undefined or the theme was inaccessible)

答: After trying something(just thought it could work this way,I managed to solve my problem).First off all you have to declare your theme in the Folder I specified,after that all you have to do is to provide the source of the script in your _Layout file.</p>

Title: Setting the Highchart theme


问:
XGBoost unreasonable splitting value in nodes
My xgboost model trained for a regression task in python using the xgboost package version 0.6 is using strange values for splits. Some values used as a splitting criteria are not present in the training dataset at all.

Example:

- there's a variable 'text' with values in the train set of [Missing,1,2]

- yet, a derived splitting criteria of a node in the trained model is 'text < 4'

What could be a possible reason of such a split when no such value (-> 4) can be found in the data set?The split does not increase the information gain, since all samples follow one branch after this decision node.

答: A possible explanation: you have all non-missing values going to the 'text < 4' branch, and all missing values to the other - 'text > 4' - branch. Can you verify?</p>


问:
How to break out of multiple if blocks inside while loop in java?
I wanted to break out of each if condition and make a validation for i,
Currently, what is happing is after all the if condition is verified only the only loop is getting considered, is there any logic to make the code validate after each if condition, The simple soltion is to add the (i<=10) in each of the if condition. is there any other alternative?</p>

```<code>code sample below
    while(i<=10){
      if(condition1){
          //action1
        }
      if(condition2){
          //action2
        }
      if(condition3){
          //action3
        }
      if(condition4){
          //action4
        }
      }
</code>```

答:
```<code><outerloop_name>:
while(i<=10){
      if(condition1){
          //action1
          break <outerloop_name>;
        }
      if(condition2){
          //action2
          break <outerloop_name>;
        }
      if(condition3){
          //action3
          break <outerloop_name>;
        }
      if(condition4){
          //action4
          break <outerloop_name>;
        }
      }
</code>```

Body:
I wanted to break out of each if condition and make a validation for i,
Currently, what is happing is after all the if condition is verified only the only loop is getting considered, is there any logic to make the code validate after each if condition, The simple soltion is to add the (i<=10) in each of the if condition. is there any other alternative?

code sample below
    while(i<=10){
      if(condition1){
          //action1
        }
      if(condition2){
          //action2
        }
      if(condition3){
          //action3
        }
      if(condition4){
          //action4
        }
      }


问:
how to Writing a static value returning method
it is not returning and wants something to return
whats wrong with it ?
why when i want to get return from this Boolean method it asks me for return
i have just set the returns in the body of method</p>

```<code>  public static Boolean winner(char[][] board) {
                if ((board[0][0] == board[0][1] && board[0][0] == board[0][2])
                        || (board[0][0] == board[1][1] && board[0][0] == board[2][2])
                        || (board[0][0] == board[1][0] && board[0][0] == board[2][0])
                        || (board[2][0] == board[2][1] && board[2][0] == board[2][2])
                        || (board[2][0] == board[1][1] && board[0][0] == board[0][2])
                        || (board[0][2] == board[1][2] && board[0][2] == board[2][2])
                        || (board[0][1] == board[1][1] && board[0][1] == board[2][1])
                        || (board[1][0] == board[1][1] && board[1][0] == board[1][2])) {
                    return true;
                } else if (true) {
                    for (int i = 0; i < board.length; i++) {
                        for (int j = 0; j < board[0].length; j++) {
                            if (board[i][j] == 'O' || board[i][j] == 'X') {
                                System.out.println("Game Over ");
                                return false;
                            }
                        }
                    }

                }

            }
</code>```

答: The else if(true) is unnecessary. You just returned if the big if was true. Beyond that, you only return second block when the if embedded inside two loops is true. You need to return something after the loops. </p>

Body:
it is not returning and wants something to return
whats wrong with it ?
why when i want to get return from this Boolean method it asks me for return
i have just set the returns in the body of method

  public static Boolean winner(char[][] board) {
                if ((board[0][0] == board[0][1] && board[0][0] == board[0][2])
                        || (board[0][0] == board[1][1] && board[0][0] == board[2][2])
                        || (board[0][0] == board[1][0] && board[0][0] == board[2][0])
                        || (board[2][0] == board[2][1] && board[2][0] == board[2][2])
                        || (board[2][0] == board[1][1] && board[0][0] == board[0][2])
                        || (board[0][2] == board[1][2] && board[0][2] == board[2][2])
                        || (board[0][1] == board[1][1] && board[0][1] == board[2][1])
                        || (board[1][0] == board[1][1] && board[1][0] == board[1][2])) {
                    return true;
                } else if (true) {
                    for (int i = 0; i < board.length; i++) {
                        for (int j = 0; j < board[0].length; j++) {
                            if (board[i][j] == 'O' || board[i][j] == 'X') {
                                System.out.println("Game Over ");
                                return false;
                            }
                        }
                    }

                }

            }


问:
Disconnect from Slick JNDI connection in Play for Scala
Slick defines here how to connect to a database using JNDI:

```<code>val db = Database.forName(jndiName: String)
</code>```

I use the above to connect to a database in Play for Scala, defining the JNDI connection in application.conf:

```<code>   def read (jndi: String, code: Int) = {
      val db = Database.forName(jndi)
      val records = TableQuery[TableDB]
      val action = records.filter(_.code === code).result
      val future = db.run(action.asTry)
      future.map{
        case Success(s) =>
          if (s.length>0)
            Some(s(0))
          else
            None
        case Failure(e) => throw new Exception ("Failure in read: " + e.getMessage)
      }
   }
</code>```

Question is: how to disconnect from the JNDI resource? Simply db.close() ? Is there a way to implicitly close the connection when the read method ends?

答:
It is not clear what make you doubt it. If you look at the source of forName, you may see that it just asks JNDI context to get object by the name you provided and then treat it as javax.sql.DataSource that can create connections. DataSource is not Closeable or anything like this so you don't have to explicitly release it. It is enough to just close the db.

As for closing  when the read method ends, this is probably not what you really want because you return Future that might still be not finished and thus might need the connection to be open. So what you probably need is Future.onComplete

```<code>  def read(jndi: String, code: Int) = {
    val records = TableQuery[TableDB]
    val action = records.filter(_.code === code).result
    val db = Database.forName(jndi)
    val future = db.run(action.asTry)
    future.onComplete(_ => db.close()) // <-- added line
    future.map {
      case Success(s) =>
        if (s.length > 0)
          Some(s(0))
        else
          None
      case Failure(e) => throw new Exception("Failure in read: " + e.getMessage)
    }
  }
</code>```

Body:
Slick defines here how to connect to a database using JNDI:

val db = Database.forName(jndiName: String)

I use the above to connect to a database in Play for Scala, defining the JNDI connection in application.conf:

   def read (jndi: String, code: Int) = {
      val db = Database.forName(jndi)
      val records = TableQuery[TableDB]
      val action = records.filter(_.code === code).result
      val future = db.run(action.asTry)
      future.map{
        case Success(s) =>
          if (s.length>0)
            Some(s(0))
          else
            None
        case Failure(e) => throw new Exception ("Failure in read: " + e.getMessage)
      }
   }

Question is: how to disconnect from the JNDI resource? Simply db.close() ? Is there a way to implicitly close the connection when the read method ends?

Body:
It is not clear what make you doubt it. If you look at the source of forName, you may see that it just asks JNDI context to get object by the name you provided and then treat it as javax.sql.DataSource that can create connections. DataSource is not Closeable or anything like this so you don't have to explicitly release it. It is enough to just close the db.

As for closing  when the read method ends, this is probably not what you really want because you return Future that might still be not finished and thus might need the connection to be open. So what you probably need is Future.onComplete

  def read(jndi: String, code: Int) = {
    val records = TableQuery[TableDB]
    val action = records.filter(_.code === code).result
    val db = Database.forName(jndi)
    val future = db.run(action.asTry)
    future.onComplete(_ => db.close()) // <-- added line
    future.map {
      case Success(s) =>
        if (s.length > 0)
          Some(s(0))
        else
          None
      case Failure(e) => throw new Exception("Failure in read: " + e.getMessage)
    }
  }


问:
Python Duplicate words
I have a question where I have to count the duplicate words in Python (v3.4.1) and put them in a sentence. I used counter but I don't know how to get the output in this following order. The input is:

```<code>mysentence = As far as the laws of mathematics refer to reality they are not certain as far as they are certain they do not refer to reality
</code>```

I made this into a list and sorted it

The output is suppose to be this

```<code>"As" is repeated 1 time.
"are" is repeated 2 times.
"as" is repeated 3 times.
"certain" is repeated 2 times.
"do" is repeated 1 time.
"far" is repeated 2 times.
"laws" is repeated 1 time.
"mathematics" is repeated 1 time.
"not" is repeated 2 times.
"of" is repeated 1 time.
"reality" is repeated 2 times.
"refer" is repeated 2 times.
"the" is repeated 1 time.
"they" is repeated 3 times.
"to" is repeated 2 times.
</code>```

I have come to this point so far

```<code>x=input ('Enter your sentence :')
y=x.split()
y.sort()
for y in sorted(y):
    print (y)
</code>```

答:
Hey i have tried it on python 2.7(mac) as i have that version so try to get hold of the logic

```<code>from collections import Counter

mysentence = """As far as the laws of mathematics refer to reality they are not certain as far as they are certain they do not refer to reality"""

mysentence = dict(Counter(mysentence.split()))
for i in sorted(mysentence.keys()):
    print ('"'+i+'" is repeated '+str(mysentence[i])+' time.')
</code>```

I hope this is what you are looking for if not then ping me up happy to learn something new.

```<code>"As" is repeated 1 time.
"are" is repeated 2 time.
"as" is repeated 3 time.
"certain" is repeated 2 time.
"do" is repeated 1 time.
"far" is repeated 2 time.
"laws" is repeated 1 time.
"mathematics" is repeated 1 time.
"not" is repeated 2 time.
"of" is repeated 1 time.
"reality" is repeated 2 time.
"refer" is repeated 2 time.
"the" is repeated 1 time.
"they" is repeated 3 time.
"to" is repeated 2 time.
</code>```

Title: Python Duplicate words

Body:
I have a question where I have to count the duplicate words in Python (v3.4.1) and put them in a sentence. I used counter but I don't know how to get the output in this following order. The input is:

mysentence = As far as the laws of mathematics refer to reality they are not certain as far as they are certain they do not refer to reality

I made this into a list and sorted it

The output is suppose to be this

"As" is repeated 1 time.
"are" is repeated 2 times.
"as" is repeated 3 times.
"certain" is repeated 2 times.
"do" is repeated 1 time.
"far" is repeated 2 times.
"laws" is repeated 1 time.
"mathematics" is repeated 1 time.
"not" is repeated 2 times.
"of" is repeated 1 time.
"reality" is repeated 2 times.
"refer" is repeated 2 times.
"the" is repeated 1 time.
"they" is repeated 3 times.
"to" is repeated 2 times.

I have come to this point so far

x=input ('Enter your sentence :')
y=x.split()
y.sort()
for y in sorted(y):
    print (y)

Body:
Hey i have tried it on python 2.7(mac) as i have that version so try to get hold of the logic

from collections import Counter

mysentence = """As far as the laws of mathematics refer to reality they are not certain as far as they are certain they do not refer to reality"""

mysentence = dict(Counter(mysentence.split()))
for i in sorted(mysentence.keys()):
    print ('"'+i+'" is repeated '+str(mysentence[i])+' time.')

I hope this is what you are looking for if not then ping me up happy to learn something new.

"As" is repeated 1 time.
"are" is repeated 2 time.
"as" is repeated 3 time.
"certain" is repeated 2 time.
"do" is repeated 1 time.
"far" is repeated 2 time.
"laws" is repeated 1 time.
"mathematics" is repeated 1 time.
"not" is repeated 2 time.
"of" is repeated 1 time.
"reality" is repeated 2 time.
"refer" is repeated 2 time.
"the" is repeated 1 time.
"they" is repeated 3 time.
"to" is repeated 2 time.


问:
Swift 4 save CBPeripherals array save state when returning to controller
So I am working with Bluetooth connections and I have an array of connected devices (some sensors). The problem in the devices is that, whenever there is something connected to that devices, CBCentralManager scanning doesnt find them (thats how they work). That's why I have to make an array of CBPeripherals that are connected an I want to display it in TableView where I display also not connected devices (the ones found while scanning).

Now, the problem is, whenever I put something into my connectedDevices:[CBPeripheral] array and I go back from my controller, and than return to it, the connectedDivecies array is empty. Thats absolutely normal and I understand it.

So the question is, how can I, in swift, store that array so whenever I return to that controller it holds same data, I mean - same CBPeripheral objects? I tried to do it with UserDefaults but nothing seems to work.

Please give me some ideas on how to manage that

答:
Just keep your devices list in the AppDelegate

then access it using something like

```<code>let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable
</code>```

Although there is a lot of discussion on whether to use App Delegate as A singleton for storing your objects.
IMHO storing an array of objects that's small won't harm your app anyway

Body:
Just keep your devices list in the AppDelegate

then access it using something like

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable

Although there is a lot of discussion on whether to use App Delegate as A singleton for storing your objects.
IMHO storing an array of objects that's small won't harm your app anyway


问:
Regex to change only number inside a div
I have this regex for now

```<code>/<div[^>]*>|(\d{1,9}\.\d{2})/
</code>```

which detect the opening of a
 and group the number in a currency format inside it.

If I have a string like this

```<code><div class="foo">Hello world 4546.00 and 6596.45 bla bla bla</div>
</code>```

I would like to only replace the numbers inside it with a preg_replace

As you can see in the example below, I don't want the number outside of the div to be selected, only ones inside.

https://regex101.com/r/AZd896/1/

答:
Brief

I'm not sure why you got downvoted so quickly, but I can only assume it's because of this question's topic and its relationship with regex match open tags except xhtml self contained tags.

By no means is this the best answer, but, in the scope of your question, it does solve your issue.

Code

See regex in use here

```<code>(?:<div[^>]*>|\G(?!\A))(?:(?!</div>).)*?\K\d{1,9}\.\d{2}
</code>```

If the
 tag might span multiple lines, you can add the s modifier to allow . to match newline characters as seen here.

Results

Input

```<code>dasdfasdf 355.56 asdfasd
<div class="sdaf">sdfsad 36546545643.00 asdfa sdf sadfasdf 544.45 sadfs</div>
dasdfasdf 355.56 asdfasd
</code>```

Output

```<code>dasdfasdf 355.56 asdfasd
<div class="sdaf">sdfsad 36 asdfa sdf sadfasdf  sadfs</div>
dasdfasdf 355.56 asdfasd
</code>```

Explanation

(?:
]*>|\G(?!\A)) Match either of the following

]*> Match the following

<div Match this literally

[^>]* Match any number of any character not present in the set (anything except >)

> Match this literally

\G(?!\A) Assert position at the end of the previous match

(?:(?!
).)*? Tempered greedy token matching any character any number of times, but as few as possible, and ensuring not to match

\K Resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match.

\d{1,9}\.\d{2} Match 1-9 digits, followed by a literal dot ., followed by exactly 2 digits

Body:
I have this regex for now

/
]*>|(\d{1,9}\.\d{2})/

which detect the opening of a
 and group the number in a currency format inside it.

If I have a string like this

Hello world 4546.00 and 6596.45 bla bla bla

I would like to only replace the numbers inside it with a preg_replace

As you can see in the example below, I don't want the number outside of the div to be selected, only ones inside.

https://regex101.com/r/AZd896/1/

Body:
Brief

I'm not sure why you got downvoted so quickly, but I can only assume it's because of this question's topic and its relationship with regex match open tags except xhtml self contained tags.

By no means is this the best answer, but, in the scope of your question, it does solve your issue.

Code

See regex in use here

(?:<div[^>]*>|\G(?!\A))(?:(?!</div>).)*?\K\d{1,9}\.\d{2}

If the <div> tag might span multiple lines, you can add the s modifier to allow . to match newline characters as seen here.

Results

Input

dasdfasdf 355.56 asdfasd
<div class="sdaf">sdfsad 36546545643.00 asdfa sdf sadfasdf 544.45 sadfs</div>
dasdfasdf 355.56 asdfasd

Output

dasdfasdf 355.56 asdfasd
<div class="sdaf">sdfsad 36 asdfa sdf sadfasdf  sadfs</div>
dasdfasdf 355.56 asdfasd

Explanation

(?:<div[^>]*>|\G(?!\A)) Match either of the following

<div[^>]*> Match the following

<div Match this literally

[^>]* Match any number of any character not present in the set (anything except >)

> Match this literally

\G(?!\A) Assert position at the end of the previous match

(?:(?!</div>).)*? Tempered greedy token matching any character any number of times, but as few as possible, and ensuring not to match </div>

\K Resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match.

\d{1,9}\.\d{2} Match 1-9 digits, followed by a literal dot ., followed by exactly 2 digits


问:
JS Add events to a List where rows are added dynamically

Hi,
I am inserting rows in a list dynamically. Right now that is happening on a click of button but eventually that data will come from a DB. That works fine!

What I want to do is that once the list is presented to a user, s/he will take the mouse over the desired list item. At that time the item should be highlighted.
So I want to add mouseover and mouseout event to each row.
But the event is triggered on the function declaration itself.
Please find the JSfiddle link here:
https://jsfiddle.net/indiaaditya/ycyb9dot/

The problem section is here::

```<code>function AddEventsToTableForEachRow(tableId) {
  //Get the NodeList
  alert("Function Called!");
  var nodelist = document.querySelectorAll(".classTableElement");
  var lclCntr = 0;
  alert("Elements found:" + nodelist.length);
  //Set ID's for all the elements
  var strInloop = "";
  //This loop sets the ID for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    nodelist[lclCntr].setAttribute("id", strInloop);
  }
  //This loop adds event for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    var rowElement = document.getElementById(strInloop);
    rowElement.addEventListener("onmouseover", alert("A"), false);
  }
}
</code>```

Explanation of JSFiddle code:

1. Click on Generate List button to add rows.

2. Click on GlowRecord Button to highlight the first row. Click it again to remove the highlight. This is the desired function on mouseover and mouseout.

3. Click on AddEvents to generate the events. This is the part of code that is not working

 AddEvents calls

    AddEventsToTableForEachRow('tblTestList')

function.
But this function immediately calls the alert function calls in it.

Expected result is that after calling AddEventsToTableForEachRow, the events should be attached to each row and when the mouse mover to the row, alert message should be shown.

In effect, as mentioned before the alert functions inside AddEventsToTableForEachRow are called immediately and no action on mouseover.

For those who question why I have not used jquery:
a. I am a complete novice to JS/HTML/CSS. I am from C/C++ background and have come to this side because of the ease of building the UI with HTML/CSS/JS.
b. I am learning on the fly and found DOM to be much cleaner and easier to understand.
But after spending 3 days on this issue I am ready for anything and everything. (But will be happier if I get DOM based solution!)

Thanks in advance.

Kind Regards,
Aditya

答:
As far as I understood your question. You want to accomplish something like this.

You first generate a row and add to the dom.

you want to attach "onmouseover" event and want to simply alert("A").

What you were doing wrong?

```<code>rowElement.addEventListener("onmouseover", alert("A"), false);
</code>```

You were doing everything good but the problem was in your above line of code. REMEMEBER you only use "on" with event names like "onmouseover" and "onclick" inside  like

. But when you use addEventListener method you omit the "on" from event names.

If you now change "onmouseover" to "mouseover" your code will still not run as you're expecting it to run. That's because you're calling the function directly in 2nd parameter of addEventListener whereas you need to pass a callback function. In your case you can simply pass an anonymous function like the line below:

```<code>rowElement.addEventListener("mouseover", function(){
    alert("A");
}, false);
</code>```

Now your script will work as expected. I hope my answer is helpful to you.
Have a look at this fiddle.

Body:
Hi,
I am inserting rows in a list dynamically. Right now that is happening on a click of button but eventually that data will come from a DB. That works fine!

What I want to do is that once the list is presented to a user, s/he will take the mouse over the desired list item. At that time the item should be highlighted.
So I want to add mouseover and mouseout event to each row.
But the event is triggered on the function declaration itself.
Please find the JSfiddle link here:
https://jsfiddle.net/indiaaditya/ycyb9dot/

The problem section is here::

function AddEventsToTableForEachRow(tableId) {
  //Get the NodeList
  alert("Function Called!");
  var nodelist = document.querySelectorAll(".classTableElement");
  var lclCntr = 0;
  alert("Elements found:" + nodelist.length);
  //Set ID's for all the elements
  var strInloop = "";
  //This loop sets the ID for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    nodelist[lclCntr].setAttribute("id", strInloop);
  }
  //This loop adds event for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    var rowElement = document.getElementById(strInloop);
    rowElement.addEventListener("onmouseover", alert("A"), false);
  }
}

Explanation of JSFiddle code:

1. Click on Generate List button to add rows.

2. Click on GlowRecord Button to highlight the first row. Click it again to remove the highlight. This is the desired function on mouseover and mouseout.

3. Click on AddEvents to generate the events. This is the part of code that is not working

 AddEvents calls

    AddEventsToTableForEachRow('tblTestList')

function.
But this function immediately calls the alert function calls in it.

Expected result is that after calling AddEventsToTableForEachRow, the events should be attached to each row and when the mouse mover to the row, alert message should be shown.

In effect, as mentioned before the alert functions inside AddEventsToTableForEachRow are called immediately and no action on mouseover.

For those who question why I have not used jquery:
a. I am a complete novice to JS/HTML/CSS. I am from C/C++ background and have come to this side because of the ease of building the UI with HTML/CSS/JS.
b. I am learning on the fly and found DOM to be much cleaner and easier to understand.
But after spending 3 days on this issue I am ready for anything and everything. (But will be happier if I get DOM based solution!)

Thanks in advance.

Kind Regards,
Aditya

Body:
As far as I understood your question. You want to accomplish something like this.

You first generate a row and add to the dom.

you want to attach "onmouseover" event and want to simply alert("A").

What you were doing wrong?

rowElement.addEventListener("onmouseover", alert("A"), false);

You were doing everything good but the problem was in your above line of code. REMEMEBER you only use "on" with event names like "onmouseover" and "onclick" inside  like <h1 onclick="doSomething()"></h1>. But when you use addEventListener method you omit the "on" from event names.

If you now change "onmouseover" to "mouseover" your code will still not run as you're expecting it to run. That's because you're calling the function directly in 2nd parameter of addEventListener whereas you need to pass a callback function. In your case you can simply pass an anonymous function like the line below:

rowElement.addEventListener("mouseover", function(){
    alert("A");
}, false);

Now your script will work as expected. I hope my answer is helpful to you.
Have a look at this fiddle.


问:
get CSS rule's percentage value in jQuery
Let's say the rule is as follows:

```<code>.largeField {
    width: 65%;
}
</code>```

Is there a way to get '65%' back somehow, and not the pixel value?

Thanks.

EDIT: Unfortunately using DOM methods is unreliable in my case, as I have a stylesheet which imports other stylesheets, and as a result the cssRules parameter ends up with either null or undefined value.

This approach, however, would work in most straightforward cases (one stylesheet, multiple separate stylesheet declarations inside the head tag of the document).

答:
Convert from pixels to percentage using cross multiplication.

Formula Setup:

1.)
(element_width_pixels/parent_width_pixels) = (element_width_percentage / 100)

2.) element_width_percentage =
(100 * element_width_pixels) / parent_width_pixels

The actual code:

```<code><script>

   var $width_percentage = (100 * $("#child").width()) / $("#parent").width();

</script>
</code>```

Body:
Let's say the rule is as follows:

.largeField {
    width: 65%;
}

Is there a way to get '65%' back somehow, and not the pixel value?

Thanks.

EDIT: Unfortunately using DOM methods is unreliable in my case, as I have a stylesheet which imports other stylesheets, and as a result the cssRules parameter ends up with either null or undefined value.

This approach, however, would work in most straightforward cases (one stylesheet, multiple separate stylesheet declarations inside the head tag of the document).

Body:
Convert from pixels to percentage using cross multiplication.

Formula Setup:

1.)
(element_width_pixels/parent_width_pixels) = (element_width_percentage / 100)

2.) element_width_percentage =
(100 * element_width_pixels) / parent_width_pixels

The actual code:

<script>

   var $width_percentage = (100 * $("#child").width()) / $("#parent").width();

</script>


问:
Search and get all child nodes of XML node base on attribute id
I have a sample XML like this:

```<code><doc>
    <customer id="1">
      <first>
        <fullname>John Doe 1</fullname>
        <contact>011-1111111</contact>
        <title>Lorem</title>
      </first>
      <second>
        <fullname>John Doe 2</fullname>
        <contact>012-2222222</contact>
        <title>Lorem</title>
      </second>
    </customer>
</doc>
</code>```

My question is how can I get all the child node inside first and second based on the customer id. So far this is what i have tried but i have no idea how to continue it.

```<code> XDocument doc = XDocument.Load("sampleXML.xml");
 var controls = from str in doc.Elements("customer")
                           where str.Attribute("id").Value == 1
                           select str;
</code>```

If I am able to get the data, how can i display the result? By using foreach loop? Sorry if this is a stupid question, but I am quite new to c# and linq.

答:
You can use XElement.Load("xmlPath") to load the xml and get all the customer elements the filter out based on the attribute. Loop through the each nodes and print.

```<code>        XElement xelement = XElement.Load("sampleXml.xml");
        var customers = xelement.Elements("customer").FirstOrDefault(x => x.Attribute("id").Value == "1");
        foreach (XElement customer in customers.Nodes())
        {
            var fullName = customer.Element("fullname").Value;
            var contact = customer.Element("contact").Value;
            var title = customer.Element("title").Value;
        }
</code>```

Body:
I have a sample XML like this:

<doc>
    <customer id="1">
      <first>
        <fullname>John Doe 1</fullname>
        <contact>011-1111111</contact>
        <title>Lorem</title>
      </first>
      <second>
        <fullname>John Doe 2</fullname>
        <contact>012-2222222</contact>
        <title>Lorem</title>
      </second>
    </customer>
</doc>

My question is how can I get all the child node inside first and second based on the customer id. So far this is what i have tried but i have no idea how to continue it.

 XDocument doc = XDocument.Load("sampleXML.xml");
 var controls = from str in doc.Elements("customer")
                           where str.Attribute("id").Value == 1
                           select str;

If I am able to get the data, how can i display the result? By using foreach loop? Sorry if this is a stupid question, but I am quite new to c# and linq.

Body:
You can use XElement.Load("xmlPath") to load the xml and get all the customer elements the filter out based on the attribute. Loop through the each nodes and print.

        XElement xelement = XElement.Load("sampleXml.xml");
        var customers = xelement.Elements("customer").FirstOrDefault(x => x.Attribute("id").Value == "1");
        foreach (XElement customer in customers.Nodes())
        {
            var fullName = customer.Element("fullname").Value;
            var contact = customer.Element("contact").Value;
            var title = customer.Element("title").Value;
        }


问:
Can a PHP class property be equal to another class property?
I want to do this:

```<code>class MyClass {
   var $array1 = array(3,4);
   var $array2 = self::$array1;
}
</code>```

and $array2 doesn't work.

Do you have a solution/trick to make a class property equal to another class property?

答:
Both your answers, Paolo and notruthless, are excellent, thank you very much!

If I want the two properties to keep in sync:

```<code>function MyClass() {
    $this->array2 = &$this->array1;
}
</code>```

If I want the two arrays to have identical values initially but then want to modify them individually, I remove the '&':

```<code>function MyClass() {
    $this->array2 = $this->array1;
}
</code>```

OwnerDisplayName: Stemar

LastEditorDisplayName: Stemar

Body:
I want to do this:

class MyClass {
   var $array1 = array(3,4);
   var $array2 = self::$array1;
}

and $array2 doesn't work.

Do you have a solution/trick to make a class property equal to another class property?

Body:
Both your answers, Paolo and notruthless, are excellent, thank you very much!

If I want the two properties to keep in sync:

function MyClass() {
    $this->array2 = &$this->array1;
}

If I want the two arrays to have identical values initially but then want to modify them individually, I remove the '&':

function MyClass() {
    $this->array2 = $this->array1;
}


问:
How to implement pause (and more) functionality?
My apologies beforehand for the length of the question, I didn't want to leave anything out.

Some background information

I'm trying to automate a data entry process by writing a Python application that uses the Windows API to simulate keystrokes, mouse movement and window/control manipulation. I have to resort to this method because I do not (yet) have the security clearance required to access the datastore/database directly (e.g. using SQL) or indirectly through a better suited API. Bureaucracy, it's a pain ;-)

The data entry process involves the correction of sales orders due to changes in article availability. The unavailable articles are either removed from the order or replaced by another suitable article.

Initially I want a human to be able to monitor the automatic data entry process to make sure everything goes right. To achieve this I slow down the actions on the one hand but also inform the user of what is currently going on through a pinned window.

The actual question

To allow the user to halt the automation process I'm registering the Pause/Break key as a hotkey and in the handler I want to pause the automation functionality. However, I'm currently struggling to figure out a way to properly pause the execution of the automation functionality. When the pause function is invoked I want the automation process to stop dead in its tracks, no matter what it is doing. I don't want it to even execute another keystroke.

UPDATE [23/01]: I actually want to do more than just pause, I want to be able to communicate with the automation process while it is running and request it to pause, skip the current sales order, give up completely and perhaps even more.

Can anybody show me The Right Way (TM) to achieve what I want?

Some more information

Here's an example of how the automation works (I'm using the pywinauto library):

```<code>from pywinauto import application
app = application.Application()
app.start_("notepad")
app.Notepad.TypeKeys("abcdef")
</code>```

UPDATE [25/01]: After a few days of working on my application I've noticed I don't really use pywinauto that much, right now I'm only using it for finding window and then I directly use SendKeysCtypes.SendKeys to simulate keyboard input and win32api functions to simulate mouse input.

What I've found out so far

Here are a few methods I've come across so far in my search for an answer:

I could separate the automation functionality and the interface + hotkey listener in two separate processes. Let's refer to the former as "automator" and the latter as "manager". The manager can then pause the execution of the automator by sending the process a SIGSTOP signal and unpause it using the SIGCONT signal (or the Windows equivalents through SuspendThread/ResumeThread).

To be able to update the user interface the automator will need to inform the manager of its progression through some sort of an IPC mechanism.

Cons:

Would using SIGSTOP not be a little harsh? Would it even work properly? Lots of people seem to be advising against it and even calling it "dangerous".

I am worried that implementing the IPC mechanism is going to be a bit complicated. On the other hand, I have worked with DBus which wouldn't be too hard to implement.

The second method and one that lots of people seem to be suggesting involves using threads and essentially boils down to the following (simplified):

```<code>while True:
    if self.pause: # pause
    # Do the work...
</code>```

However, doing it this way it seems it will only pause after there is no more work to do. The only way I see this method would work would be to divide the work (the entire automation process) into smaller work segments (i.e. tasks). Before starting on a new task the worker thread would check if it should pause and wait.

Cons:

Seems like an implementation to divide the work into smaller segments, such as the one above, would be very ugly code wise (aesthetically).

The way I imagine it, all statements would be transformed to look something like: queue.put((function, args)) (e.g. queue.put((app.Notepad.TypeKeys, "abcdef"))) and you'd have the automating process thread running through the tasks and continuously checking for the pause state before starting a task. That just can't be right...

The program would not actually stop dead in its tracks, but would first finish a task (however small) before actually pausing.

Progress made

UPDATE [23/01]: I've implemented a version of my application using the first method through the mentioned SuspendThread/ResumeThread functionality. So far this seems to work very nicely and also allows me to write the automation stuff just like you'd write any other script. The only quirk I've come across is that keyboard modifiers (CTRL, ALT, SHIFT) get "stuck" while paused. Something I can probably easily work around.

I've also written a test using the second method (threads and signals/message passing) and implemented the pause functionality. However, it looks really ugly (both checking for the pause flag and everything related to the "doing the work"). So if anybody can show me a proper example of something similar to the second method I'd appreciate it.

Related questions

Pausing a process?

Pausing a thread using threading class

Alex Martelli posted an answer saying:

There is no method for other threads to forcibly pause a thread (any more than there is for other threads to kill that thread) -- the target thread must cooperate by occasionally checking appropriate "flags" (a threading.Condition might be appropriate for the pause/unpause case).

He then referred to the multiprocessing module and SIGSTOP/SIGCONT.

Is there a way to indefinitely pause a thread?

Pausing a process in Windows

An answer to this question quotes the MSDN documentation regarding SuspendThread:

This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself. The target thread must be designed to watch for this signal and respond appropriately.

Is there any way to kill a Thread in Python?

How do I pass an exception between threads in python

答:
Keep in mind that although in your level of abstraction, "executing a keystroke" is a single atomic operation, it's implemented on the machine as a rather complicated sequence of machine instructions. So, pausing a thread at arbitrary points could lead to things being in an indeterminate state. Sending SIGSTOP is the same level of dangerous as pausing a thread at an arbitrary point. Depending on where you are in a particular step, though, your automation could potentially be broken. For example, if you pause in the middle of a timing-dependent step.

It seems to me that this problem would be best solved at the level of the automation library. I'm not very familiar with the automation library that you're using. It might be worth contacting the developers of the library to see if they have any suggestions for pausing the execution of automation steps at safe sub-step levels.

Body:
My apologies beforehand for the length of the question, I didn't want to leave anything out.

Some background information

I'm trying to automate a data entry process by writing a Python application that uses the Windows API to simulate keystrokes, mouse movement and window/control manipulation. I have to resort to this method because I do not (yet) have the security clearance required to access the datastore/database directly (e.g. using SQL) or indirectly through a better suited API. Bureaucracy, it's a pain ;-)

The data entry process involves the correction of sales orders due to changes in article availability. The unavailable articles are either removed from the order or replaced by another suitable article.

Initially I want a human to be able to monitor the automatic data entry process to make sure everything goes right. To achieve this I slow down the actions on the one hand but also inform the user of what is currently going on through a pinned window.

The actual question

To allow the user to halt the automation process I'm registering the Pause/Break key as a hotkey and in the handler I want to pause the automation functionality. However, I'm currently struggling to figure out a way to properly pause the execution of the automation functionality. When the pause function is invoked I want the automation process to stop dead in its tracks, no matter what it is doing. I don't want it to even execute another keystroke.

UPDATE [23/01]: I actually want to do more than just pause, I want to be able to communicate with the automation process while it is running and request it to pause, skip the current sales order, give up completely and perhaps even more.

Can anybody show me The Right Way (TM) to achieve what I want?

Some more information

Here's an example of how the automation works (I'm using the pywinauto library):

from pywinauto import application
app = application.Application()
app.start_("notepad")
app.Notepad.TypeKeys("abcdef")

UPDATE [25/01]: After a few days of working on my application I've noticed I don't really use pywinauto that much, right now I'm only using it for finding window and then I directly use SendKeysCtypes.SendKeys to simulate keyboard input and win32api functions to simulate mouse input.

What I've found out so far

Here are a few methods I've come across so far in my search for an answer:

I could separate the automation functionality and the interface + hotkey listener in two separate processes. Let's refer to the former as "automator" and the latter as "manager". The manager can then pause the execution of the automator by sending the process a SIGSTOP signal and unpause it using the SIGCONT signal (or the Windows equivalents through SuspendThread/ResumeThread).

To be able to update the user interface the automator will need to inform the manager of its progression through some sort of an IPC mechanism.

Cons:

Would using SIGSTOP not be a little harsh? Would it even work properly? Lots of people seem to be advising against it and even calling it "dangerous".

I am worried that implementing the IPC mechanism is going to be a bit complicated. On the other hand, I have worked with DBus which wouldn't be too hard to implement.

The second method and one that lots of people seem to be suggesting involves using threads and essentially boils down to the following (simplified):

while True:
    if self.pause: # pause
    # Do the work...

However, doing it this way it seems it will only pause after there is no more work to do. The only way I see this method would work would be to divide the work (the entire automation process) into smaller work segments (i.e. tasks). Before starting on a new task the worker thread would check if it should pause and wait.

Cons:

Seems like an implementation to divide the work into smaller segments, such as the one above, would be very ugly code wise (aesthetically).

The way I imagine it, all statements would be transformed to look something like: queue.put((function, args)) (e.g. queue.put((app.Notepad.TypeKeys, "abcdef"))) and you'd have the automating process thread running through the tasks and continuously checking for the pause state before starting a task. That just can't be right...

The program would not actually stop dead in its tracks, but would first finish a task (however small) before actually pausing.

Progress made

UPDATE [23/01]: I've implemented a version of my application using the first method through the mentioned SuspendThread/ResumeThread functionality. So far this seems to work very nicely and also allows me to write the automation stuff just like you'd write any other script. The only quirk I've come across is that keyboard modifiers (CTRL, ALT, SHIFT) get "stuck" while paused. Something I can probably easily work around.

I've also written a test using the second method (threads and signals/message passing) and implemented the pause functionality. However, it looks really ugly (both checking for the pause flag and everything related to the "doing the work"). So if anybody can show me a proper example of something similar to the second method I'd appreciate it.

Related questions

Pausing a process?

Pausing a thread using threading class

Alex Martelli posted an answer saying:

There is no method for other threads to forcibly pause a thread (any more than there is for other threads to kill that thread) -- the target thread must cooperate by occasionally checking appropriate "flags" (a threading.Condition might be appropriate for the pause/unpause case).

He then referred to the multiprocessing module and SIGSTOP/SIGCONT.

Is there a way to indefinitely pause a thread?

Pausing a process in Windows

An answer to this question quotes the MSDN documentation regarding SuspendThread:

This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself. The target thread must be designed to watch for this signal and respond appropriately.

Is there any way to kill a Thread in Python?

How do I pass an exception between threads in python