问:
Getting Firebase Listview position
I have a User class for populate a listview. This is the way i create User node

```<code>        currentUser= FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference usersDatabase= FirebaseDatabase.getInstance().getReference("Users");
    usersDatabase.keepSynced(true);
    User users= new User(FirebaseAuth.getInstance().getCurrentUser().getDisplayName());
    String key = currentUser;
    usersDatabase.child(key).setValue(users);
</code>```

All works good... until i want to work with values retrieved from this listview. I set up a way for long click items of listview for get the value, but it doesn't work.

```<code>@Override
        public void onItemCheckedStateChanged(ActionMode mode, int position,
                                              long id, boolean checked) {
            adminToAdd = new ArrayList<>();
            if (checked) {
                adminToAdd.add(uAdapter.getItem(position));
            } else {
                adminToAdd.remove(uAdapter.getItem(position));
            }
            uAdapter.notifyDataSetChanged();

            int checkedItems = listView.getCheckedItemCount();
            if (checkedItems==1){
                mode.setTitle(String.valueOf(checkedItems) + getString(R.string.selected));
            } else {
                mode.setTitle(String.valueOf(checkedItems) + getString(R.string.more_selected));
            }

        }
    });
    uAdapter= new UsersAdapter(this, User.class, R.layout.one_user, FirebaseDatabase.getInstance().getReference("Users"));
    listView.setAdapter(uAdapter);

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int position, long arg3) {
            selectedPosition = position;
            final ListView list = (ListView) arg0;
            list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            list.setItemChecked(position, true);
            return true;
        }
    });
</code>```

I was supposing that with this code i can take position for each values of adminToAdd ArrayList. Then, i use it for set another database child called "Admins". The way:

```<code>@Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem menuItem) {
            // TODO Auto-generated method stub
            switch (menuItem.getItemId()) {
                case R.id.menu_admin_add:

                    for (User newAdmin : adminToAdd) {
                        DatabaseReference admin_node= FirebaseDatabase.getInstance().getReference().getRoot().child("Admins");
                        admin_node.push().setValue(idAdminToAdd);
                        Toast.makeText(UsersList.this,getString(R.string.admin_added),Toast.LENGTH_LONG).show();
                    }
                    uAdapter.notifyDataSetChanged();
                    mode.finish();
            }
            return false;
        }
</code>```

No way, i can selelect whatever element of the listview, but i get always the first one. Any help will be appreciated.

Update: This is the Listener i use for get the idAdminToAdd value:

```<code>DatabaseReference adminDatabase = FirebaseDatabase.getInstance().getReference().getRoot().child("Users");
    adminDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                idAdminToAdd = childSnapshot.getKey();
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
</code>```

答:
To get the value of the element of ListView on which the user has clicked you need to use the following line of code:</p>

```<code>String s = (String) arg0.getItemAtPosition(position);
Log("TAG", s);
</code>```

Title: Getting Firebase Listview position

Body:
I have a User class for populate a listview. This is the way i create User node

        currentUser= FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference usersDatabase= FirebaseDatabase.getInstance().getReference("Users");
    usersDatabase.keepSynced(true);
    User users= new User(FirebaseAuth.getInstance().getCurrentUser().getDisplayName());
    String key = currentUser;
    usersDatabase.child(key).setValue(users);

All works good... until i want to work with values retrieved from this listview. I set up a way for long click items of listview for get the value, but it doesn't work.

@Override
        public void onItemCheckedStateChanged(ActionMode mode, int position,
                                              long id, boolean checked) {
            adminToAdd = new ArrayList<>();
            if (checked) {
                adminToAdd.add(uAdapter.getItem(position));
            } else {
                adminToAdd.remove(uAdapter.getItem(position));
            }
            uAdapter.notifyDataSetChanged();

            int checkedItems = listView.getCheckedItemCount();
            if (checkedItems==1){
                mode.setTitle(String.valueOf(checkedItems) + getString(R.string.selected));
            } else {
                mode.setTitle(String.valueOf(checkedItems) + getString(R.string.more_selected));
            }

        }
    });
    uAdapter= new UsersAdapter(this, User.class, R.layout.one_user, FirebaseDatabase.getInstance().getReference("Users"));
    listView.setAdapter(uAdapter);

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int position, long arg3) {
            selectedPosition = position;
            final ListView list = (ListView) arg0;
            list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            list.setItemChecked(position, true);
            return true;
        }
    });

I was supposing that with this code i can take position for each values of adminToAdd ArrayList. Then, i use it for set another database child called "Admins". The way:

@Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem menuItem) {
            // TODO Auto-generated method stub
            switch (menuItem.getItemId()) {
                case R.id.menu_admin_add:

                    for (User newAdmin : adminToAdd) {
                        DatabaseReference admin_node= FirebaseDatabase.getInstance().getReference().getRoot().child("Admins");
                        admin_node.push().setValue(idAdminToAdd);
                        Toast.makeText(UsersList.this,getString(R.string.admin_added),Toast.LENGTH_LONG).show();
                    }
                    uAdapter.notifyDataSetChanged();
                    mode.finish();
            }
            return false;
        }

No way, i can selelect whatever element of the listview, but i get always the first one. Any help will be appreciated.

Update: This is the Listener i use for get the idAdminToAdd value:

DatabaseReference adminDatabase = FirebaseDatabase.getInstance().getReference().getRoot().child("Users");
    adminDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                idAdminToAdd = childSnapshot.getKey();
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

Body:
To get the value of the element of ListView on which the user has clicked you need to use the following line of code:

String s = (String) arg0.getItemAtPosition(position);
Log("TAG", s);


来源: stackexchange

问:
Look for a pattern of number in different column of a matrix in MATLAB
I need help for the following task: how can I write a MATLAB code that compares, two by two, the odd and the even columns of a matrix, looking for two different patterns of numbers, respectively one for the even and one for the odd.
I want the code to report in which column (for each pair) the pattern appears first.

For example: I have the following matrix

```<code>A = [0 1 0 1 0 0
     1 0 1 0 1 1
     0 0 0 0 0 0
     0 1 0 1 0 1
     0 0 1 0 0 0]
</code>```

I want to look for two patterns, say: 100 (in the odd column of each pair of columns) and 010 (in the even columns of each pair of columns). Then, I want to report for each of the three pairs of columns if it appears first 100 in the odd or 010 in the even.

In the example we have:

odd(for columns 1,2 -> 100 appear first),

odd(for columns 3,4 -> 100 appear first),

even(for columns 5,6 -> 010 appear first)

答:
First, let's define the matrix [mxn] and two patterns:

```<code>A = randi([0 1],50,100);
[m,n]=size(A);
pat=[0 1 0 0 1];
pat2=[1 0 0 1 0];
</code>```

Now, find the indices where the matrix contain these patterns. We will omit indices in the last lines because it's a pattern that continue in different columns, and we will omit the odd\even columns, for first\second pattern, respectively:

```<code>B=strfind(A(:).',pat);
B(mod(B,m)==0 | mod(B,m)>(m-length(pat)+1) | mod(B,2*m)<=m)=[];
C=strfind(A(:).',pat2);
C(mod(C,m)==0 | mod(C,m)>(m-length(pat2)+1) | mod(C,2*m)>m)=[];
</code>```

Now, for the case that there is more than one match in the same column (as in the last column in our case), we will remain only the first of each:

```<code>[un,ind]=unique(ceil(B/m));
B2=ones(1,ceil(n/2))*numel(A);
B2(ismember(2:2:n,un))=B(ind);
[un,ind]=unique(ceil(C/m));
C2=ones(1,ceil(n/2))*numel(A);
C2(ismember(1:2:n,un))=C(ind);
</code>```

And, the result:

```<code>result=double((B2-m)>C2);
result(intersect(find(~B2),find(~C2)))=-1;
</code>```

The result will be a vector of 1 x (n/2), as the number of pairs of columns. while 1 represents the "win" of the odd column of each pair and 0 represents the "win" of the even column of each pair.

I generalized the code for the case that there is no pattern find in one of the columns. In this case, the second column of the pair is wins. In the case that both of the columns in the pair is lack its pattern, the result will be -1.

ContentLicense: CC BY-SA 3.0

Body:
I need help for the following task: how can I write a MATLAB code that compares, two by two, the odd and the even columns of a matrix, looking for two different patterns of numbers, respectively one for the even and one for the odd.
I want the code to report in which column (for each pair) the pattern appears first.

For example: I have the following matrix

A = [0 1 0 1 0 0
     1 0 1 0 1 1
     0 0 0 0 0 0
     0 1 0 1 0 1
     0 0 1 0 0 0]

I want to look for two patterns, say: 100 (in the odd column of each pair of columns) and 010 (in the even columns of each pair of columns). Then, I want to report for each of the three pairs of columns if it appears first 100 in the odd or 010 in the even.

In the example we have:

odd(for columns 1,2 -> 100 appear first),

odd(for columns 3,4 -> 100 appear first),

even(for columns 5,6 -> 010 appear first)

Body:
First, let's define the matrix [mxn] and two patterns:

A = randi([0 1],50,100);
[m,n]=size(A);
pat=[0 1 0 0 1];
pat2=[1 0 0 1 0];

Now, find the indices where the matrix contain these patterns. We will omit indices in the last lines because it's a pattern that continue in different columns, and we will omit the odd\even columns, for first\second pattern, respectively:

B=strfind(A(:).',pat);
B(mod(B,m)==0 | mod(B,m)>(m-length(pat)+1) | mod(B,2*m)<=m)=[];
C=strfind(A(:).',pat2);
C(mod(C,m)==0 | mod(C,m)>(m-length(pat2)+1) | mod(C,2*m)>m)=[];

Now, for the case that there is more than one match in the same column (as in the last column in our case), we will remain only the first of each:

[un,ind]=unique(ceil(B/m));
B2=ones(1,ceil(n/2))*numel(A);
B2(ismember(2:2:n,un))=B(ind);
[un,ind]=unique(ceil(C/m));
C2=ones(1,ceil(n/2))*numel(A);
C2(ismember(1:2:n,un))=C(ind);

And, the result:

result=double((B2-m)>C2);
result(intersect(find(~B2),find(~C2)))=-1;

The result will be a vector of 1 x (n/2), as the number of pairs of columns. while 1 represents the "win" of the odd column of each pair and 0 represents the "win" of the even column of each pair.

I generalized the code for the case that there is no pattern find in one of the columns. In this case, the second column of the pair is wins. In the case that both of the columns in the pair is lack its pattern, the result will be -1.


问:
Changing port on Apache doesn't work (using IZ-WAMP)
I'm using IZ-WAMP https://sourceforge.net/projects/iz-wamp/ for PHP/Wordpress locally.

In their tray menu, on can access to httpd.conf

I changed port to 80 with

Define IZ_WAMP_HTTP_PORT   "80"

But after restarting Apache, localhost doesn't work anymore.

Update after answer: I can't see any port 80 used by any app, and for httpd.exe I can only see "http" which is weird.

答:
Ok, the problem is solved, fine!

How to change IZ-WAMP Wordpress port 8080 to 80:

1-go to http://localhost:8080/wordpress to check it works fine

2-go to http://localhost:8080/adminer (or by de IZ-WAMP Menu "MySQL/Adminer")

3-select the "wordpress" database

4-change value:

```<code>update wp_options set optionvalue='http://localhost' where option_name='siteurl';
</code>```

5-change value:

```<code>update wp_options set optionvalue='http://localhost' where option_name='home';
</code>```

6-change in "httpd.conf" file (or by de IZ-WAMP Menu "Administration/Configuration Files")

```<code>[before] Define IZ_WAMP_HTTP_PORT   "8080"

[after]  Define IZ_WAMP_HTTP_PORT   "80"
</code>```

7-restart by the IZ-WAMP Menu "Restart All"

8-go to http://localhost/wordpress to check it works fine again

Body:
Ok, the problem is solved, fine!

How to change IZ-WAMP Wordpress port 8080 to 80:

1-go to http://localhost:8080/wordpress to check it works fine

2-go to http://localhost:8080/adminer (or by de IZ-WAMP Menu "MySQL/Adminer")

3-select the "wordpress" database

4-change value:

update wp_options set optionvalue='http://localhost' where option_name='siteurl';

5-change value:

update wp_options set optionvalue='http://localhost' where option_name='home';

6-change in "httpd.conf" file (or by de IZ-WAMP Menu "Administration/Configuration Files")

[before] Define IZ_WAMP_HTTP_PORT   "8080"

[after]  Define IZ_WAMP_HTTP_PORT   "80"

7-restart by the IZ-WAMP Menu "Restart All"

8-go to http://localhost/wordpress to check it works fine again


问:
Why are the list items from a JSON file coming back undefined jQuery?
So I have a dog name tool that is working as far as the pop up I'm using a separate json file to get the names populated into the list as list items. Here are the html and jquery that does this:

```<code><div class="dnt-container-mobile seasonal-bg-dark">
  <h1 class="mobile-heading">Dog Name Finder</h1>
  <h1 class="wide-heading">
    <!-- <span class="logo teal icon-akc-logo dnt-logo"></span> -->Dog Name Finder</h1>
  <form class="dnt-tool" id="dnt" name="dnt">
    <div class="dnt-overlay">
      <input id="male" name="gender" type="radio" value="Male" />
      <label for="male">Male</label>
      <input data-id="594" id="female" name="gender" type="radio" value="Female" />
      <label for="female">Female</label>
      <input checked="checked" data-id="0" id="all" name="gender" type="radio" value="All" />
      <label for="all">All</label>
      <select>
            <option data-id="0" value="/dog-name-finder/">Select a Category</option>
            <option data-id="0" value="/dog-name-finder/">All</option>
            <option value="/dog-name-finder/baby/">Baby</option>
            <option data-id="602" value="/dog-name-finder/celebrity/">Celebrity</option>
            <option data-id="603" value="/dog-name-finder/cute/">Cute</option>
            <option data-id="598" value="/dog-name-finder/disney/">Disney</option>
            <option data-id="600" value="/dog-name-finder/fancy/">Fancy</option>
            <option data-id="605" value="/dog-name-finder/most-popular/">Most Popular</option>
            <option data-id="599" value="/dog-name-finder/presidential/">Presidential</option>
            <option data-id="597" value="/dog-name-finder/techy/">Techy</option>
            <option data-id="596" value="/dog-name-finder/television/">Television</option>
            <option data-id="606" value="/dog-name-finder/trendy/">Trendy</option>
            <option data-id="595" value="/dog-name-finder/unisex/">Unisex</option>
            <option data-id="604" value="/dog-name-finder/video-game/">Video Game</option>
      </select>
    </div>
    <!-- end of dnt-overlay -->
    <div class="dnt-btn">
      <button id="submit" type="submit">Show Names</button>
    </div>
    <!-- end of dnt btn -->
  </form>
  <!-- end of dnt-tool -->
</div>
<!-- end of dnt-container-mobile -->
</code>```

Here is the jquery:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/0.9.9/jquery.magnific-popup.min.js"></script>
<script>
  $(document).ready(function() {
        $('#dnt').submit(function(e) {
          var cat_id = $('.dnt-overlay > select > option:selected').data('id') || 0;
          var cat_title = $('.dnt-overlay > select > option:selected').text() || 'All';
          if (cat_id === 0) {
            cat_title = 'All';
          }
          var dnt_url = $('.dnt-overlay > select > option:selected').val() || '/dog-name-finder/';
          var gender = $('.dnt-overlay > [name=gender]:checked').data('id') || 0;
          var gender_title = $('.dnt-overlay > [name=gender]:checked').val() || 'All';
          var title = cat_title;
          var html = '';

          var params = '';

          if (window.innerWidth <= 320) {
            params = '?limit=18';
          } else {
            params = '?limit=21';
          }

          if (cat_id > 0) {
            params += '&' + 'cat_id=' + cat_id;
          }

          if (gender > 0 && cat_title != 'Gender Agnostic' && cat_title != 'Unisex' && cat_title != 'Male' && cat_title != 'Female') {
            title += ' ' + gender_title;
            params += '&' + 'gender=' + gender;
            if (cat_title == 'All') {
              dnt_url += gender_title.toLowerCase() + '/';
            } else {
              dnt_url += '?gender=' + gender_title.charAt(0).toLowerCase();
            }
          }

          title += ' Dog Names';

          $('#dnt-popup > h1').text(title);
          $('#dnt-popup > .more-btn').find('a').attr('href', dnt_url);

          e.preventDefault(); // We don't need to send the form, because it's all local
          if ($('#male').is(':checked')) { // Check if male is checked
            $('#dnt-popup').removeClass('dnt-all').removeClass('dnt-female').addClass('dnt-male');
          } else if ($('#female').is(':checked')) { // Check if female is checked
            $('#dnt-popup').removeClass('dnt-all').removeClass('dnt-male').addClass('dnt-female');
          } else if ($('#all').is(':checked')) { // Check if all is checked
            $('#dnt-popup').removeClass('dnt-female').removeClass('dnt-male').addClass('dnt-all');
          }
          $.ajax({
              type: 'GET',
              dataType: "json",
              url: "/wp-content/themes/akc/dnt.json" + params,
            })

            .done(function(data) {

              $.each(data, function(index, value) {
                html += '<li>' + value.title + '</li>';
              });

              $('#dnt-popup > .results-list > ul').html(html);

              $.magnificPopup.open({ // open pop up for male
                items: {
                  src: '#dnt-popup',
                  type: 'inline'

                }, //item
                mainClass: 'animated slideInRight'
              }); ///popup open

            });

        }); ///submit function

        $('#dnt-popup > .more-btn > .long-btn > a, #dnt-popup > .more-btn > .short-btn > a').on("click", function() {

          var cat_id = $('.dnt-overlay > select > option:selected').data('id') || 0;
          var cat_title = $('.dnt-overlay > select > option:selected').text() || 'All';
          if (cat_id === 0) {
            cat_title = 'All';
          }

          var gender_title = $('.dnt-overlay > [name=gender]:checked').val() || 'All';

        }); ///submit function
</script>
</code>```

Here is some of the data in the json file:

```<code>[{
    "Name": "Aaliyah",
    "Female": 594,
    "Baby": 601
  },
  {
    "Name": "Abby",
    "Female": 594
  },
  {
    "Name": "Abe",
    "Male": 593,
    "Video Games": 604
  }
]
</code>```

Any reason the data would come back undefined? the json is formatted correctly. There's no console error messages.

答:
There is no key as title in your JSON. You have to use value.Name to acces names

var data = [{
    "Name": "Aaliyah",
    "Female": 594,
    "Baby": 601
  },
  {
    "Name": "Abby",
    "Female": 594
  },
  {
    "Name": "Abe",
    "Male": 593,
    "Video Games": 604
  }
];

$.each(data, function(index, value) {
 console.log(value.Name);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

If you want to limit the names to 21(asked in comment) then you can do it like this

```<code>$.each(data, function(index, value) {
 if(index==21){
  return false;
 }
 console.log(value.Name);
});
</code>```

Body:
So I have a dog name tool that is working as far as the pop up I'm using a separate json file to get the names populated into the list as list items. Here are the html and jquery that does this:

Dog Name Finder

    Dog Name Finder

  <form class="dnt-tool" id="dnt" name="dnt">

      <input id="male" name="gender" type="radio" value="Male" />
      Male
      <input data-id="594" id="female" name="gender" type="radio" value="Female" />
      Female
      <input checked="checked" data-id="0" id="all" name="gender" type="radio" value="All" />
      All
      <select>
            <option data-id="0" value="/dog-name-finder/">Select a Category</option>
            <option data-id="0" value="/dog-name-finder/">All</option>
            <option value="/dog-name-finder/baby/">Baby</option>
            <option data-id="602" value="/dog-name-finder/celebrity/">Celebrity</option>
            <option data-id="603" value="/dog-name-finder/cute/">Cute</option>
            <option data-id="598" value="/dog-name-finder/disney/">Disney</option>
            <option data-id="600" value="/dog-name-finder/fancy/">Fancy</option>
            <option data-id="605" value="/dog-name-finder/most-popular/">Most Popular</option>
            <option data-id="599" value="/dog-name-finder/presidential/">Presidential</option>
            <option data-id="597" value="/dog-name-finder/techy/">Techy</option>
            <option data-id="596" value="/dog-name-finder/television/">Television</option>
            <option data-id="606" value="/dog-name-finder/trendy/">Trendy</option>
            <option data-id="595" value="/dog-name-finder/unisex/">Unisex</option>
            <option data-id="604" value="/dog-name-finder/video-game/">Video Game</option>
      </select>

      <button id="submit" type="submit">Show Names</button>

  </form>

Here is the jquery:

Here is some of the data in the json file:

[{
    "Name": "Aaliyah",
    "Female": 594,
    "Baby": 601
  },
  {
    "Name": "Abby",
    "Female": 594
  },
  {
    "Name": "Abe",
    "Male": 593,
    "Video Games": 604
  }
]

Any reason the data would come back undefined? the json is formatted correctly. There's no console error messages.

Body:
There is no key as title in your JSON. You have to use value.Name to acces names

var data = [{
    "Name": "Aaliyah",
    "Female": 594,
    "Baby": 601
  },
  {
    "Name": "Abby",
    "Female": 594
  },
  {
    "Name": "Abe",
    "Male": 593,
    "Video Games": 604
  }
];

$.each(data, function(index, value) {
 console.log(value.Name);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you want to limit the names to 21(asked in comment) then you can do it like this

$.each(data, function(index, value) {
 if(index==21){
  return false;
 }
 console.log(value.Name);
});


问:
Upload file and call function to plot data in shiny app
I have a file containing a chat log:

```<code>24/01/2016, 11:50:17 pm: Line to skip
24/01/2016, 11:50:17 pm: Line to skip
25/01/2016, 11:51:47 pm: User1: Message one is here
25/01/2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and

can
[span]

Several lines.
24/01/2016, 11:51:47 pm: User3: My first message
27/10/2017, 12:54:03 am: +44 012 3456789 left
28/10/2017, 02:54:03 pm: User3: My second message!
</code>```

```<code>rawData <- structure(list(V1 = c("24 01 2016, 11:50:17 pm: Line to skip",
        "24 01 2016, 11:50:17 pm: Line to skip", "24 01 2016, 11:51:47 pm: User1: Message one is here",
        "24 01 2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and ",
        "can", "[span]", "Several lines.", "24 01 2016, 11:51:47 pm: User3: My first message",
        "27 10 2017, 12:54:03 am: +44 012 3456789 left")), .Names = "V1", row.names = c(NA,
        -9L), class = "data.frame")
</code>```

In my script, I have a function to parse the file, and another to plot the number of posts per user:

```<code># Parse the file:
parseR <- function(file='data/chatlog.txt',drop="44"){
  rawData <- read.delim(file, quote = "",
                  row.names = NULL,
                  stringsAsFactors = FALSE,
                  header = F)

  # join multi line messages into single line
  # rawData$V1<-gsub("[\r\n]", "Hello", rawData$V2)

  rawData$V1<-gsub("http", ' ', rawData$V1)
  # replace '/' with spaces
  rawData$V1<-gsub("/", " ", rawData$V1)

  sepData<-suppressWarnings(separate(rawData, V1, c("datetime", "sender", "message"), sep = ": ", extra = "merge"))

  sepData$message <- trimws(sepData$message)
  sepData$sender<-factor(sepData$sender)

  data <- sepData %>%
    filter(!is.na(message)) %>%
    filter(!grepl(drop, sender)) %>%
    droplevels()

  # data$date_time<-strsplit(data$date_time, '_')
  # data$datetime<-dmy_hms(data$datetime,tz=NULL)
  data$datetime<-dmy_hms(data$datetime, tz=NULL)

  cleanData<-separate(data, datetime, c("date", "time"), sep = " ", remove =TRUE)
  cleanData$date<-ymd(cleanData$date)
  cleanData$time<-hms(cleanData$time)

  return(cleanData)
}

# Plot the number of posts per user
senderPosts <- function(){
  data <- parseR()

  postCount<-as.data.frame(cbind(table(data$sender)))
  postCount <- data.frame(names = row.names(postCount), postCount)
  rownames(postCount)<-NULL
  colnames(postCount)<-c("name", "posts")

  postCount <- transform(postCount, name = reorder(name, -posts))

  # Plot bar
  p <- ggplot(postCount)
  p <- p + geom_bar(aes(name, posts),stat='identity')
  p <- p + scale_y_continuous("Number of posts", breaks=seq(0,max(postCount$posts),by=100))
  p <- p + cleanTheme()
  p

}
</code>```

I'm trying to make this toy example into a shiny web app. The accepted answer to this question has been super useful in getting me started and I can upload the file, but I'm not sure how to actually integrate my functions in sever.R. Should I develop my functions as a package, and then load then in sever.R, or can I pass the file I upload to my functions within the sever.R script itself?

Here's what I've got so far:

ui.R

```<code>library(shiny)

suppressMessages(library("wordcloud"))
shinyUI(fluidPage(
  titlePanel("Column Plot"),
  tabsetPanel(
    tabPanel("Upload File",
             titlePanel("Uploading Files"),
             sidebarLayout(
               sidebarPanel(
                 fileInput('file1', 'Choose CSV File',
                           accept='.txt'
                           ),

                 tags$br()

               ),
               mainPanel(
                 tableOutput('contents')
               )
             )
    )

  )
)
)
</code>```

sever.R

```<code>library(shiny)
suppressMessages(library(ggplot2))
suppressMessages(library(dplyr))
suppressMessages(library(plyr))
suppressMessages(library(tidyr))
suppressMessages(library(lubridate))

shinyServer(function(input, output) {
  output$contents <- renderTable({

    inFile <- input$file1

    if (is.null(inFile))
      return(NULL)

    rawData <- read.delim(inFile$datapath, quote = "",
                          row.names = NULL,
                          stringsAsFactors = FALSE,
                          header = F)

    rawData$V1<-gsub("http", ' ', rawData$V1)
    # replace '/' with spaces
    rawData$V1<-gsub("/", " ", rawData$V1)

    sepData<-suppressWarnings(separate(rawData, V1, c("datetime", "sender", "message"), sep = ": ", extra = "merge"))

    sepData$message <- trimws(sepData$message)
    sepData$sender<-factor(sepData$sender)

    data <- sepData %>%
      filter(!is.na(message)) %>%
      filter(!grepl(drop, sender)) %>%
      droplevels()

    data$datetime<-lubridate::dmy_hms(data$datetime)

    cleanData<-separate(data, datetime, c("date", "time"), sep = " ", remove =TRUE)
    cleanData$date<-lubridate::ymd(cleanData$date)
    cleanData$time<-lubridate::hms(cleanData$time)
    head(cleanData)
  })
})
</code>```

Firstly, there are a few problems with the output head(cleanData):

When I run head(parseR()) in Rstudio I get my desired output:

```<code>structure(list(date = structure(c(16825, 16825, 16824, 17467), class = "Date"),
    time = structure(c(47, 4, 47, 3), year = c(0, 0, 0, 0), month = c(0,
    0, 0, 0), day = c(0, 0, 0, 0), hour = c(23, 23, 23, 14), minute = c(51,
    53, 51, 54), class = structure("Period", package = "lubridate")),
    sender = structure(c(1L, 2L, 3L, 3L), .Label = c("User1",
    "User2", "User3"), class = "factor"), message = c("Message one is here",
    "A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and",
    "My first message", "My second message!")), .Names = c("date",
"time", "sender", "message"), row.names = c(NA, 4L), class = "data.frame")
</code>```

But when I run the app, the dates and times are not properly parsed (I'm using lubriudate).

Secondly, how can I call my plot function to output a plot in shiny?

答:
Like you wrapped your table in renderTable in server.R, and called tableOutput('contents') in ui.R, you need to wrap your plot in a renderPlot and call plotOutput('...') in ui.R.

Do you mean that the table output format is wrong/ugly? One workaround is to cast everything to strings and use format to get the format you want.

You can put your functions before the shinyServer(function(input, output) { ... } call in server.R, and call your functions within the shinyServer.

Body:
I have a file containing a chat log:

24/01/2016, 11:50:17 pm: Line to skip
24/01/2016, 11:50:17 pm: Line to skip
25/01/2016, 11:51:47 pm: User1: Message one is here
25/01/2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and

can
[span]

Several lines.
24/01/2016, 11:51:47 pm: User3: My first message
27/10/2017, 12:54:03 am: +44 012 3456789 left
28/10/2017, 02:54:03 pm: User3: My second message!

rawData <- structure(list(V1 = c("24 01 2016, 11:50:17 pm: Line to skip",
        "24 01 2016, 11:50:17 pm: Line to skip", "24 01 2016, 11:51:47 pm: User1: Message one is here",
        "24 01 2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and ",
        "can", "[span]", "Several lines.", "24 01 2016, 11:51:47 pm: User3: My first message",
        "27 10 2017, 12:54:03 am: +44 012 3456789 left")), .Names = "V1", row.names = c(NA,
        -9L), class = "data.frame")

In my script, I have a function to parse the file, and another to plot the number of posts per user:

# Parse the file:
parseR <- function(file='data/chatlog.txt',drop="44"){
  rawData <- read.delim(file, quote = "",
                  row.names = NULL,
                  stringsAsFactors = FALSE,
                  header = F)

  # join multi line messages into single line
  # rawData$V1<-gsub("[\r\n]", "Hello", rawData$V2)

  rawData$V1<-gsub("http", ' ', rawData$V1)
  # replace '/' with spaces
  rawData$V1<-gsub("/", " ", rawData$V1)

  sepData<-suppressWarnings(separate(rawData, V1, c("datetime", "sender", "message"), sep = ": ", extra = "merge"))

  sepData$message <- trimws(sepData$message)
  sepData$sender<-factor(sepData$sender)

  data <- sepData %>%
    filter(!is.na(message)) %>%
    filter(!grepl(drop, sender)) %>%
    droplevels()

  # data$date_time<-strsplit(data$date_time, '_')
  # data$datetime<-dmy_hms(data$datetime,tz=NULL)
  data$datetime<-dmy_hms(data$datetime, tz=NULL)

  cleanData<-separate(data, datetime, c("date", "time"), sep = " ", remove =TRUE)
  cleanData$date<-ymd(cleanData$date)
  cleanData$time<-hms(cleanData$time)

  return(cleanData)
}

# Plot the number of posts per user
senderPosts <- function(){
  data <- parseR()

  postCount<-as.data.frame(cbind(table(data$sender)))
  postCount <- data.frame(names = row.names(postCount), postCount)
  rownames(postCount)<-NULL
  colnames(postCount)<-c("name", "posts")

  postCount <- transform(postCount, name = reorder(name, -posts))

  # Plot bar
  p <- ggplot(postCount)
  p <- p + geom_bar(aes(name, posts),stat='identity')
  p <- p + scale_y_continuous("Number of posts", breaks=seq(0,max(postCount$posts),by=100))
  p <- p + cleanTheme()
  p

}

I'm trying to make this toy example into a shiny web app. The accepted answer to this question has been super useful in getting me started and I can upload the file, but I'm not sure how to actually integrate my functions in sever.R. Should I develop my functions as a package, and then load then in sever.R, or can I pass the file I upload to my functions within the sever.R script itself?

Here's what I've got so far:

ui.R

library(shiny)

suppressMessages(library("wordcloud"))
shinyUI(fluidPage(
  titlePanel("Column Plot"),
  tabsetPanel(
    tabPanel("Upload File",
             titlePanel("Uploading Files"),
             sidebarLayout(
               sidebarPanel(
                 fileInput('file1', 'Choose CSV File',
                           accept='.txt'
                           ),

                 tags$br()

               ),
               mainPanel(
                 tableOutput('contents')
               )
             )
    )

  )
)
)

sever.R

library(shiny)
suppressMessages(library(ggplot2))
suppressMessages(library(dplyr))
suppressMessages(library(plyr))
suppressMessages(library(tidyr))
suppressMessages(library(lubridate))

shinyServer(function(input, output) {
  output$contents <- renderTable({

    inFile <- input$file1

    if (is.null(inFile))
      return(NULL)

    rawData <- read.delim(inFile$datapath, quote = "",
                          row.names = NULL,
                          stringsAsFactors = FALSE,
                          header = F)

    rawData$V1<-gsub("http", ' ', rawData$V1)
    # replace '/' with spaces
    rawData$V1<-gsub("/", " ", rawData$V1)

    sepData<-suppressWarnings(separate(rawData, V1, c("datetime", "sender", "message"), sep = ": ", extra = "merge"))

    sepData$message <- trimws(sepData$message)
    sepData$sender<-factor(sepData$sender)

    data <- sepData %>%
      filter(!is.na(message)) %>%
      filter(!grepl(drop, sender)) %>%
      droplevels()

    data$datetime<-lubridate::dmy_hms(data$datetime)

    cleanData<-separate(data, datetime, c("date", "time"), sep = " ", remove =TRUE)
    cleanData$date<-lubridate::ymd(cleanData$date)
    cleanData$time<-lubridate::hms(cleanData$time)
    head(cleanData)
  })
})

Firstly, there are a few problems with the output head(cleanData):

When I run head(parseR()) in Rstudio I get my desired output:

structure(list(date = structure(c(16825, 16825, 16824, 17467), class = "Date"),
    time = structure(c(47, 4, 47, 3), year = c(0, 0, 0, 0), month = c(0,
    0, 0, 0), day = c(0, 0, 0, 0), hour = c(23, 23, 23, 14), minute = c(51,
    53, 51, 54), class = structure("Period", package = "lubridate")),
    sender = structure(c(1L, 2L, 3L, 3L), .Label = c("User1",
    "User2", "User3"), class = "factor"), message = c("Message one is here",
    "A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and",
    "My first message", "My second message!")), .Names = c("date",
"time", "sender", "message"), row.names = c(NA, 4L), class = "data.frame")

But when I run the app, the dates and times are not properly parsed (I'm using lubriudate).

Secondly, how can I call my plot function to output a plot in shiny?


问:
Redshift: Does key-based distribution optimize equality filters?
This documentation describes key-distribution in redshift as follows:

The rows are distributed according to the values in one column. The
  leader node will attempt to place matching values on the same node
  slice. If you distribute a pair of tables on the joining keys, the
  leader node collocates the rows on the slices according to the values
  in the joining columns so that matching values from the common columns
  are physically stored together.

I was wondering if key-distribution additionally helps in optimizing equality filters. My intuition says it should but it isn't mentioned anywhere.

Also, I saw a documentation regarding sort-keys which says that to select a sort-key:

Look for columns that are used in range filters and equality filters.

This got me confused since sort-keys are explicitly mentioned as a way to optimize equality filters.

I am asking this because I already have a candidate sort-key on which I will be doing range queries. But I also want to have quick equality filters on another column which is a good distribution key in my case.

答:
The simple rule is:

Use DISTKEY for the column most commonly joined

Use SORTKEY for fields most commonly used in a WHERE statement

There actually are benefits to using the same field for SORTKEY and DISTKEY. From Choose the Best Sort Key:

If you frequently join a table, specify the join column as both the sort key and the distribution key.

This enables the query optimizer to choose a sort merge join instead of a slower hash join. Because the data is already sorted on the join key, the query optimizer can bypass the sort phase of the sort merge join.

Feel free to do some performance tests -- create a few different versions of the table, and use INSERT or SELECT INTO to populate them. Then, try common queries to see how they perform.


问:
spring-data both: custom repository and out of the box optionals
I'm using custom Spring Data repository implementation/extension (one of the example here) but I would like to still make use of Optionals for basic operations - something as below (example for Mongo or Elasticsearch):

```<code>public interface DomainRepository extends MongoRepository<Domain, Long>, DomainRepositoryCustomAnyName {
    Optional<Domain> findOne(Long id);
}
</code>```

Without the need for implemention that method on my own in my DomainRepositoryImpl class (which implements DomainRepositoryCustomAnyName).

Is that somehow possible?

Currently I'm getting an exception (the same as the one indicating that I should implement that method in my DomainRepositoryImpl  class): Caused by: org.springframework.data.mapping.PropertyReferenceException: No property findOne found for type Domain

答:
I ran into quite the same problem, I think. I'm not using MongoDB but PostgreSQL but the reason for the problem might be the same. The example on the site you linked to does not use findOne so I'm not sure where you picked that up. A lot of tutorials are for versions of spring-data prior to 2.x.x. The thing is that the interfaces and implementations of the repositories changed quite a bit from 1.11.8 to 2.0.0 so the problem of yours might be connected to a version issue.

From somewhere in the past to 1.11.8 the SimpleJpaRepository had a method

```<code>public T findOne(ID id)
</code>```

and support for wrapping that result in an Optional. That would fit to your code. I tested it and it worked for a simple example. Of course I do not have your domain objects and so on.

In 2.0.0 this method got removed from SimpleJpaRepository and replaced by

```<code>public <S extends T> Optional<S> findOne(Example<S> example)
</code>```

and

```<code>public Optional<T> findById(ID id)
</code>```

So assuming that your are using spring-data-jpa 2.x.x, you have 3 options:

Switch back to version 1.11.8

Change your method signature to

Optional<Domain> findOne(Example<Domain> ex);

Use the new method instead:

Optional<Domain> findById(Long id);

Body:
I'm using custom Spring Data repository implementation/extension (one of the example here) but I would like to still make use of Optionals for basic operations - something as below (example for Mongo or Elasticsearch):

public interface DomainRepository extends MongoRepository<Domain, Long>, DomainRepositoryCustomAnyName {
    Optional<Domain> findOne(Long id);
}

Without the need for implemention that method on my own in my DomainRepositoryImpl class (which implements DomainRepositoryCustomAnyName).

Is that somehow possible?

Currently I'm getting an exception (the same as the one indicating that I should implement that method in my DomainRepositoryImpl  class): Caused by: org.springframework.data.mapping.PropertyReferenceException: No property findOne found for type Domain

Body:
I ran into quite the same problem, I think. I'm not using MongoDB but PostgreSQL but the reason for the problem might be the same. The example on the site you linked to does not use findOne so I'm not sure where you picked that up. A lot of tutorials are for versions of spring-data prior to 2.x.x. The thing is that the interfaces and implementations of the repositories changed quite a bit from 1.11.8 to 2.0.0 so the problem of yours might be connected to a version issue.

From somewhere in the past to 1.11.8 the SimpleJpaRepository had a method

public T findOne(ID id)

and support for wrapping that result in an Optional. That would fit to your code. I tested it and it worked for a simple example. Of course I do not have your domain objects and so on.

In 2.0.0 this method got removed from SimpleJpaRepository and replaced by

public <S extends T> Optional<S> findOne(Example<S> example)

and

public Optional<T> findById(ID id)

So assuming that your are using spring-data-jpa 2.x.x, you have 3 options:

Switch back to version 1.11.8

Change your method signature to

Optional<Domain> findOne(Example<Domain> ex);

Use the new method instead:

Optional<Domain> findById(Long id);


问:
Checking within a range of field of fields
I wasn't quite sure how to word the title, sorry if it doesn't make sense/is misleading.

Note - a "boat" is 3 O's next to each other in an array, so

```<code>_|O|_  _|_|_
_|O|_  O|O|O
 |O|    | |
</code>```

are boats.

So I have an a list of lists (n x n) (working with lists) in which I generate n boats at random spaces. I don't want the boats to be next to each other, touch by corners, or be on top of each other.

A tried checking if a boat would end up on top of another boat in the vein of this:

```<code>if board[y - 2][x] == 'O' or board[y + 2][x] == 'O' ...
</code>```

and so on, which ended up being unsurprisingly long.

I also got index out of range errors, since I was sometimes checking for coordinates not in the field.

So, is there a way I can check for boats in every direction without going out of index range?

Better yet, any ideas on how to make the boats not generate next to each other?

The code for boat generation is here:

```<code>from random import *

side = int(input())
game_state = []

def generate_initial_state():

    for i in range(side):
        game_state.append([])
        for j in range(side):
            game_state[i].append('.')

    for i in range(side):
        # Generate boat origin on random coordinates within the game board,
        # if there's a boat already, generate new ones
        y_cor = randint(0, side-1)
        x_cor = randint(0, side-1)
        while game_state[y_cor][x_cor] == 'O':
            y_cor = randint(0, side - 1)
            x_cor = randint(0, side - 1)
        # Direct chooses if the boat will be generated up, down, or sideways
        direct = randint(1, 4)
        cycle = 0

        while cycle < 3:
        # Generates a boat going from origin in one direction,
        # if the boat would end outside the board, chooses a different direction
            if direct == 1:
                if y_cor + 2 >= side:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor + cycle][x_cor] = 'O'
                    cycle += 1
            elif direct == 2:
                if x_cor + 2 >= side:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor][x_cor + cycle] = 'O'
                    cycle += 1
            elif direct == 3:
                if y_cor - 2 < 0:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor - cycle][x_cor] = 'O'
                    cycle += 1
            elif direct == 4:
                if x_cor - 2 < 0:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor][x_cor - cycle] = 'O'
                    cycle += 1

for i in range(side):
    print(*game_state[i])
</code>```

答:
First I would only use two directions (horizontal and vertical), which shouldn't change the probabilities (with your model, a boat can be generated in two ways).

This allows index overflow to only occur by exceeding the allowable indices, which provokes an IndexError that can be intercepted (using a negative index doesn't and that could mess up your generator).

Secondly, using a flag could help you do the trick.

I added a few other modifications :

EDIT : I just realized that my code was rejecting perfectly valid boats if they were on the border, so here is a version that doesn't.

Update : some explanations

We use a boolean flag boat_built to track the suitability of a randomly chosen position of the boat: once all tests are made, this variable decides if the choice was suitable (True) or if obstructions were encountered while tests were carried out (False).

Using

```<code>boat_built &= (game_state[x_cor + k*dx][y_cor + k*dy] != "0")
</code>```

we update the flag for every test : if boat_built was False before the test, it will remain False regardless of the test's result (False & a = False): this is intended, because it means that an obstruction has already been encountered and the boat is invalid.

On the other hand, if boat_built was True before the test, it will contain the result of the test afterwards (True & a = a): this is also intended, since failing the new test means we now have found an obstruction.

Note that all 15 tests are carried out for every boat, even if an obstruction is encountered early on.

```<code>from random import *

side = int(input())

game_state = [['.' for i in range(side)] for j in range(side)]

l_dir = [(1, 0), (0, 1)]

def generate_initial_state():

    for i in range(side):
        boat_built = False
        while not boat_built:
            boat_built = True

            y_cor = randrange(side)
            x_cor = randrange(side)

            dx, dy = l_dir[randrange(2)]

            try:
                # check that the three required cells are empty
                for k in range(3):
                    boat_built &= (game_state[x_cor + k*dx][y_cor + k*dy] != "0")
            except IndexError:
                # if any is out of range, choice is invalid
                boat_built = False

            for k in range(5):
                for l in [-1, 1]:
                    try:
                        # check if neighbours on the long sides are empty
                        boat_built &= (game_state[x_cor + (k-1)*dx + l*dy][y_cor + l*dx + (k-1)*dy] != "0")
                    except IndexError:
                        # if we're out of range, no obstruction
                        pass

            for k in [-1, 3]:
                try:
                    # check if neighbours on the short sides are empty
                    boat_built &= (game_state[x_cor + k*dx][y_cor + k*dy] != "0")
                except IndexError:
                    # again, if we're out of range, no obstruction
                    pass

        # if we reach this point, a valid position has been found
        for k in range(3):
            game_state[x_cor + k*dx][y_cor + k*dy] = "0"

generate_initial_state()

for i in range(side):
    print(*game_state[i])
</code>```

Body:
I wasn't quite sure how to word the title, sorry if it doesn't make sense/is misleading.

Note - a "boat" is 3 O's next to each other in an array, so

_|O|_  _|_|_
_|O|_  O|O|O
 |O|    | |

are boats.

So I have an a list of lists (n x n) (working with lists) in which I generate n boats at random spaces. I don't want the boats to be next to each other, touch by corners, or be on top of each other.

A tried checking if a boat would end up on top of another boat in the vein of this:

if board[y - 2][x] == 'O' or board[y + 2][x] == 'O' ...

and so on, which ended up being unsurprisingly long.

I also got index out of range errors, since I was sometimes checking for coordinates not in the field.

So, is there a way I can check for boats in every direction without going out of index range?

Better yet, any ideas on how to make the boats not generate next to each other?

The code for boat generation is here:

from random import *

side = int(input())
game_state = []

def generate_initial_state():

    for i in range(side):
        game_state.append([])
        for j in range(side):
            game_state[i].append('.')

    for i in range(side):
        # Generate boat origin on random coordinates within the game board,
        # if there's a boat already, generate new ones
        y_cor = randint(0, side-1)
        x_cor = randint(0, side-1)
        while game_state[y_cor][x_cor] == 'O':
            y_cor = randint(0, side - 1)
            x_cor = randint(0, side - 1)
        # Direct chooses if the boat will be generated up, down, or sideways
        direct = randint(1, 4)
        cycle = 0

        while cycle < 3:
        # Generates a boat going from origin in one direction,
        # if the boat would end outside the board, chooses a different direction
            if direct == 1:
                if y_cor + 2 >= side:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor + cycle][x_cor] = 'O'
                    cycle += 1
            elif direct == 2:
                if x_cor + 2 >= side:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor][x_cor + cycle] = 'O'
                    cycle += 1
            elif direct == 3:
                if y_cor - 2 < 0:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor - cycle][x_cor] = 'O'
                    cycle += 1
            elif direct == 4:
                if x_cor - 2 < 0:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor][x_cor - cycle] = 'O'
                    cycle += 1

for i in range(side):
    print(*game_state[i])

Body:
First I would only use two directions (horizontal and vertical), which shouldn't change the probabilities (with your model, a boat can be generated in two ways).

This allows index overflow to only occur by exceeding the allowable indices, which provokes an IndexError that can be intercepted (using a negative index doesn't and that could mess up your generator).

Secondly, using a flag could help you do the trick.

I added a few other modifications :

EDIT : I just realized that my code was rejecting perfectly valid boats if they were on the border, so here is a version that doesn't.

Update : some explanations

We use a boolean flag boat_built to track the suitability of a randomly chosen position of the boat: once all tests are made, this variable decides if the choice was suitable (True) or if obstructions were encountered while tests were carried out (False).

Using

boat_built &= (game_state[x_cor + k*dx][y_cor + k*dy] != "0")

we update the flag for every test : if boat_built was False before the test, it will remain False regardless of the test's result (False & a = False): this is intended, because it means that an obstruction has already been encountered and the boat is invalid.

On the other hand, if boat_built was True before the test, it will contain the result of the test afterwards (True & a = a): this is also intended, since failing the new test means we now have found an obstruction.

Note that all 15 tests are carried out for every boat, even if an obstruction is encountered early on.

from random import *

side = int(input())

game_state = [['.' for i in range(side)] for j in range(side)]

l_dir = [(1, 0), (0, 1)]

def generate_initial_state():

    for i in range(side):
        boat_built = False
        while not boat_built:
            boat_built = True

            y_cor = randrange(side)
            x_cor = randrange(side)

            dx, dy = l_dir[randrange(2)]

            try:
                # check that the three required cells are empty
                for k in range(3):
                    boat_built &= (game_state[x_cor + k*dx][y_cor + k*dy] != "0")
            except IndexError:
                # if any is out of range, choice is invalid
                boat_built = False

            for k in range(5):
                for l in [-1, 1]:
                    try:
                        # check if neighbours on the long sides are empty
                        boat_built &= (game_state[x_cor + (k-1)*dx + l*dy][y_cor + l*dx + (k-1)*dy] != "0")
                    except IndexError:
                        # if we're out of range, no obstruction
                        pass

            for k in [-1, 3]:
                try:
                    # check if neighbours on the short sides are empty
                    boat_built &= (game_state[x_cor + k*dx][y_cor + k*dy] != "0")
                except IndexError:
                    # again, if we're out of range, no obstruction
                    pass

        # if we reach this point, a valid position has been found
        for k in range(3):
            game_state[x_cor + k*dx][y_cor + k*dy] = "0"

generate_initial_state()

for i in range(side):
    print(*game_state[i])


问:
Convert array-like String to ArrayList in Java
I've been trying to convert a String like this: "[1,2,3]" to an ArrayList in Java.
What I tried so far is to use GSon library to convert the String mentioned above to List using:

Gson - convert from Json to a typed ArrayList<T>

Convert Gson Array to Arraylist

Parsing JSON array into java.util.List with Gson

but it ends with an exception (I can provide more details if needed). The first question should be actually if it's a good approach to achieve such a transformation?

答:
I suggest you use regular expression to convert the string from "[1,2,3,...]" to "1,2,3,..." and then ue asList() method of Arrays class to convert it to a List.

Refer the following snippet

```<code>import java.util.regex.*;
...
...
String str = "[1,2,3,4,5,6,7,8,9,10]";
str = str.replaceAll("[(*)])","$1");
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
</code>```

Body:
I suggest you use regular expression to convert the string from "[1,2,3,...]" to "1,2,3,..." and then ue asList() method of Arrays class to convert it to a List.

Refer the following snippet

import java.util.regex.*;
...
...
String str = "[1,2,3,4,5,6,7,8,9,10]";
str = str.replaceAll("[(*)])","$1");
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));


问:
Paste CSV or Tab-Delimited data to excel with NO formatting
I'm pasting Tab Delimited data from Notepad++ to excel (about 50k rows and 3 columns). No matter how many different ways I try it, Excel wants to convert a cell containing one " to the next instance of " into one cell content.
For Example, if my data looked like this:

```<code>"Apple  1.0  Store
Banana  1.3  Store
"Cherry"  2.5  Garden
Watermelon 4.0 Field
</code>```

The excel file looks like this:

```<code>Apple1.0StoreBanana1.3Store
Cherry  2.5GardenWatermelon4.0Field
</code>```

One way to get around this is to open the file as a CSV in excel, however this leads to Excel formatting the number values to simplified ones using Excel's "General" format. So the data would look like the following:

```<code>"Apple      1     Store
Banana      1.3   Store
"Cherry"    2.5   Garden
Watermelon  4     Field
</code>```

The data I'm getting is coming from SQL Server Studio so my options for file formats are:

.CSV

.Txt (Tab-delimited)

Copy Pasting from Query results

The solution I'm looking for is to have the data represented in Excel with no excel processing taking place on the quotations, numbers or any other cell contents.

答:
Have you tried opening it via Text Import?

Got to Data tab > From Text (third form left on default)

You will have window similar to Text To Columns.

Select correct delimiter, remember to remove the quote sign from TExt Qualifier and mark all columns as text to avoid Excel autoformatting.

Step 1:

Step 2:

Step 3:

ContentLicense: CC BY-SA 4.0

Body:
I'm pasting Tab Delimited data from Notepad++ to excel (about 50k rows and 3 columns). No matter how many different ways I try it, Excel wants to convert a cell containing one " to the next instance of " into one cell content.
For Example, if my data looked like this:

"Apple  1.0  Store
Banana  1.3  Store
"Cherry"  2.5  Garden
Watermelon 4.0 Field

The excel file looks like this:

Apple1.0StoreBanana1.3Store
Cherry  2.5GardenWatermelon4.0Field

One way to get around this is to open the file as a CSV in excel, however this leads to Excel formatting the number values to simplified ones using Excel's "General" format. So the data would look like the following:

"Apple      1     Store
Banana      1.3   Store
"Cherry"    2.5   Garden
Watermelon  4     Field

The data I'm getting is coming from SQL Server Studio so my options for file formats are:

.CSV

.Txt (Tab-delimited)

Copy Pasting from Query results

The solution I'm looking for is to have the data represented in Excel with no excel processing taking place on the quotations, numbers or any other cell contents.


问:
R: How to read selected columns from a RDS files?
How to read part of the data from very large files?

The sample data is generated as:

```<code>set.seed(123)
df <- data.frame(replicate(10, sample(0:2000, 15 * 10^5, rep = TRUE)),
                 replicate(10, stringi::stri_rand_strings(1000, 5)))
head(df)
#     X1   X2   X3   X4   X5   X6   X7   X8   X9  X10  X1.1  X2.1  X3.1  X4.1  X5.1  X6.1  X7.1  X8.1  X9.1 X10.1
# 1  575 1843 1854  883  592 1362 1075  210 1526 1365 Qk8NP Xvw9z OYRa1 8BGIV bejiv CCoIE XDKJN HR7zc 2kKNY 1I5h8
# 2 1577  390 1861  912  277  636  758 1461 1978 1865 ZaHFl QLsli E7lbs YGq8u DgUAW c6JQ0 RAZFn Sc0Zt mif8I 3Ys6U
# 3  818 1076  147 1221  257 1115  759 1959 1088 1292 jM5Uw ctM3y 0HiXR hjOHK BZDOP ULQWm Ei8qS BVneZ rkKNL 728gf
# 4 1766  884 1331 1144 1260  768 1620 1231 1428 1193 r4ZCI eCymC 19SwO Ht1O0 repPw YdlSW NRgfL RX4ta iAtVn Hzm0q
# 5 1881 1851 1324 1930 1584 1318  940 1796  830   15 w8d1B qK1b0 CeB8u SlNll DxndB vaufY ZtlEM tDa0o SEMUX V7tLQ
# 6   91  264 1563  414  914 1507 1935 1970  287  409 gsY1u FxIgu 2XqS4 8kreA ymngX h0hkK reIsn tKgQY ssR7g W3v6c
</code>```

saveRDS is used to save the file.

```<code>saveRDS(df, 'df.rds')
</code>```

The file size is looked using the below commands:

```<code>file.info('df.rds')$size
# [1] 29935125
utils:::format.object_size(29935125, "auto")
# [1] "28.5 Mb"
</code>```

The saved file is read using the below function.

```<code>readRDS('df.rds')
</code>```

However, some of my files are in GBs and would need only few columns for certain processing. Is it possible to read selected columns from RDS files?

Note: I already have RDS files, generated after considerably large amounts of processing. Now, I want to know the best possible way to read selected columns from the existing RDS files.

答:
SQLite also could be a common way to store tabular/matrix/dataframe data on your hard drive using an SQLite database. This also allows the use of standard SQL commands or DPLYR to interrogate the data. Just be warned that SQLite does not have a date format so any dates need to be converted to character before writing them to the database.</p>

```<code>set.seed(123)
df <- data.frame(replicate(10, sample(0:2000, 15 * 10^5, rep = TRUE)),
                 replicate(10, stringi::stri_rand_strings(1000, 5)))

library(RSQLite)
conn <- dbConnect(RSQLite::SQLite(), dbname="myDB")
dbWriteTable(conn,"mytable",df)
alltables <- dbListTables(conn)
# Use sql queries to query data...
oneColumn <- dbGetQuery(conn,"SELECT X1 FROM mytable")

library(dplyr)
library(dbplyr)
my_db <- tbl(conn, "mytable")
my_db
# Use dplyr functions to query data...
my_db %>% select(X1)
</code>```

Body:
How to read part of the data from very large files?

The sample data is generated as:

set.seed(123)
df <- data.frame(replicate(10, sample(0:2000, 15 * 10^5, rep = TRUE)),
                 replicate(10, stringi::stri_rand_strings(1000, 5)))
head(df)
#     X1   X2   X3   X4   X5   X6   X7   X8   X9  X10  X1.1  X2.1  X3.1  X4.1  X5.1  X6.1  X7.1  X8.1  X9.1 X10.1
# 1  575 1843 1854  883  592 1362 1075  210 1526 1365 Qk8NP Xvw9z OYRa1 8BGIV bejiv CCoIE XDKJN HR7zc 2kKNY 1I5h8
# 2 1577  390 1861  912  277  636  758 1461 1978 1865 ZaHFl QLsli E7lbs YGq8u DgUAW c6JQ0 RAZFn Sc0Zt mif8I 3Ys6U
# 3  818 1076  147 1221  257 1115  759 1959 1088 1292 jM5Uw ctM3y 0HiXR hjOHK BZDOP ULQWm Ei8qS BVneZ rkKNL 728gf
# 4 1766  884 1331 1144 1260  768 1620 1231 1428 1193 r4ZCI eCymC 19SwO Ht1O0 repPw YdlSW NRgfL RX4ta iAtVn Hzm0q
# 5 1881 1851 1324 1930 1584 1318  940 1796  830   15 w8d1B qK1b0 CeB8u SlNll DxndB vaufY ZtlEM tDa0o SEMUX V7tLQ
# 6   91  264 1563  414  914 1507 1935 1970  287  409 gsY1u FxIgu 2XqS4 8kreA ymngX h0hkK reIsn tKgQY ssR7g W3v6c

saveRDS is used to save the file.

saveRDS(df, 'df.rds')

The file size is looked using the below commands:

file.info('df.rds')$size
# [1] 29935125
utils:::format.object_size(29935125, "auto")
# [1] "28.5 Mb"

The saved file is read using the below function.

readRDS('df.rds')

However, some of my files are in GBs and would need only few columns for certain processing. Is it possible to read selected columns from RDS files?

Note: I already have RDS files, generated after considerably large amounts of processing. Now, I want to know the best possible way to read selected columns from the existing RDS files.

Body:
SQLite also could be a common way to store tabular/matrix/dataframe data on your hard drive using an SQLite database. This also allows the use of standard SQL commands or DPLYR to interrogate the data. Just be warned that SQLite does not have a date format so any dates need to be converted to character before writing them to the database.

set.seed(123)
df <- data.frame(replicate(10, sample(0:2000, 15 * 10^5, rep = TRUE)),
                 replicate(10, stringi::stri_rand_strings(1000, 5)))

library(RSQLite)
conn <- dbConnect(RSQLite::SQLite(), dbname="myDB")
dbWriteTable(conn,"mytable",df)
alltables <- dbListTables(conn)
# Use sql queries to query data...
oneColumn <- dbGetQuery(conn,"SELECT X1 FROM mytable")

library(dplyr)
library(dbplyr)
my_db <- tbl(conn, "mytable")
my_db
# Use dplyr functions to query data...
my_db %>% select(X1)


问:
Assign to a null pointer an area inside a function and preserve the value outside
I have a function that reads from a socket, it returns a char** where packets are stored and my intention is to use a NULL unsigned int pointer where I store the length of single packet.

```<code>char** readPackets(int numToRead,unsigned int  **lens,int socket){

    char** packets=(char**)malloc(numToRead);
    int *len=(int*)malloc(sizeof(int)*numToRead);

    *(lens)=len;

    for(int i=0;i<numToRead;i++){
        //read
        packets[i]=(char*)malloc(MAX_ETH_LEN);
        register int pack_len=read(socket,packets[i],MAX_ETH_LEN);

        //TODO handler error in  case of freezing

        if(pack_len<=0){
            i--;
            continue;
        }
        len[i]=pack_len;
    }

    return packets;

}
</code>```

I use it in this way:

```<code>unsigned int *lens_out=NULL;
char **packets=readPackets(N_PACK,&lens,sniff_sock[handler]);
</code>```

where N_PACK is a constant defined previously.

Now the problem is that when I am inside the function everything works, in fact *(lens) points to the same memory area of len and outside the function lens_out points to the same area too. Inside the function len[i] equals to *(lens[i]) (I checked it with gdb).

The problem is that outside the function even if lens_out points to the same area of len elements with same index are different for example

```<code>len[0]=46
lens_out[0]=4026546640
</code>```

Can anyone explain where I made the mistake?

答:
Your statement char** packets=(char**)malloc(numToRead) for sure does not reserve enough memory. Note that an element of packets-array is of type char*, and that sizeof(char*) is probably 8 (eventually 4), but very very unlikely 1. So you should write

```<code>char** packets = malloc(sizeof(char*) * numToRead)
</code>```

Otherwise, you write out of the bounds of reserved memory, thereby yielding undefined behaviour (probably the one you explained).

Note further that with i--; continue;, you get memory leaks since you assign a new memory block to the ith element, but you lose reference to the memory reserved right before.  Write free(packets[i]);i--;continue; instead.

Further, len[0] is an integral type, whereas lens[0] refers to a pointer to int. Comparing these two does not make sense.

Body:
I have a function that reads from a socket, it returns a char** where packets are stored and my intention is to use a NULL unsigned int pointer where I store the length of single packet.

char** readPackets(int numToRead,unsigned int  **lens,int socket){

    char** packets=(char**)malloc(numToRead);
    int *len=(int*)malloc(sizeof(int)*numToRead);

    *(lens)=len;

    for(int i=0;i<numToRead;i++){
        //read
        packets[i]=(char*)malloc(MAX_ETH_LEN);
        register int pack_len=read(socket,packets[i],MAX_ETH_LEN);

        //TODO handler error in  case of freezing

        if(pack_len<=0){
            i--;
            continue;
        }
        len[i]=pack_len;
    }

    return packets;

}

I use it in this way:

unsigned int *lens_out=NULL;
char **packets=readPackets(N_PACK,&lens,sniff_sock[handler]);

where N_PACK is a constant defined previously.

Now the problem is that when I am inside the function everything works, in fact *(lens) points to the same memory area of len and outside the function lens_out points to the same area too. Inside the function len[i] equals to *(lens[i]) (I checked it with gdb).

The problem is that outside the function even if lens_out points to the same area of len elements with same index are different for example

len[0]=46
lens_out[0]=4026546640

Can anyone explain where I made the mistake?

Body:
Your statement char** packets=(char**)malloc(numToRead) for sure does not reserve enough memory. Note that an element of packets-array is of type char*, and that sizeof(char*) is probably 8 (eventually 4), but very very unlikely 1. So you should write

char** packets = malloc(sizeof(char*) * numToRead)

Otherwise, you write out of the bounds of reserved memory, thereby yielding undefined behaviour (probably the one you explained).

Note further that with i--; continue;, you get memory leaks since you assign a new memory block to the ith element, but you lose reference to the memory reserved right before.  Write free(packets[i]);i--;continue; instead.

Further, len[0] is an integral type, whereas lens[0] refers to a pointer to int. Comparing these two does not make sense.


问:
How to implemennt OnZoomListener on MapView
I would like to have onZoomListener on my MapView.
The code below is what I have done. It registers if zoom buttons are tapped. Since all new phones now supports pinch to zoom, this is useless. Does anybody have idea how to do real onZoomListener? Thanks.</p>

```<code>   OnZoomListener listener = new OnZoomListener() {
   @Override
   public void onVisibilityChanged(boolean arg0) {
    // TODO Auto-generated method stub

   }
   @Override
   public void onZoom(boolean arg0) {
    Log.d(TAG, "ZOOM CHANGED");
    // TODO Auto-generated method stub

   }
  };

  ZoomButtonsController zoomButton = mapView.getZoomButtonsController();
  zoomButton.setOnZoomListener(listener);
</code>```

答: Edit: I believe what you've found is probably the only mechanism to allow this detection. (Editing my post to remove misinformation) Extending the MapView and overriding the onDraw() method would work.  One consideration to make will be how often to fire the code listening to zoom.  For instance, while zooming the onDraw may be called dozens of times each with a different zoom level.  This may cause poor performance if your listener is firing every time.  You could throttle this by determining that a zoom change has taken place and then waiting for the zoom level to be the same on two subsequent redraws before firing the event.  This all depends on how you want your code to be called.</p>

ContentLicense: CC BY-SA 2.5

Body:
I would like to have onZoomListener on my MapView.
The code below is what I have done. It registers if zoom buttons are tapped. Since all new phones now supports pinch to zoom, this is useless. Does anybody have idea how to do real onZoomListener? Thanks.

   OnZoomListener listener = new OnZoomListener() {
   @Override
   public void onVisibilityChanged(boolean arg0) {
    // TODO Auto-generated method stub

   }
   @Override
   public void onZoom(boolean arg0) {
    Log.d(TAG, "ZOOM CHANGED");
    // TODO Auto-generated method stub

   }
  };

  ZoomButtonsController zoomButton = mapView.getZoomButtonsController();
  zoomButton.setOnZoomListener(listener);


问:
Subsetting rows with "_" in one column in R
I have a data frame that contains of over 10000 rows and approximately 20 columns.
The ID column includes some entries that have a "_ "  separating two or more numbers/words etc.
How do I subset only rows that have a "_ " in the ID column into a separate data frame? </p>

答:
The str_detect function from stringr is helpful here. Now that the package is included with version 1.2 of the tidyverse package, the following code should work:

```<code>library(tidyverse)

filtered_df <- df %>%
  filter(str_detect(ID, "_"))
</code>```

This line of code will return filtered_df, a data frame based on df that only includes the rows where the ID column includes an underscore.

Body:
The str_detect function from stringr is helpful here. Now that the package is included with version 1.2 of the tidyverse package, the following code should work:

library(tidyverse)

filtered_df <- df %>%
  filter(str_detect(ID, "_"))

This line of code will return filtered_df, a data frame based on df that only includes the rows where the ID column includes an underscore.


答:
Don't open the file directly in excel.  Instead import it and control the data types and file layout.

Open a new excel document:

Select Data menu:

Select From Text in get External Data section.

Select file to import

On step 1 of import wizard select delimited

Click next

Select tab checkbox and change text qualifier to {none}.

Click next

Set column data types to general, text, text

Click finish.

Excel auto imports the data the best it can when you open directly in excel.  You lose flexibility/control when this happens.  better to import and control yourself to get the fine adjustments you're looking for.

You end up with something like this:

By treating the numbers like text, the zero's don't get messed up.

By setting the text qualifier to none, the quotes don't get messed up.

Title: Paste CSV or Tab-Delimited data to excel with NO formatting


问:
Informing div to look like boxes without distrubing Grids
Greetings i am kinda new to boostrap, Anyhow, I am trying to Create is, Boxes to look like this (right side):

And so far i got nothing. i used padding but it mess up my grid system, what i did was give a col-sm-8 for picture side and a col-sm-4 for boxes however it is where it gets tricky it always mess my grid system. this is my html. could you help me out a little bit?

```<code><div class="container">
    <div class="row">
        <div class="col-sm-8">
            <img src="xxxx" />
        </div>
        <div class="col-sm-4">
            <div class="col-sm-6">
                <div style="background-color: grey; padding: 25px; text-align: center; vertical-align: middle">
                    Oven
                </div>
            </div>
            <div class="col-sm-6">
                <div style="background-color: grey; padding: 25px; text-align: center; vertical-align: middle">
                    Cookers
                </div>
            </div>
            <div class="col-sm-6">
                <div style="background-color: grey; padding: 25px; text-align: center; vertical-align: middle">
                    Microwave Ovens
                </div>
            </div>
            <div class="col-sm-6">
                <div style="background-color: grey; padding: 25px; text-align: center; vertical-align: middle">
                    Steamers
                </div>
            </div>
            <div class="col-sm-6">
                <div style="background-color: grey; padding: 25px; text-align: center; vertical-align: middle">
                    Cooker hoods
                </div>
            </div>
            <div class="col-sm-6">
                <div style="background-color: grey; padding: 25px; text-align: center; vertical-align: middle">
                    Hobs
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

答:
You are missing a row class, it's mandatory for nested rows/columns, so you can do this (go full page to see the result as you want) :

.box {
  background-color: grey;
  padding: 25px;
  text-align: center;
  vertical-align: middle;
  margin: 10px;
}

img {
  max-width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<div class="container">
  <div class="row">
    <div class="col-sm-8">
      <img src="https://lorempixel.com/800/400/" />
    </div>
    <div class="col-sm-4">
      <div class="row">
        <div class="col-sm-6">
          <div class="box">
            Oven
          </div>
        </div>
        <div class="col-sm-6">
          <div class="box">
            Cookers
          </div>
        </div>
        <div class="col-sm-6">
          <div class="box">
            Microwave
          </div>
        </div>
        <div class="col-sm-6">
          <div class="box">
            Steamers
          </div>
        </div>
        <div class="col-sm-6">
          <div class="box">
            Cooker hoods
          </div>
        </div>
        <div class="col-sm-6">
          <div class="box">
            Hobs
          </div>
        </div>
      </div>
    </div>
  </div>
</div></code>```

You can read more about grid nesting

Body:
Greetings i am kinda new to boostrap, Anyhow, I am trying to Create is, Boxes to look like this (right side):

And so far i got nothing. i used padding but it mess up my grid system, what i did was give a col-sm-8 for picture side and a col-sm-4 for boxes however it is where it gets tricky it always mess my grid system. this is my html. could you help me out a little bit?

                    Oven

                    Cookers

                    Microwave Ovens

                    Steamers

                    Cooker hoods

                    Hobs

Body:
You are missing a row class, it's mandatory for nested rows/columns, so you can do this (go full page to see the result as you want) :

.box {
  background-color: grey;
  padding: 25px;
  text-align: center;
  vertical-align: middle;
  margin: 10px;
}

img {
  max-width: 100%;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<div class="container">
  <div class="row">
    <div class="col-sm-8">
      <img src="https://lorempixel.com/800/400/" />
    </div>
    <div class="col-sm-4">
      <div class="row">
        <div class="col-sm-6">
          <div class="box">
            Oven
          </div>
        </div>
        <div class="col-sm-6">
          <div class="box">
            Cookers
          </div>
        </div>
        <div class="col-sm-6">
          <div class="box">
            Microwave
          </div>
        </div>
        <div class="col-sm-6">
          <div class="box">
            Steamers
          </div>
        </div>
        <div class="col-sm-6">
          <div class="box">
            Cooker hoods
          </div>
        </div>
        <div class="col-sm-6">
          <div class="box">
            Hobs
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

You can read more about grid nesting


问:
how do I set the location of pegman?
I have been trying to find a way to set the location on peg man in google maps via programming instead of dragging and dropping.Is there a way to set the location of pegman on google maps programmatically? </p>

答:
better late than never, but you're looking for the pano function setPosition

setStreetView sets the pano view, but setPosition should place pegman.

Title: how do I set the location of pegman?


问:
How to change the Figure Canvas Color (PyQt)
How can I set the background color of my figures? I would like to use FigureCanvasQTAgg.</p>

```<code>from PyQt5 import QtCore, QtWidgets, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT
from matplotlib.figure import Figure

class FigureCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvasQTAgg.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(
            self,
            QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding,
        )
        FigureCanvas.updateGeometry(self)
</code>```

答:
Under usual circumstances there is no difference between the figure background and the canvas background. So you may set the figure background to some color

```<code>self.fig.set_facecolor("blue")
</code>```

In case you do not want to change the figure's background color (I can't think of any reason right now, but maybe there is one use case), you would need to make the figure background transparent, such that the canvas background color can shine through,

```<code>self.fig.set_facecolor("none")
self.setStyleSheet("background-color:blue;")
</code>```

This answer of mine gives some insight and also a test code to play with.

Body:
How can I set the background color of my figures? I would like to use FigureCanvasQTAgg.

from PyQt5 import QtCore, QtWidgets, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT
from matplotlib.figure import Figure

class FigureCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvasQTAgg.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(
            self,
            QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding,
        )
        FigureCanvas.updateGeometry(self)

Body:
Under usual circumstances there is no difference between the figure background and the canvas background. So you may set the figure background to some color

self.fig.set_facecolor("blue")

In case you do not want to change the figure's background color (I can't think of any reason right now, but maybe there is one use case), you would need to make the figure background transparent, such that the canvas background color can shine through,

self.fig.set_facecolor("none")
self.setStyleSheet("background-color:blue;")

This answer of mine gives some insight and also a test code to play with.


问:
Shell script: get the exit status of a failed background child process in Solaris
I have written a POC .This code works fine in Linux but not in Solaris. I am using Solaris 10

```<code>enter code here
#!/bin/sh
echo inside parent
echo executing child in the background
./remove deepti & # executing dummy command to make sure that background process fails
childpid=$!
i=0
while [ `ps -p $childpid >/dev/null; echo $?` = 0 ]; do
    sleep 5
    i=`expr $i + 1`
    if [ $i -gt 3 ]; then
        echo wait exceeded
        ps -p $childpid >/dev/null
        exit $?
    fi
done
wait $childpid
exit $?
</code>```

I expect that Wait shall return me the exit status of background command . exit status should be 127 . However I get exit status as 0.

答:
It is not a bug but the expected and documented behavior of /bin/sh on Solaris. Quoted from wait(1) manual page:

If pid is not an active process ID, the wait utility will return immediately and the return code will be 0.

Older Bourne shell documentation was not specifying what wait should do when invoked with already dead processes so the result was undefined behavior. The documentation was fixed to clarify that point in 1998. ksh was the recommended way to get the expected return status: http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=4068875

With Solaris 10 and older, /bin/sh is a legacy scripting language that shouldn't be used with new code. You'd rather use /bin/ksh or /usr/xpg4/bin/sh instead for POSIX scripts. Solaris 11 Express provides a POSIX /bin/sh so this kind of issues would no more happen.

Body:
I have written a POC .This code works fine in Linux but not in Solaris. I am using Solaris 10

enter code here
#!/bin/sh
echo inside parent
echo executing child in the background
./remove deepti & # executing dummy command to make sure that background process fails
childpid=$!
i=0
while [ `ps -p $childpid >/dev/null; echo $?` = 0 ]; do
    sleep 5
    i=`expr $i + 1`
    if [ $i -gt 3 ]; then
        echo wait exceeded
        ps -p $childpid >/dev/null
        exit $?
    fi
done
wait $childpid
exit $?

I expect that Wait shall return me the exit status of background command . exit status should be 127 . However I get exit status as 0.


问:
Symfony: clone object with Datetime field and add days to cloned object dates
I have an apparently simple problem but after several hours of try-and-error I only get wrong results.

The goal is to duplicate an object Convention with a OneToMany relation to HallReservation and add some days to this reservations. The result I get is, the days are added in the cloned objects and in the original objects, I want the original objects to remain unaltered.

This is the significant code:

```<code>/**
 * @ORM\Entity()
 */
class Convention
{
/**
 * @ORM\OneToMany(targetEntity="HallReservation", mappedBy="convention", cascade={"all"})
 */
private $hallReservation;

/**
 * Clone object
 *
 */
public function __clone()
{
    if ($this->id)
    {
        $this->id=null;
        $this->reference = null;
        $this->registrationDate = new \Datetime('now');

        foreach ($this->hallReservation as $hallR)
        {
            $clonedR = clone $hallR;
            $clonedR->setConvention($this);
            $newRDate = clone $hallR->getDate();
            $clonedR->setDate($newRDate);
            $this->hallReservation->add($clonedR);
        }
    }
}

/**
 * @ORM\Entity()
 */
class HallReservation
{
/**
 * @var \Date
 *
 * @ORM\Column(name="date", type="date")
 */
private $date;

/**
 * Clone object
 *
 */
public function __clone()
{
    if ($this->id)
    {
        $this->id=null;
        $clonedDate = clone $this->date;
        $this->date = $clonedDate;

}
</code>```

Controller code:

```<code>        $jumpInterval = $originalConventionBeginDate->diff($newDate);
        foreach ($newConvention->getHallReservation() as $newHallR)
        {
            $prevDate = clone $newHallR->getDate();
            $prevDate->add($jumpInterval);

            $newHallR->setDate($prevDate);
        }
        $em->persist($newConvention);
        $em->flush();
</code>```

As you see I clone datetime object everywhere but still the original convention hall reservations dates are also being added.

答:
When you clone the Convention object you do not set the hallReservation property to a new Collection. A OneToMany relation in Doctrine is mapped to a Collection object, so when you clone the Convention object, you get a reference to the original hallReservation collection in the cloned object.

You could try something like this:

```<code><?php

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity()
 */
class Convention
{
/**
 * @ORM\OneToMany(targetEntity="HallReservation", mappedBy="convention", cascade={"all"})
 */
private $hallReservation;

/**
 * Clone object
 *
 */
public function __clone()
{
    if ($this->id)
    {
        $this->id=null;
        $this->reference = null;
        $this->registrationDate = new \Datetime('now');
        $reservations = new ArrayCollection();

        foreach ($this->hallReservation as $hallR)
        {
            $clonedR = clone $hallR;
            $clonedR->setConvention($this);
            $newRDate = clone $hallR->getDate();
            $clonedR->setDate($newRDate);
            $reservations->add($clonedR);
        }

        $this->hallReservation = $reservations;
    }
}
</code>```

Body:
I have an apparently simple problem but after several hours of try-and-error I only get wrong results.

The goal is to duplicate an object Convention with a OneToMany relation to HallReservation and add some days to this reservations. The result I get is, the days are added in the cloned objects and in the original objects, I want the original objects to remain unaltered.

This is the significant code:

/**
 * @ORM\Entity()
 */
class Convention
{
/**
 * @ORM\OneToMany(targetEntity="HallReservation", mappedBy="convention", cascade={"all"})
 */
private $hallReservation;

/**
 * Clone object
 *
 */
public function __clone()
{
    if ($this->id)
    {
        $this->id=null;
        $this->reference = null;
        $this->registrationDate = new \Datetime('now');

        foreach ($this->hallReservation as $hallR)
        {
            $clonedR = clone $hallR;
            $clonedR->setConvention($this);
            $newRDate = clone $hallR->getDate();
            $clonedR->setDate($newRDate);
            $this->hallReservation->add($clonedR);
        }
    }
}

/**
 * @ORM\Entity()
 */
class HallReservation
{
/**
 * @var \Date
 *
 * @ORM\Column(name="date", type="date")
 */
private $date;

/**
 * Clone object
 *
 */
public function __clone()
{
    if ($this->id)
    {
        $this->id=null;
        $clonedDate = clone $this->date;
        $this->date = $clonedDate;

}

Controller code:

        $jumpInterval = $originalConventionBeginDate->diff($newDate);
        foreach ($newConvention->getHallReservation() as $newHallR)
        {
            $prevDate = clone $newHallR->getDate();
            $prevDate->add($jumpInterval);

            $newHallR->setDate($prevDate);
        }
        $em->persist($newConvention);
        $em->flush();

As you see I clone datetime object everywhere but still the original convention hall reservations dates are also being added.

Body:
When you clone the Convention object you do not set the hallReservation property to a new Collection. A OneToMany relation in Doctrine is mapped to a Collection object, so when you clone the Convention object, you get a reference to the original hallReservation collection in the cloned object.

You could try something like this:

<?php

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity()
 */
class Convention
{
/**
 * @ORM\OneToMany(targetEntity="HallReservation", mappedBy="convention", cascade={"all"})
 */
private $hallReservation;

/**
 * Clone object
 *
 */
public function __clone()
{
    if ($this->id)
    {
        $this->id=null;
        $this->reference = null;
        $this->registrationDate = new \Datetime('now');
        $reservations = new ArrayCollection();

        foreach ($this->hallReservation as $hallR)
        {
            $clonedR = clone $hallR;
            $clonedR->setConvention($this);
            $newRDate = clone $hallR->getDate();
            $clonedR->setDate($newRDate);
            $reservations->add($clonedR);
        }

        $this->hallReservation = $reservations;
    }
}


问:
C how to show all unused functions (including ones defined in h files)
Somewhat related to this, but it still doesn't quite answer my question

I have a C project, and i would like to enumerate all unreferenced functions (including non-static, so setting compiler option for werror=unused-function only partially works...) in order to identify and clean up the codebase.

One way I thought is to enumerate all the functions in the project, and then make a script to go through each and see if it is called via cscope... but I'm not sure how to get a list-form of all the functions in the first place. That link above has a solution that is failing for me.

Any other ideas are welcome.

答:
I would use a static code analysis tool such as lint.  It is a good tool for discovering potential problems in your code as well as for keeping it tidy, since it can be configured to point out unused functions/variables/etc.

Others have suggested Cppcheck which is a free alternative, but I have not used it so I cannot personally vouch for it.


问:
Temp dir in java being overwritten
I have a file that is in tar.gz format. I read it's path and then I try to write it inside a temp directory that I created. The directory gets over written as a file. What am I doing wrong? I am doing this in scala but using java classes underneath.</p>

```<code>def restore(id: String) = {
    Future {
      val sourceDir = getSourceFile(id)
      val f = {
        new File(sourceDir)
      }
      if (!f.exists())
        throw ResourceNotFoundException(s"Failed")

      val tmpDir = Files.createTempDirectory("restoreMe")

      val p = Paths.get(s"${tmpDir.toAbsolutePath().toString}/")
      Files.copy(f.toPath, p, StandardCopyOption.REPLACE_EXISTING);
    }
  }
</code>```

答:
use this</p>

```<code>Path src = f.toPath
Files.copy(src, p.resolve(src.getFileName()), StandardCopyOption.REPLACE_EXISTING);
</code>```

Title: Temp dir in java being overwritten

Body:
I have a file that is in tar.gz format. I read it's path and then I try to write it inside a temp directory that I created. The directory gets over written as a file. What am I doing wrong? I am doing this in scala but using java classes underneath.

def restore(id: String) = {
    Future {
      val sourceDir = getSourceFile(id)
      val f = {
        new File(sourceDir)
      }
      if (!f.exists())
        throw ResourceNotFoundException(s"Failed")

      val tmpDir = Files.createTempDirectory("restoreMe")

      val p = Paths.get(s"${tmpDir.toAbsolutePath().toString}/")
      Files.copy(f.toPath, p, StandardCopyOption.REPLACE_EXISTING);
    }
  }

Body:
use this

Path src = f.toPath
Files.copy(src, p.resolve(src.getFileName()), StandardCopyOption.REPLACE_EXISTING);


问:
Where does a logger goes in DDD?
To which layer does the logger belongs in DDD?</p>

答:
What would we want to log in DDD?

Important events that occur, of course.

The Logger itself is a service of the infrastructure.  Bridging the domain and the logger can occur in an event handler.

Logging fits well inside of event handlers and when placed there it creates a very nice separation of concerns.

Title: Where does a logger goes in DDD?


问:
Undefined symbols for architecture x86_64 - how to find missing files
I am trying to use the ceres-solver package. After installing it using home-brew, I added created my CMakeLists.txt file as follows:

```<code>cmake_minimum_required(VERSION 3.8)
project(myproject)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(untitled ${SOURCE_FILES})

# add extra include directories
include_directories(/usr/local/include)
include_directories(/usr/local/include/eigen3)

# add extra lib directories
link_directories(/usr/local/lib)
</code>```

When I try to use the Ceres package, however, I get a linking error. As a very simple test case, I am using the following code:

```<code>#include "ceres.h"

int main(int argc, char** argv) {
    ceres::Problem problem;
    return 0;
}
</code>```

which raises the following error:

```<code>Undefined symbols for architecture x86_64:
  "ceres::Problem::Problem()", referenced from:
      _main in main.cpp.o
  "ceres::Problem::~Problem()", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

From looking around on stackoverflow, I now know that I am likely missing something from CMakeLists.txt, but no matter what I try including I can't seem to get rid of the error. Any suggestions on how to solve this?

I am currently working in CLion for Mac on OS 10.12.6.

Post solution edit

As recommended by PureVision, I changed my CMakeLists.txt to the following and all is well

```<code>cmake_minimum_required(VERSION 3.8)
project(myproject)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

# add extra include directories
include_directories(/usr/local/include)
include_directories(/usr/local/include/eigen3)

# add extra lib directories
link_directories(/usr/local/lib)

link_libraries(glog)
link_libraries(ceres)

add_executable(myproject ${SOURCE_FILES})
</code>```

答:
Move your link_directories and include_directories calls before your add_executable call.

Link_directories and include_directories only apply to targets created after those functions are called. See link_directories.

Next, the reason why you are getting the linker error is probably due to the fact that you have not linked the library that you're trying to use into your target "untitled". The function you're looking for is target_link_libraries.

An example is:

```<code>target_link_libraries(untitled general NameOfLibrary)
</code>```

There are a lot more options you can apply to target_link_libraries but you can find more information inside of the link. One thing I will note, is that I don't have a path to the library inside of the target_link_libraries call, but that's assuming the library that you're looking for is specified in the link_directories() call. This function will accept paths as well however.

Hopefully this is what you're looking for.

Body:
I am trying to use the ceres-solver package. After installing it using home-brew, I added created my CMakeLists.txt file as follows:

cmake_minimum_required(VERSION 3.8)
project(myproject)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(untitled ${SOURCE_FILES})

# add extra include directories
include_directories(/usr/local/include)
include_directories(/usr/local/include/eigen3)

# add extra lib directories
link_directories(/usr/local/lib)

When I try to use the Ceres package, however, I get a linking error. As a very simple test case, I am using the following code:

#include "ceres.h"

int main(int argc, char** argv) {
    ceres::Problem problem;
    return 0;
}

which raises the following error:

Undefined symbols for architecture x86_64:
  "ceres::Problem::Problem()", referenced from:
      _main in main.cpp.o
  "ceres::Problem::~Problem()", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

From looking around on stackoverflow, I now know that I am likely missing something from CMakeLists.txt, but no matter what I try including I can't seem to get rid of the error. Any suggestions on how to solve this?

I am currently working in CLion for Mac on OS 10.12.6.

Post solution edit

As recommended by PureVision, I changed my CMakeLists.txt to the following and all is well

cmake_minimum_required(VERSION 3.8)
project(myproject)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

# add extra include directories
include_directories(/usr/local/include)
include_directories(/usr/local/include/eigen3)

# add extra lib directories
link_directories(/usr/local/lib)

link_libraries(glog)
link_libraries(ceres)

add_executable(myproject ${SOURCE_FILES})

Body:
Move your link_directories and include_directories calls before your add_executable call.

Link_directories and include_directories only apply to targets created after those functions are called. See link_directories.

Next, the reason why you are getting the linker error is probably due to the fact that you have not linked the library that you're trying to use into your target "untitled". The function you're looking for is target_link_libraries.

An example is:

target_link_libraries(untitled general NameOfLibrary)

There are a lot more options you can apply to target_link_libraries but you can find more information inside of the link. One thing I will note, is that I don't have a path to the library inside of the target_link_libraries call, but that's assuming the library that you're looking for is specified in the link_directories() call. This function will accept paths as well however.

Hopefully this is what you're looking for.