问:
contentEditable does not wrap first line in tags
I have a div with the attribute contentEditable set.

The trouble I am having is that the first line I type does not get wrapped in tags, but the subsequent lines do.

So typing:

```<code>qwerty
zxcv
asdfg
</code>```

Results in:

```<code><div class="editable" contentEditable="true">
    qwerty
    <div>zxcv</div>
    <div>asdfg</div>
</div>
</code>```

So I need the qwerty line to become
qwerty

答:
Context

This is a solution to the OP that ensures the first line in a content editable div always gets wrapped and fixes common bugs like:

Un-wrapped first line after erasing editor and immediately typing.

Line break added after erasing editor.

All of the issues mentioned by Kasper Fredenslund:

Ctrl + A + Del

Ctrl + A + Backspace

Ctrl + A + Any typing the user does

It uses event listeners to catch when a user focuses on the editor and when they leave. For more context please read the comments in the code.

Code

Below is a full working fiddle of the code. My original example can be found at this JS Fiddle page.

// On Dom Ready
document.getElementById('editor').addEventListener('focusin', checkEditor);
document.getElementById('editor').addEventListener('focusout', checkEditor);

function checkEditor() {
  // Get the DOM element that the user is in
  // Allows you to have multiple editos on one page
  // Next 3 lines of code from: https://stackoverflow.com/a/1553668/3193156
  var e = event || window.event;
  var elem = e.target || e.srcElement;
  if (elem.nodeType == 3) {
    elem = elem.parentNode;
  } // Defeat Safari bug
  // Grab the elements inner HTML
  var html = elem.innerHTML
    // If html is empty or does not start with a div see if we need to fix something
  if (html == '' || html.substr(0, 5) != '
') {
    notify('Running editor checks.');
    var index;
    // Catch bug where a line break is added after a user uses backspace to wipe the editor
    if (html.substr(0, 4) == '
') {
      notify('Removed line break.');
      index = html.indexOf('\n');
      // If there are any lines after this line break save them
      if (index > -1) {
        html = html.substr(html.indexOf('\n') + 1);
      } else {
        html = '';
      }
      elem.innerHTML = html;
      // If everything is ok return otherwise keep processing
      if (html != '' && html.substr(0, 5) == '
') {
        return;
      }
    }
    // Catch bug where first line after erasing editor does not get wrapped
    index = html.indexOf('\n');
    if (index > -1) {
      notify('Wrapped the fist line, did not check the rest.');
      html = html = '
' + html.substr(0, html.indexOf('\n') + 1) + '
' + html.substr(html.indexOf('\n') + 1);
      elem.innerHTML = html;
      return;
    } else {
      html = html.trim();
      if (html.length > 0) {
        notify('Wrapped the fist line');
        html = '
' + html.trim() + '
';
        elem.innerHTML = html;
        return;
      }
    }
    // If we made it here the editor shold be considered empty, reset it
    notify('Editor reset.');
    var div = document.createElement('DIV');
    div.innerHTML = '
';
    elem.appendChild(div);
  }
}

function notify(msg) {
  var div = document.createElement('DIV');
  div.innerHTML = msg;
  document.getElementById('messages').appendChild(div);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#editor {
  width: 90%;
  height: 200px;
  padding: 1rem;
  border: 1px solid #000;
}</code>```

```

To-Do / Missing

This solution answers the OP and does not account for the following use cases:

Checking results after pasting in content; this would need to go line by line and wrap everything.

Checking any other lines after the first; not common but I believe you can end up with and un-wrapped line at the end of your content depending in browser.

Body:
I have a div with the attribute contentEditable set.

The trouble I am having is that the first line I type does not get wrapped in tags, but the subsequent lines do.

So typing:

qwerty
zxcv
asdfg

Results in:

    qwerty

zxcv

asdfg

So I need the qwerty line to become
qwerty

Body:
Context

This is a solution to the OP that ensures the first line in a content editable div always gets wrapped and fixes common bugs like:

Un-wrapped first line after erasing editor and immediately typing.

Line break added after erasing editor.

All of the issues mentioned by Kasper Fredenslund:

Ctrl + A + Del

Ctrl + A + Backspace

Ctrl + A + Any typing the user does

It uses event listeners to catch when a user focuses on the editor and when they leave. For more context please read the comments in the code.

Code

Below is a full working fiddle of the code. My original example can be found at this JS Fiddle page.

// On Dom Ready
document.getElementById('editor').addEventListener('focusin', checkEditor);
document.getElementById('editor').addEventListener('focusout', checkEditor);

function checkEditor() {
  // Get the DOM element that the user is in
  // Allows you to have multiple editos on one page
  // Next 3 lines of code from: https://stackoverflow.com/a/1553668/3193156
  var e = event || window.event;
  var elem = e.target || e.srcElement;
  if (elem.nodeType == 3) {
    elem = elem.parentNode;
  } // Defeat Safari bug
  // Grab the elements inner HTML
  var html = elem.innerHTML
    // If html is empty or does not start with a div see if we need to fix something
  if (html == '' || html.substr(0, 5) != '<div>') {
    notify('Running editor checks.');
    var index;
    // Catch bug where a line break is added after a user uses backspace to wipe the editor
    if (html.substr(0, 4) == '<br>') {
      notify('Removed line break.');
      index = html.indexOf('\n');
      // If there are any lines after this line break save them
      if (index > -1) {
        html = html.substr(html.indexOf('\n') + 1);
      } else {
        html = '';
      }
      elem.innerHTML = html;
      // If everything is ok return otherwise keep processing
      if (html != '' && html.substr(0, 5) == '<div>') {
        return;
      }
    }
    // Catch bug where first line after erasing editor does not get wrapped
    index = html.indexOf('\n');
    if (index > -1) {
      notify('Wrapped the fist line, did not check the rest.');
      html = html = '<div>' + html.substr(0, html.indexOf('\n') + 1) + '</div>' + html.substr(html.indexOf('\n') + 1);
      elem.innerHTML = html;
      return;
    } else {
      html = html.trim();
      if (html.length > 0) {
        notify('Wrapped the fist line');
        html = '<div>' + html.trim() + '</div>';
        elem.innerHTML = html;
        return;
      }
    }
    // If we made it here the editor shold be considered empty, reset it
    notify('Editor reset.');
    var div = document.createElement('DIV');
    div.innerHTML = '<br>';
    elem.appendChild(div);
  }
}

function notify(msg) {
  var div = document.createElement('DIV');
  div.innerHTML = msg;
  document.getElementById('messages').appendChild(div);
}

#editor {
  width: 90%;
  height: 200px;
  padding: 1rem;
  border: 1px solid #000;
}

<div id="editor" contenteditable="true">

</div>
<div id="messages">
</div>

To-Do / Missing

This solution answers the OP and does not account for the following use cases:

Checking results after pasting in content; this would need to go line by line and wrap everything.

Checking any other lines after the first; not common but I believe you can end up with and un-wrapped line at the end of your content depending in browser.


来源: stackexchange

问:
How to generate numbered list with line break using R whisker templating engine
I have the following data:

```<code>data <- list( name = "Chris",
             children_names = c("Alex", "John")
            )
</code>```

Using R's templating engine whisker, I want to get this output,
when rendered:

```<code>I am Chris
My children are:
    Child No 1 is Alex
    Child No 2 is John
</code>```

This is my current code:

```<code>library(whisker)
template <-
'I am {{name}}
My children are:
{{children_names}}
'

data <- list( name = "Chris",
             children_names = c("Alex", "John")

            )

text <- whisker.render(template, data)
cat(text)

# which produces:

# I am Chris
# My children are:
# Alex,John
</code>```

Which is not what I want.
What's the right way to do it?

答:
You probably already figured this out, but in case you haven't:</p>

```<code>library(whisker)

template <-
  'I am {{name}} \n
  My children are: \n
  {{#children_names}}
  Child No {{number}} is {{cname}}
  {{/children_names}}'

data <- list(
  name = "Chris",
  children_names = list(
    list(cname = "Alex", number = 1), list(cname = "John", number = 2)
  )
)

text <- whisker.render(template, data)
cat(text)

# I am Chris
#
# My children are:
#
# Child No 1 is Alex
# Child No 2 is John
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following data:

data <- list( name = "Chris",
             children_names = c("Alex", "John")
            )

Using R's templating engine whisker, I want to get this output,
when rendered:

I am Chris
My children are:
    Child No 1 is Alex
    Child No 2 is John

This is my current code:

library(whisker)
template <-
'I am {{name}}
My children are:
{{children_names}}
'

data <- list( name = "Chris",
             children_names = c("Alex", "John")

            )

text <- whisker.render(template, data)
cat(text)

# which produces:

# I am Chris
# My children are:
# Alex,John

Which is not what I want.
What's the right way to do it?

Body:
You probably already figured this out, but in case you haven't:

library(whisker)

template <-
  'I am {{name}} \n
  My children are: \n
  {{#children_names}}
  Child No {{number}} is {{cname}}
  {{/children_names}}'

data <- list(
  name = "Chris",
  children_names = list(
    list(cname = "Alex", number = 1), list(cname = "John", number = 2)
  )
)

text <- whisker.render(template, data)
cat(text)

# I am Chris
#
# My children are:
#
# Child No 1 is Alex
# Child No 2 is John


问:
Anyone please do have Netflow data using nfdump in csv file?

I had collected data using tcpdump but i want data from nfdump as a csv file.

答:
```<code>nfdump -r /tmp/nfcapd.201712052349 -o csv > /var/log/netflow/test.csv
</code>```


问:
Linq To SQL throws has no supported translation to SQL Exception when using generic Insert method
I have a method to insert entity to tables genericly using type T. But I want to add a feature to check if the entity to be added exists in the table based on a matcher property (e.g Name). When I execute the code it throws 'has no supported translation to SQL' on the check line. My code part is below. How can I fix this problem?</p>

```<code>    public static InsertStatus Add<T>(T ent, string matcherProp) where T : class
    {
        System.Data.Linq.Table<T> t = otdc.GetTable<T>();

        //Exception on this line
        if (t.Any(item => object.Equals(GetPropValue(item, matcherProp), GetPropValue(ent, matcherProp))))
            return InsertStatus.AlreadyExists;

        try
        {
            t.InsertOnSubmit(ent);
            otdc.SubmitChanges();
            return InsertStatus.Successfull;
        }
        catch
        {
            return InsertStatus.UnknownError;
        }
    }
    public static object GetPropValue(object src, string propName)
    {
        return src.GetType().GetProperty(propName).GetValue(src, null);
    }
</code>```

答:
Instead of making matcherProp a string, consider making it an Expression<Func<T, P>> so you can invoke it as:  Add(myEntity, e => e.Name).

Then you need something like

```<code>public static InsertStatus Add<T>(T ent, Expression<Func<T,P>> keySelector) where P : class
{
    System.Data.Linq.Table<T> t = otdc.GetTable<T>();

    var memberAccess = (keySelector as LambdaExpression)?.Body as MemberExpression;
    ParameterExpression paramExpr = Expression.Parameter(typeof(T), "e");
    Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T,bool>>(
            Expression.Equal(memberAccess.Update(Expression.Constant(ent)), memberAccess.Update(paramExpr)), paramExpr);

    if (t.Any(predicate))
    {
</code>```

With appropriate error checking of course.

Body:
I have a method to insert entity to tables genericly using type T. But I want to add a feature to check if the entity to be added exists in the table based on a matcher property (e.g Name). When I execute the code it throws 'has no supported translation to SQL' on the check line. My code part is below. How can I fix this problem?

    public static InsertStatus Add<T>(T ent, string matcherProp) where T : class
    {
        System.Data.Linq.Table<T> t = otdc.GetTable<T>();

        //Exception on this line
        if (t.Any(item => object.Equals(GetPropValue(item, matcherProp), GetPropValue(ent, matcherProp))))
            return InsertStatus.AlreadyExists;

        try
        {
            t.InsertOnSubmit(ent);
            otdc.SubmitChanges();
            return InsertStatus.Successfull;
        }
        catch
        {
            return InsertStatus.UnknownError;
        }
    }
    public static object GetPropValue(object src, string propName)
    {
        return src.GetType().GetProperty(propName).GetValue(src, null);
    }

Body:
Instead of making matcherProp a string, consider making it an Expression<Func<T, P>> so you can invoke it as:  Add(myEntity, e => e.Name).

Then you need something like

public static InsertStatus Add<T>(T ent, Expression<Func<T,P>> keySelector) where P : class
{
    System.Data.Linq.Table<T> t = otdc.GetTable<T>();

    var memberAccess = (keySelector as LambdaExpression)?.Body as MemberExpression;
    ParameterExpression paramExpr = Expression.Parameter(typeof(T), "e");
    Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T,bool>>(
            Expression.Equal(memberAccess.Update(Expression.Constant(ent)), memberAccess.Update(paramExpr)), paramExpr);

    if (t.Any(predicate))
    {

With appropriate error checking of course.


问:
Why does java accept Long format with underscore, but it doesn't parse it using String?
I am aware of the fact that this format long val = 1_000_000L; is valid in java, but what I found non constitent is the behaviour of the Long#parseLong method that does not parse this format if it is passed as a String, I tried the below code and I always get the exception:

```<code>   String h = "1_000_000L";
    long val = 1_000_000L;
    System.out.printf("this a valid format : %d\n", val);
    try {
        Long m = Long.parseLong(h);
        System.out.println(m);
    } catch (NumberFormatException e) {
        System.out.printf("cannot parse this number : %s\n", h);
    }
</code>```

NB. I am building something like a personal java compiler and I want that it works without getting rid of the underscore format.

答:
There never was a requirement that numeric literal that you can type in source code would work the same way as numbers parsed from a String.

Here is the Javadocs of Long.parseLong:

The characters in the string must all be decimal digits, except that
  the first character may be an ASCII minus sign '-' (\u002D') to
  indicate a negative value or an ASCII plus sign '+' ('\u002B') to
  indicate a positive value.

So not only are underscores not allowed, but the L suffix also.  It's not meant to parse numbers of the format from source code.

The underscores in numeric literals were introduced in Java 7, but only to improve readability of source code, not programmatic parsing of strings.

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.

These features are entirely separate and were never meant to be consistent with each other.

The NumberFormatException you got is expected and it is working correctly.

Body:
I am aware of the fact that this format long val = 1_000_000L; is valid in java, but what I found non constitent is the behaviour of the Long#parseLong method that does not parse this format if it is passed as a String, I tried the below code and I always get the exception:

   String h = "1_000_000L";
    long val = 1_000_000L;
    System.out.printf("this a valid format : %d\n", val);
    try {
        Long m = Long.parseLong(h);
        System.out.println(m);
    } catch (NumberFormatException e) {
        System.out.printf("cannot parse this number : %s\n", h);
    }

NB. I am building something like a personal java compiler and I want that it works without getting rid of the underscore format.


问:
Using Switch-blocks to Parse input for a Text Adventure?
Okay, I have a goal right now to make a basic text adventure. To do this, however, I would need/want to have a switch statement that can do the following:

Check to see if a string has a word SOMEWHERE inside.

Check to see if a string has two words in any combination somewhere inside.

How would I accomplish this? Could you show me coding for this specific example:

A user is prompted for data. A switch statement checks for "look box" as one case, and "sleep" as another. The program doesn't care what order any words are in, but does care about the order of the letters.

Please explain everything in detail. I just started coding.

EDIT: Thank you for all the answers. I understand there are better, more complicated, and more useful ways of handling this, but it just isn't at my level yet.

答:
Here's another idea:

```<code>    string input = "look at the sleep box";
    bool caseA = input.Contains("sleep");
    bool caseB = input.Contains("look") && input.Contains("box");

    int scenarioId;
    if (caseA && caseB)
        scenarioId = 1;
    else if (caseA)
        scenarioId = 2;
    else if (caseB)
        scenarioId = 3;
    // more logic?
    else
        scenarioId = 0;

    switch (scenarioId)
    {
        case 1:
            Console.WriteLine("Do scenario 1");
            break;
        case 2:
            Console.WriteLine("Do scenario 2");
            break;
        case 3:
            Console.WriteLine("Do scenario 3");
            break;
        // more cases
        default:
            Console.WriteLine("???");
            break;
    }
</code>```

It uses if/then/else to assess a particular scenario including potential combinations such as input like "look at the sleep box" and then uses a switch statement to execute accordingly.

Body:
Here's another idea:

    string input = "look at the sleep box";
    bool caseA = input.Contains("sleep");
    bool caseB = input.Contains("look") && input.Contains("box");

    int scenarioId;
    if (caseA && caseB)
        scenarioId = 1;
    else if (caseA)
        scenarioId = 2;
    else if (caseB)
        scenarioId = 3;
    // more logic?
    else
        scenarioId = 0;

    switch (scenarioId)
    {
        case 1:
            Console.WriteLine("Do scenario 1");
            break;
        case 2:
            Console.WriteLine("Do scenario 2");
            break;
        case 3:
            Console.WriteLine("Do scenario 3");
            break;
        // more cases
        default:
            Console.WriteLine("???");
            break;
    }

It uses if/then/else to assess a particular scenario including potential combinations such as input like "look at the sleep box" and then uses a switch statement to execute accordingly.

ContentLicense: CC BY-SA 2.5


问:
How to create draft pages with dependent elements in insert-only database
I have an insert-only PostgreSQL database with a Book table, a Page table and an Element table.
Books can have multiple pages and pages can have multiple elements.
The database is insert-only because any time a page is modified, a new version of that page is created in a new record for auditing reasons.

```<code>-------------
Book
-------------
id [PK]

-------------
Page
-------------
id [PK]
book_id [FK]
version
created

-------------
Element
-------------
id [PK]
page_id [FK]
version
created
</code>```

Currently, Element has a Foreign Key pointing to Page.id and Page has a Foreign Key pointing to Book.id.

A requirement is to have independent page drafts (versions) that can contain any number of elements. Every time a new page draft (version) is created, the new draft should be a clone of the previous version and it should contain all elements in the previous version. Elements can be added to or removed from a specific version of the Page, although Elements records are never deleted.

For scalibility reasons, I would avoid cloning all the elements together with the page, since the elements could be a very large number. I would also what to avoid many-to-many relationships between pages and elements.

I was thinking about replacing the Element.page_id FK with an Element.book_id FK so to have a single bucket of elements and pages more loosely coupled with each other. This way, when cloning a page, I wouldn't have to clone all the elements, but I would need a way to associate each element with a particular version of a Page.

Ideally, I should be able to retrieve a page version with all the elements associated to that version with a single SQL query.

I am still in a design/prototyping phase, so any aspect of the databse can potentially be changed to fulfill the requirements.

What could be the best way to associate Pages and Elements according to the requirements above? I hope the requirements are clear, if not, please ask any questions and I'll try to clarify.

Note: by "insert-only" database I mean a database where no record gets ever updated or deleted, only inserted. This is for auditing purposes so we can have a full history of any editing activity.

答:
Possible solution is using Unary Relationship on Pages (each Page has parent Page_id).

You can insert each new Pages with it's own Elements. (with null parent)

If any new versions of existing Pages coming, you can insert new Page with parent Page id.

There is no need to set Elements of parent Page to new Page. (the Page can retrieve them from parent Page)

If new version has it's specific Elements, you can set them to new coming Page.

and so on.

Note that, PostgreSQL has remarkable performances in recursive queries.

Body:
I have an insert-only PostgreSQL database with a Book table, a Page table and an Element table.
Books can have multiple pages and pages can have multiple elements.
The database is insert-only because any time a page is modified, a new version of that page is created in a new record for auditing reasons.

-------------
Book
-------------
id [PK]

-------------
Page
-------------
id [PK]
book_id [FK]
version
created

-------------
Element
-------------
id [PK]
page_id [FK]
version
created

Currently, Element has a Foreign Key pointing to Page.id and Page has a Foreign Key pointing to Book.id.

A requirement is to have independent page drafts (versions) that can contain any number of elements. Every time a new page draft (version) is created, the new draft should be a clone of the previous version and it should contain all elements in the previous version. Elements can be added to or removed from a specific version of the Page, although Elements records are never deleted.

For scalibility reasons, I would avoid cloning all the elements together with the page, since the elements could be a very large number. I would also what to avoid many-to-many relationships between pages and elements.

I was thinking about replacing the Element.page_id FK with an Element.book_id FK so to have a single bucket of elements and pages more loosely coupled with each other. This way, when cloning a page, I wouldn't have to clone all the elements, but I would need a way to associate each element with a particular version of a Page.

Ideally, I should be able to retrieve a page version with all the elements associated to that version with a single SQL query.

I am still in a design/prototyping phase, so any aspect of the databse can potentially be changed to fulfill the requirements.

What could be the best way to associate Pages and Elements according to the requirements above? I hope the requirements are clear, if not, please ask any questions and I'll try to clarify.

Note: by "insert-only" database I mean a database where no record gets ever updated or deleted, only inserted. This is for auditing purposes so we can have a full history of any editing activity.


问:
Hibernate hangs during SELECT with SQL server
I'm adding support to our application to use SQL Server (it already works fine with MySQL) and hitting a problem with Hibernate/JDBC queries hanging after a few successes.  In this case the database is completely empty to start with.  The problem occurs while we are loading data into the database.

Again this works fine with MySQL.

Here's the hibernate sql statements (hangs on last entry):

```<code>Hibernate: select permission0_.dbID as dbID1_73_, permission0_.Created as Created2_73_, permission0_.dbVersion as dbVersio3_73_, permission0_.Origin as Origin4_73_, permission0_.Updated as Updated5_73_, permission0_.Entity as Entity6_73_ from Permission permission0_ where permission0_.Entity=?
Hibernate: select permission0_.dbID as dbID1_73_, permission0_.Created as Created2_73_, permission0_.dbVersion as dbVersio3_73_, permission0_.Origin as Origin4_73_, permission0_.Updated as Updated5_73_, permission0_.Entity as Entity6_73_ from Permission permission0_ where permission0_.Entity=?
Hibernate: select next value for hibernate_sequence
Hibernate: insert into Permission (Created, dbVersion, Origin, Updated, Entity, dbID) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into Permission_Operations (Permission_id, T_element) values (?, ?)
Hibernate: select permission0_.dbID as dbID1_73_, permission0_.Created as Created2_73_, permission0_.dbVersion as dbVersio3_73_, permission0_.Origin as Origin4_73_, permission0_.Updated as Updated5_73_, permission0_.Entity as Entity6_73_ from Permission permission0_ where permission0_.Entity=?
Hibernate: select permission0_.dbID as dbID1_73_, permission0_.Created as Created2_73_, permission0_.dbVersion as dbVersio3_73_, permission0_.Origin as Origin4_73_, permission0_.Updated as Updated5_73_, permission0_.Entity as Entity6_73_ from Permission permission0_ where permission0_.Entity=?
</code>```

When I use SQL Server Studio I see the last query as State=SUSPENDED and Wait=LCK_M_S (see image below).

The last query will never finish/return.  I have left it running as much as 12 hours.  I did add a time-out of 60 seconds using javax.persistence.query.timeout hint with the Query just so it didn't hang forever.

Configuration:

SQL Server 2017

Hibernate 4.3.11.Final

SQL Server Connector for JDBC 6.2.1.jre8

Oracle Java 8

My persistence.xml:

```<code>        <property name="hibernate.hbm2ddl.auto" value="update" />
        <property name="hibernate.id.new_generator_mappings" value="true" />
        <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
        <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
        <property name="hibernate.c3p0.acquire_increment" value="1" />
        <property name="hibernate.c3p0.min_size" value="5" />
        <property name="hibernate.c3p0.max_size" value="25" />
        <property name="hibernate.c3p0.max_statements" value="50" />
        <property name="hibernate.c3p0.validate" value="true" />
        <!-- Tried with and without this:
        <property name="hibernate.c3p0.preferredTestQuery" value="SELECT 1" />
        -->
</code>```

I also programetically set these values:

```<code>hibernate.connection.driver_class  : com.microsoft.sqlserver.jdbc.SQLServerDriver
hibernate.connection.password      : <MASKED>
hibernate.connection.url           : jdbc:sqlserver://sqlserver:1433;databaseName=xxx_test0
hibernate.connection.username      : xxx
hibernate.dialect                  : org.hibernate.dialect.SQLServer2012Dialect
hibernate.show_sql                 : true
</code>```

答:
I figured out the problem.  I was not doing a commit after the inserts but before the next select.  For some reason MySQL was fine with this, but SQL Server wanted to wait.

Adding a commit after all the inserts completed solved the problem.

Body:
I'm adding support to our application to use SQL Server (it already works fine with MySQL) and hitting a problem with Hibernate/JDBC queries hanging after a few successes.  In this case the database is completely empty to start with.  The problem occurs while we are loading data into the database.

Again this works fine with MySQL.

Here's the hibernate sql statements (hangs on last entry):

Hibernate: select permission0_.dbID as dbID1_73_, permission0_.Created as Created2_73_, permission0_.dbVersion as dbVersio3_73_, permission0_.Origin as Origin4_73_, permission0_.Updated as Updated5_73_, permission0_.Entity as Entity6_73_ from Permission permission0_ where permission0_.Entity=?
Hibernate: select permission0_.dbID as dbID1_73_, permission0_.Created as Created2_73_, permission0_.dbVersion as dbVersio3_73_, permission0_.Origin as Origin4_73_, permission0_.Updated as Updated5_73_, permission0_.Entity as Entity6_73_ from Permission permission0_ where permission0_.Entity=?
Hibernate: select next value for hibernate_sequence
Hibernate: insert into Permission (Created, dbVersion, Origin, Updated, Entity, dbID) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into Permission_Operations (Permission_id, T_element) values (?, ?)
Hibernate: select permission0_.dbID as dbID1_73_, permission0_.Created as Created2_73_, permission0_.dbVersion as dbVersio3_73_, permission0_.Origin as Origin4_73_, permission0_.Updated as Updated5_73_, permission0_.Entity as Entity6_73_ from Permission permission0_ where permission0_.Entity=?
Hibernate: select permission0_.dbID as dbID1_73_, permission0_.Created as Created2_73_, permission0_.dbVersion as dbVersio3_73_, permission0_.Origin as Origin4_73_, permission0_.Updated as Updated5_73_, permission0_.Entity as Entity6_73_ from Permission permission0_ where permission0_.Entity=?

When I use SQL Server Studio I see the last query as State=SUSPENDED and Wait=LCK_M_S (see image below).

The last query will never finish/return.  I have left it running as much as 12 hours.  I did add a time-out of 60 seconds using javax.persistence.query.timeout hint with the Query just so it didn't hang forever.

Configuration:

SQL Server 2017

Hibernate 4.3.11.Final

SQL Server Connector for JDBC 6.2.1.jre8

Oracle Java 8

My persistence.xml:

        <property name="hibernate.hbm2ddl.auto" value="update" />
        <property name="hibernate.id.new_generator_mappings" value="true" />
        <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
        <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
        <property name="hibernate.c3p0.acquire_increment" value="1" />
        <property name="hibernate.c3p0.min_size" value="5" />
        <property name="hibernate.c3p0.max_size" value="25" />
        <property name="hibernate.c3p0.max_statements" value="50" />
        <property name="hibernate.c3p0.validate" value="true" />

I also programetically set these values:

hibernate.connection.driver_class  : com.microsoft.sqlserver.jdbc.SQLServerDriver
hibernate.connection.password      : <MASKED>
hibernate.connection.url           : jdbc:sqlserver://sqlserver:1433;databaseName=xxx_test0
hibernate.connection.username      : xxx
hibernate.dialect                  : org.hibernate.dialect.SQLServer2012Dialect
hibernate.show_sql                 : true


问:
Kotlin generic type issue
I'm lost in generic types many hours. I want to simplified the code but I can't cast object when its generic type. How I can solve this problem or another simplified way? (I'm use kotlin 1.2)

```<code>sealed class SETTING(override val key: String) : SettingsKeyContract

object optFirstLaunch : SETTING("first_launch"), SettingsKeyContractWithType<Boolean> {
    override val defaults = true
}

object optNotifications : SETTING("notification_list"), SettingsKeyContractWithType<List<String>> {
    override val defaults = emptyList<String>()
}

interface SettingsKeyContract { val key: String }
interface SettingsKeyContractWithType<T : Any> : SettingsKeyContract {

    val defaults: T

    @Suppress("UNCHECKED_CAST")
    fun get(): T?       = (App.getContentComponent()?.getSettings()?.get(key)?.value?.data as? T)
    fun remove()        = (App.getContentComponent()?.getSettings())?.delete(key)
    fun save(value: T)  = (App.getContentComponent()?.getSettings()?.add(key, value))

}

class OptionModel(@OPTIONS_ID optionId: Int, contract: SettingsKeyContract)

val optionModel = OptionModel(1, optNotifications)
when(optionModel.contract){
    is SettingsKeyContractWithType<List<String>> -> (optionModel.contract as SettingsKeyContractWithType<List<String>>).set(listOf("ring-1", "ring-2")) //error
    is SettingsKeyContractWithType<Boolean> -> (optionModel.contract as SettingsKeyContractWithType<Boolean>).set(true)  //error
}
</code>```

Error:

```<code>Cannot check for instance of erased type: SettingsKeyContractWithType<...>
</code>```

答:
Please take a look at the explanation of type erasure and type checks for generic types in the language reference: Type erasure and generic type checks.

Basically, you cannot do that sort of check because the instances of SettingsKeyContractWithType do not hold any information about their actual type argument at runtime.

An option that you could try here is to add make SettingsKeyContractWithType explicitly store some representation of the type argument. A simple KClass does not seem to fit, because it cannot represent a concrete generic type (you cannot have a KClass for List<String>.

If that's really what you want, consider using the technique of super type tokens, as described here: (link).

You can add a TypeReference<T> property to SettingsKeyContractWithType, fill it within an inline factory function with a reified type parameter.

Title: Kotlin generic type issue

Body:
I'm lost in generic types many hours. I want to simplified the code but I can't cast object when its generic type. How I can solve this problem or another simplified way? (I'm use kotlin 1.2)

sealed class SETTING(override val key: String) : SettingsKeyContract

object optFirstLaunch : SETTING("first_launch"), SettingsKeyContractWithType<Boolean> {
    override val defaults = true
}

object optNotifications : SETTING("notification_list"), SettingsKeyContractWithType<List<String>> {
    override val defaults = emptyList<String>()
}

interface SettingsKeyContract { val key: String }
interface SettingsKeyContractWithType<T : Any> : SettingsKeyContract {

    val defaults: T

    @Suppress("UNCHECKED_CAST")
    fun get(): T?       = (App.getContentComponent()?.getSettings()?.get(key)?.value?.data as? T)
    fun remove()        = (App.getContentComponent()?.getSettings())?.delete(key)
    fun save(value: T)  = (App.getContentComponent()?.getSettings()?.add(key, value))

}

class OptionModel(@OPTIONS_ID optionId: Int, contract: SettingsKeyContract)

val optionModel = OptionModel(1, optNotifications)
when(optionModel.contract){
    is SettingsKeyContractWithType<List<String>> -> (optionModel.contract as SettingsKeyContractWithType<List<String>>).set(listOf("ring-1", "ring-2")) //error
    is SettingsKeyContractWithType<Boolean> -> (optionModel.contract as SettingsKeyContractWithType<Boolean>).set(true)  //error
}

Error:

Cannot check for instance of erased type: SettingsKeyContractWithType<...>


问:
Use a Form response to create a folder in Drive when form is submitted
I have a Google form, first question is "Client Name" I would like my script to create a folder in Drive and have the name of the folder be the response to the "Client Name" question.

```<code> function main() {

var form = FormApp.getActiveForm();
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
  var formResponse = formResponses[i];
  var itemResponses = formResponse.getItemResponses();
for (var j = 0; j < itemResponses.length; j++)
  var itemResponse = itemResponses[j];
 }
     DriveApp.getRootFolder().createFolder(itemResponse);

}
</code>```

I've been trying different combinations of this but have had no success.

答:
You have to use a on form submit event. Assuming that the Client Name is the first question, then the following on form submit installable trigger added to the form will create the folder with the given name:

```<code>function createFolder(e) {
  var items = e.response.getItemResponses()
  var name = items[0].getResponse();
  DriveApp.createFolder(name);
}
</code>```

Related

How to get form values in the submit event handler?

Body:
I have a Google form, first question is "Client Name" I would like my script to create a folder in Drive and have the name of the folder be the response to the "Client Name" question.

 function main() {

var form = FormApp.getActiveForm();
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
  var formResponse = formResponses[i];
  var itemResponses = formResponse.getItemResponses();
for (var j = 0; j < itemResponses.length; j++)
  var itemResponse = itemResponses[j];
 }
     DriveApp.getRootFolder().createFolder(itemResponse);

}

I've been trying different combinations of this but have had no success.

Body:
You have to use a on form submit event. Assuming that the Client Name is the first question, then the following on form submit installable trigger added to the form will create the folder with the given name:

function createFolder(e) {
  var items = e.response.getItemResponses()
  var name = items[0].getResponse();
  DriveApp.createFolder(name);
}

Related

How to get form values in the submit event handler?


问:
Angular 4; paginator's "items per page" translation
I'm using material design on Angular 4. I have a table with paginator on the bottom:

Is there any way to translate "Items per page" in Angular4?

I got access to this label by

```<code>this.paginator._intl.itemsPerPageLabel
</code>```

in .ts file of my component, which I put in ngOnInit()

I also have translations in i18n fo .json file, which structure is:

```<code>"MESSAGES_LIST_TABLE": {
      "DATE": "Date",
      "FROM": "From",
      "TO": "To",
      "MESSAGE": "Message",
      "AMOUNT": "Amount",
      "BALANCE": "Balance",
      "AVAILABLE_BALANCE": "Avail. bal",
      "ITEMS_PER_PAGE": "Items per page"
}
</code>```

Can I somehow translate it like this?

```<code>this.paginator._intl.itemsPerPageLabel = {{'CUSTOMER.MESSAGES_LIST_TABLE.ITEMS_PER_PAGE' | translate}}
</code>```

答: Create a new instance of MatPaginatorIntl and include it in a custom provider as explained in angular material documentation.</p>

Body:
I'm using material design on Angular 4. I have a table with paginator on the bottom:

Is there any way to translate "Items per page" in Angular4?

I got access to this label by

this.paginator._intl.itemsPerPageLabel

in .ts file of my component, which I put in ngOnInit()

I also have translations in i18n fo .json file, which structure is:

"MESSAGES_LIST_TABLE": {
      "DATE": "Date",
      "FROM": "From",
      "TO": "To",
      "MESSAGE": "Message",
      "AMOUNT": "Amount",
      "BALANCE": "Balance",
      "AVAILABLE_BALANCE": "Avail. bal",
      "ITEMS_PER_PAGE": "Items per page"
}

Can I somehow translate it like this?

this.paginator._intl.itemsPerPageLabel = {{'CUSTOMER.MESSAGES_LIST_TABLE.ITEMS_PER_PAGE' | translate}}


问:
My shooting script does not work after respawning
I have a character who is able to shoot; however, when the character dies and respawns he is unable to shoot and I get the error:

```<code>UnassignedReferenceException: The variable BulletTrailPrefab of Weapon has not been assigned.
</code>```

You probably need to assign the BulletTrailPrefab variable of the Weapon script in the inspector.

```<code>UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineObject.cs:74)

UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineObject.cs:84)

Weapon.Effect () (at Assets/Weapon.cs:64)

Weapon.Shoot () (at Assets/Weapon.cs:53)

Weapon.Update () (at Assets/Weapon.cs:33)
</code>```

If someone can help me fixing this it would be greatly appreciated. I have tried lots of stuff however nothing appears to work.

My weapon script

```<code>using UnityEngine;
using System.Collections;

public class Weapon : MonoBehaviour {

    public float fireRate = 0;
    public float Damage = 10;
    public LayerMask whatToHit;

    public Transform target;

    public Transform BulletTrailPrefab;
    float timeToSpawnEffect = 0;
    public float effectSpawnRate = 10;

    float timeToFire = 0;
    Transform firePoint;

    float nextTimeToSearch = 0;

    // Use this for initialization
    void Awake () {
        firePoint = transform.FindChild ("firePoint");
        if (firePoint == null) {
            Debug.LogError ("No firePoint? WHAT?!");
        }
    }

    // Update is called once per frame
    void Update () {
        if (fireRate == 0) {
            if (Input.GetButtonDown ("Fire1")) {
                Shoot();
            }
        }
        else {
            if (Input.GetButton ("Fire1") && Time.time > timeToFire) {
                timeToFire = Time.time + 1/fireRate;
                Shoot();
            }
        }
        if (target == null) {
            FindBulletTrailPrefab ();
            return;
        }
    }

    void Shoot () {
        Vector2 mousePosition = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
        Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);
        RaycastHit2D hit = Physics2D.Raycast (firePointPosition, mousePosition-firePointPosition, 100, whatToHit);
        if (Time.time >= timeToSpawnEffect) {
            Effect ();
            timeToSpawnEffect = Time.time + 1/effectSpawnRate;
        }
        Debug.DrawLine (firePointPosition, (mousePosition-firePointPosition)*100, Color.cyan);
        if (hit.collider != null) {
            Debug.DrawLine (firePointPosition, hit.point, Color.red);
            Debug.Log ("We hit " + hit.collider.name + " and did " + Damage + " damage.");
        }
    }

    void Effect () {
        Instantiate (BulletTrailPrefab, firePoint.position, firePoint.rotation);
    }
    void FindBulletTrailPrefab () {
        if (nextTimeToSearch <= Time.time) {
            GameObject searchResult = GameObject.FindGameObjectWithTag ("BulletTrail");
            if (searchResult != null)
                target = searchResult.transform;
            nextTimeToSearch = Time.time + 0.5f;
        }
    }
}
</code>```

My gamemaster script

```<code>    using UnityEngine;
    using System.Collections;

    public class GameMaster : MonoBehaviour {

        public static GameMaster gm;

        void Start () {
            if (gm == null) {
                gm = GameObject.FindGameObjectWithTag ("GM").GetComponent<GameMaster>();
            }
        }

        public Transform playerPrefab;
        public Transform spawnPoint;
        public int spawnDelay = 2;

        public IEnumerator RespawnPlayer () {
            Debug.Log ("TODO: Add waiting for spawn sound");
            yield return new WaitForSeconds (spawnDelay);

            Instantiate (playerPrefab, spawnPoint.position, spawnPoint.rotation);
            Debug.Log ("TODO: Add Spawn Particles");
        }

        public static void KillPlayer (Player player) {
            Destroy (player.gameObject);
            gm.StartCoroutine (gm.RespawnPlayer());
        }
    }
</code>```

My player script

```<code>    using UnityEngine;
    using System.Collections;

    public class Player : MonoBehaviour {

        [System.Serializable]
        public class PlayerStats {
            public int Health = 100;
        }

        public PlayerStats playerStats = new PlayerStats();

        public int fallBoundary = -20;

        void Update () {
            if (transform.position.y <= fallBoundary)
                DamagePlayer (9999999);
        }

        public void DamagePlayer (int damage) {
            playerStats.Health -= damage;
            if (playerStats.Health <= 0) {
                GameMaster.KillPlayer(this);
            }
        }
    }
</code>```

答:
Late answer for answering's sake! (Lovely!)

The reason it only happens after you respawn is because when you instantiate a new playerPrefab, the Weapon object (which presumably is part of your player prefab) does not have the assignments you had made in the editor—those assignments are only for the specific instances that were in the editor. You'll need to manually assign it at runtime in one of two ways:

1) When you respawn:

```<code>public IEnumerator RespawnPlayer () {
    // ...
    GameObject playerInstance = Instantiate (
        playerPrefab,
        spawnPoint.position,
        spawnPoint.rotation) as GameObject;
    Weapon weaponInstance = playerInstance.GetComponentInChildren<Weapon>;
    weaponInstance.BulletTrailPrefab = /* prefab reference */;
    // ...
}
</code>```

2) In your Weapon script:

```<code>void Start () {
    BulletTrailPrefab = /* prefab reference */;
}
</code>```

But in either case you would have to have some way of referencing the prefab at runtime, such as putting a reference into the GameMaster script or using Resources.Load().

ContentLicense: CC BY-SA 4.0

Body:
I have a character who is able to shoot; however, when the character dies and respawns he is unable to shoot and I get the error:

UnassignedReferenceException: The variable BulletTrailPrefab of Weapon has not been assigned.

You probably need to assign the BulletTrailPrefab variable of the Weapon script in the inspector.

UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineObject.cs:74)

UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineObject.cs:84)

Weapon.Effect () (at Assets/Weapon.cs:64)

Weapon.Shoot () (at Assets/Weapon.cs:53)

Weapon.Update () (at Assets/Weapon.cs:33)

If someone can help me fixing this it would be greatly appreciated. I have tried lots of stuff however nothing appears to work.

My weapon script

using UnityEngine;
using System.Collections;

public class Weapon : MonoBehaviour {

    public float fireRate = 0;
    public float Damage = 10;
    public LayerMask whatToHit;

    public Transform target;

    public Transform BulletTrailPrefab;
    float timeToSpawnEffect = 0;
    public float effectSpawnRate = 10;

    float timeToFire = 0;
    Transform firePoint;

    float nextTimeToSearch = 0;

    // Use this for initialization
    void Awake () {
        firePoint = transform.FindChild ("firePoint");
        if (firePoint == null) {
            Debug.LogError ("No firePoint? WHAT?!");
        }
    }

    // Update is called once per frame
    void Update () {
        if (fireRate == 0) {
            if (Input.GetButtonDown ("Fire1")) {
                Shoot();
            }
        }
        else {
            if (Input.GetButton ("Fire1") && Time.time > timeToFire) {
                timeToFire = Time.time + 1/fireRate;
                Shoot();
            }
        }
        if (target == null) {
            FindBulletTrailPrefab ();
            return;
        }
    }

    void Shoot () {
        Vector2 mousePosition = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
        Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);
        RaycastHit2D hit = Physics2D.Raycast (firePointPosition, mousePosition-firePointPosition, 100, whatToHit);
        if (Time.time >= timeToSpawnEffect) {
            Effect ();
            timeToSpawnEffect = Time.time + 1/effectSpawnRate;
        }
        Debug.DrawLine (firePointPosition, (mousePosition-firePointPosition)*100, Color.cyan);
        if (hit.collider != null) {
            Debug.DrawLine (firePointPosition, hit.point, Color.red);
            Debug.Log ("We hit " + hit.collider.name + " and did " + Damage + " damage.");
        }
    }

    void Effect () {
        Instantiate (BulletTrailPrefab, firePoint.position, firePoint.rotation);
    }
    void FindBulletTrailPrefab () {
        if (nextTimeToSearch <= Time.time) {
            GameObject searchResult = GameObject.FindGameObjectWithTag ("BulletTrail");
            if (searchResult != null)
                target = searchResult.transform;
            nextTimeToSearch = Time.time + 0.5f;
        }
    }
}

My gamemaster script

    using UnityEngine;
    using System.Collections;

    public class GameMaster : MonoBehaviour {

        public static GameMaster gm;

        void Start () {
            if (gm == null) {
                gm = GameObject.FindGameObjectWithTag ("GM").GetComponent<GameMaster>();
            }
        }

        public Transform playerPrefab;
        public Transform spawnPoint;
        public int spawnDelay = 2;

        public IEnumerator RespawnPlayer () {
            Debug.Log ("TODO: Add waiting for spawn sound");
            yield return new WaitForSeconds (spawnDelay);

            Instantiate (playerPrefab, spawnPoint.position, spawnPoint.rotation);
            Debug.Log ("TODO: Add Spawn Particles");
        }

        public static void KillPlayer (Player player) {
            Destroy (player.gameObject);
            gm.StartCoroutine (gm.RespawnPlayer());
        }
    }

My player script

    using UnityEngine;
    using System.Collections;

    public class Player : MonoBehaviour {

        [System.Serializable]
        public class PlayerStats {
            public int Health = 100;
        }

        public PlayerStats playerStats = new PlayerStats();

        public int fallBoundary = -20;

        void Update () {
            if (transform.position.y <= fallBoundary)
                DamagePlayer (9999999);
        }

        public void DamagePlayer (int damage) {
            playerStats.Health -= damage;
            if (playerStats.Health <= 0) {
                GameMaster.KillPlayer(this);
            }
        }
    }

Body:
Late answer for answering's sake! (Lovely!)

The reason it only happens after you respawn is because when you instantiate a new playerPrefab, the Weapon object (which presumably is part of your player prefab) does not have the assignments you had made in the editor—those assignments are only for the specific instances that were in the editor. You'll need to manually assign it at runtime in one of two ways:

1) When you respawn:

public IEnumerator RespawnPlayer () {
    // ...
    GameObject playerInstance = Instantiate (
        playerPrefab,
        spawnPoint.position,
        spawnPoint.rotation) as GameObject;
    Weapon weaponInstance = playerInstance.GetComponentInChildren<Weapon>;
    weaponInstance.BulletTrailPrefab = /* prefab reference */;
    // ...
}

2) In your Weapon script:

void Start () {
    BulletTrailPrefab = /* prefab reference */;
}

But in either case you would have to have some way of referencing the prefab at runtime, such as putting a reference into the GameMaster script or using Resources.Load().


问:
Keep getting runtime error - Script out of range- on Access VBA
Trying to pull input from two text boxes using an array and build a message box with the list. Upon opening the form asks "how many names" to add to the list, then holds that number. You then click "Add name" up until the name count hits 5. Then it should have a message box pop up saying the list is full.

```<code>Option Compare Database
Option Explicit

Dim intItems As Integer

Dim strFName() As String, strLName() As String

Private Sub Form_Load()
intItems = Val(InputBox("How many names?", "Name  Count"))
Do While intItems <= 0
MsgBox "Please provide a number greater than 0", vbCritical, "Correct Value
Required"
intItems = Val(InputBox("How many names do you have?", "Name List"))
Loop
ReDim strFName(intItems - 1)
End Sub

Private Sub cmdAddName_Click()
Dim intI As Integer
If IsNull(Me.txtFirstName.Value) Or IsNull(Me.txtLastName.Value) = True Then
MsgBox "There must be values for both First and Last names", vbCritical,
"Data Entry Error"
Else
If strFName(intItems - 1) <> "" Then
MsgBox "Sorry, the list is full!"
Me.txtFirstName.Value = Null
Me.txtLastName.Value = Null
Else
For intI = 0 To intItems - 1
If strFName(intI) = "" Then
strFName(intI) = Me.txtFirstName.Value
strLName(intI) = Me.txtLastName.Value
Me.txtFirstName.Value = Null
Me.txtLastName.Value = Null
Exit For
End If
Next
End If
End If
End Sub
</code>```

I get a runtime error "Script out of range" on 'If strFName(intItems - 1) <> "" Then anyone have any ideas as to why?

答: you forgot to reDim the other array and reset the data type of the array</p>

Body:
Trying to pull input from two text boxes using an array and build a message box with the list. Upon opening the form asks "how many names" to add to the list, then holds that number. You then click "Add name" up until the name count hits 5. Then it should have a message box pop up saying the list is full.

Option Compare Database
Option Explicit

Dim intItems As Integer

Dim strFName() As String, strLName() As String

Private Sub Form_Load()
intItems = Val(InputBox("How many names?", "Name  Count"))
Do While intItems <= 0
MsgBox "Please provide a number greater than 0", vbCritical, "Correct Value
Required"
intItems = Val(InputBox("How many names do you have?", "Name List"))
Loop
ReDim strFName(intItems - 1)
End Sub

Private Sub cmdAddName_Click()
Dim intI As Integer
If IsNull(Me.txtFirstName.Value) Or IsNull(Me.txtLastName.Value) = True Then
MsgBox "There must be values for both First and Last names", vbCritical,
"Data Entry Error"
Else
If strFName(intItems - 1) <> "" Then
MsgBox "Sorry, the list is full!"
Me.txtFirstName.Value = Null
Me.txtLastName.Value = Null
Else
For intI = 0 To intItems - 1
If strFName(intI) = "" Then
strFName(intI) = Me.txtFirstName.Value
strLName(intI) = Me.txtLastName.Value
Me.txtFirstName.Value = Null
Me.txtLastName.Value = Null
Exit For
End If
Next
End If
End If
End Sub

I get a runtime error "Script out of range" on 'If strFName(intItems - 1) <> "" Then anyone have any ideas as to why?


问:
issue with fopen on google app engine
I'm having the issue with fopen() on google app engine. Works normal 3-4 times and than this response from server.

Message: fopen(https://website_url/image_name.png): failed to open
  stream: Connection closed.

Any idea how to troubleshoot what happened and why?

```<code>$image = "https://website_url/image_name.png";
$f = fopen($image,'rb');
</code>```

php ini has allow_url_fopen = On

答:
First make sure you have the correct path.
You need to give fopen the full path of the file, and you don't need chdir() at all. Try this version:

```<code>$path_to_file='url';
</code>```

$fh = fopen($path_to_file.$filename, 'w') or die('Permission error');

Title: issue with fopen on google app engine

Body:
I'm having the issue with fopen() on google app engine. Works normal 3-4 times and than this response from server.

Message: fopen(https://website_url/image_name.png): failed to open
  stream: Connection closed.

Any idea how to troubleshoot what happened and why?

$image = "https://website_url/image_name.png";
$f = fopen($image,'rb');

php ini has allow_url_fopen = On

Body:
First make sure you have the correct path.
You need to give fopen the full path of the file, and you don't need chdir() at all. Try this version:

$path_to_file='url';

$fh = fopen($path_to_file.$filename, 'w') or die('Permission error');


问:
How to create a polygon with coordinates you read from a file with tkinter
I want to display an image of the District of Columbia and I have 240 coordinates to create a polygon with tKinter. The coordinates are separated by a space and I want to 'split' them and append them to x and y. The program I have so far attached below is not running anything and just says "operation complete". The expected outcome is a display of DC in a window that is 640x480.

```<code>from Tkinter import Tk,Canvas
from PIL import Image,ImageTk
root = Tk()
canvas = Canvas(root, width=640, height=480, bg="white")
f = open("lab312.txt")
points = []
for n in range (1, 240):
   z = f.readline()
   coords= z.split(" ")
   x=float(coords[0])
   y=float(coords[1])
   points.append((12820*x+300,324*y+2198))
root.mainloop()
</code>```

The results I received was a window that wasn't 480x640 and it had nothing on it.

答:
Here is a minimal working example that uses a list of strings as the input 'file'.  Your main issue will be translating from the coordinates used in your data file to canvas plot coordinates with x and y in their respective ranges, with y increasing down.</p>

```<code>import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=640, height=480, bg="white")
canvas.pack()
f = [
'50 50',
'100 10',
'200 200',
'100 300',
'75 200',
]
points = []
for line in f:
    x, y = map(int, line.split())
    points.extend((x, y))
canvas.create_polygon(*points, fill='red')
root.update()
</code>```

Body:
I want to display an image of the District of Columbia and I have 240 coordinates to create a polygon with tKinter. The coordinates are separated by a space and I want to 'split' them and append them to x and y. The program I have so far attached below is not running anything and just says "operation complete". The expected outcome is a display of DC in a window that is 640x480.

from Tkinter import Tk,Canvas
from PIL import Image,ImageTk
root = Tk()
canvas = Canvas(root, width=640, height=480, bg="white")
f = open("lab312.txt")
points = []
for n in range (1, 240):
   z = f.readline()
   coords= z.split(" ")
   x=float(coords[0])
   y=float(coords[1])
   points.append((12820*x+300,324*y+2198))
root.mainloop()

The results I received was a window that wasn't 480x640 and it had nothing on it.

Body:
Here is a minimal working example that uses a list of strings as the input 'file'.  Your main issue will be translating from the coordinates used in your data file to canvas plot coordinates with x and y in their respective ranges, with y increasing down.

import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=640, height=480, bg="white")
canvas.pack()
f = [
'50 50',
'100 10',
'200 200',
'100 300',
'75 200',
]
points = []
for line in f:
    x, y = map(int, line.split())
    points.extend((x, y))
canvas.create_polygon(*points, fill='red')
root.update()


问:
kubectl update service with new label and service names
Is it possible to update an external loadbalancer service in kubernetes with a new spec from an yaml file.

I can do rolling updates of the deployments but how can I update services, primarily not changing the external IP address.

Thanks, Rajesh

答:
I think I have the answer

env KUBE_EDITOR="nano" kubectl edit svc/my-service

And I can edit the service with the new selector/labels.

I am not sure if there is a better option


问:
Build angular project into idea with maven
we are building SPA with Spring Boot Rest api and Angular 4. Here is our project structure in idea. It is small project, so we have it together. Project structure:

And here you are pom file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>custom-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>custom-name</name>
    <description>Example App</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

We need help with configuration. Is possible to set up project that, when we run mvn clean package, then project is compile and build, and angular project too. So next when we run project in idea, it start with SPA app on same server. We do not have a lot of experience with that configuration. Can you help us? Thanks in advance.

EDIT:

I'll tried configure pom.xml to build angular project into war, but index controller still not works. Error:

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.

Thu Dec 07 03:10:09 CET 2017 There was an unexpected error (type=Not
  Found, status=404). No message available

Here is war structure:

Servlet initializer:

```<code>@EnableWebMvc
public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

}
</code>```

And Controller class:

```<code>@Controller
public class IndexController {

    @RequestMapping("/")
    public String index() {
        return "index.html";
    }

}
</code>```

答: You can run npm tasks from maven. Please check the following link NPM build using maven</p>

Body:
we are building SPA with Spring Boot Rest api and Angular 4. Here is our project structure in idea. It is small project, so we have it together. Project structure:

And here you are pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>custom-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>custom-name</name>
    <description>Example App</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

We need help with configuration. Is possible to set up project that, when we run mvn clean package, then project is compile and build, and angular project too. So next when we run project in idea, it start with SPA app on same server. We do not have a lot of experience with that configuration. Can you help us? Thanks in advance.

EDIT:

I'll tried configure pom.xml to build angular project into war, but index controller still not works. Error:

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.

Thu Dec 07 03:10:09 CET 2017 There was an unexpected error (type=Not
  Found, status=404). No message available

Here is war structure:

Servlet initializer:

@EnableWebMvc
public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

}

And Controller class:

@Controller
public class IndexController {

    @RequestMapping("/")
    public String index() {
        return "index.html";
    }

}


问:
printf variable placeholder? Is it even a thing?
```<code>#include <stdio.h>
char pos[] = {34,92,48,51,51,91,57,59,57,72,37,115,34}; // "\033[9;9H%s"

main() {
    printf(pos,"Aaaaaaa");              // (1) This doesnt work as intended
    printf("\033[9;9H%s","Aaaaaaa");    // (2) Works as intended
}
</code>```

So why (2) works and (1) doesn't?

答:
There are two problems with pos.

First what you have is a character array, not a null terminated string.  You need to add a 0 to the end of that array.

Second, you don't have the same characters.  In the string literal "\033[9;9H%s" there are a total of 8 characters while pos has 13.

The sequence \033 represent a single character whose value is 33 octal or 27 decimal.  You instead have the literal characters '\', '0', '3', and '3'.  So replace 92,48,51,51 with 27.  Also, you have 34 for the first and last characters in pos, which is the double quote character ".  These characters are not part of the string literal but are used to denote it in code.  So get rid of those.

pos should now look like this:

```<code>char pos[] = {27,91,57,59,57,72,37,115,0};
</code>```

Body:
#include <stdio.h>
char pos[] = {34,92,48,51,51,91,57,59,57,72,37,115,34}; // "\033[9;9H%s"

main() {
    printf(pos,"Aaaaaaa");              // (1) This doesnt work as intended
    printf("\033[9;9H%s","Aaaaaaa");    // (2) Works as intended
}

So why (2) works and (1) doesn't?

Body:
There are two problems with pos.

First what you have is a character array, not a null terminated string.  You need to add a 0 to the end of that array.

Second, you don't have the same characters.  In the string literal "\033[9;9H%s" there are a total of 8 characters while pos has 13.

The sequence \033 represent a single character whose value is 33 octal or 27 decimal.  You instead have the literal characters '\', '0', '3', and '3'.  So replace 92,48,51,51 with 27.  Also, you have 34 for the first and last characters in pos, which is the double quote character ".  These characters are not part of the string literal but are used to denote it in code.  So get rid of those.

pos should now look like this:

char pos[] = {27,91,57,59,57,72,37,115,0};


答:
You've got three differences:

You don't need the initial and final 34 character ("), since string (2) doesn't print them out.

You need a null terminator to ensure that you print only your string and nothing more.

If \033 is meant to be an escape character, then its value is just 27, not 92,48,51,51.

After addressing those differences, your pos array:

```<code>{34,92,48,51,51,91,57,59,57,72,37,115,34}
</code>```

Should instead look like this (aligned to match the original array):

```<code>            {27,91,57,59,57,72,37,115,0}
</code>```

Title: printf variable placeholder? Is it even a thing?

Body:
You've got three differences:

You don't need the initial and final 34 character ("), since string (2) doesn't print them out.

You need a null terminator to ensure that you print only your string and nothing more.

If \033 is meant to be an escape character, then its value is just 27, not 92,48,51,51.

After addressing those differences, your pos array:

{34,92,48,51,51,91,57,59,57,72,37,115,34}

Should instead look like this (aligned to match the original array):

            {27,91,57,59,57,72,37,115,0}


问:
Add labels to navigation bar
I am adding a calendar to my app and thought it would be cool to mimic the format of standard iOS Calendar app as per weekday labels:

In the Calendar app, these labels (S,M,T,W,T,F,S) seem to be integrated into the navigation bar, so I was wondering if there is a way to implement this or if this is something Apple left to themselves (as there seems to be no standard way to add anything but bar button items). Mind you, these labels should be dynamic - e.g. rearrange in case of day 2 as firstWeekDay for certain Locale.

答:
You just need to set a view to your title view of navigationItem for example:

```<code>sampleLabel.textAlignment = .center
sampleLabel.textColor = UIColor.white
sampleLabel.font = UIFont.systemFont(ofSize: 12, weight: .medium)
sampleLabel.frame = CGRect(x: 0, y: 0, width: 40, height: 30)
sampleLabel.text = "T"
let titleView = UIView
titleView.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
titleView.addSubview(sampleLabel)
navigationItem.titleView = titleView
</code>```

You can add labels to your navigationBar like sampleLabel wherever you want.

Title: Add labels to navigation bar

Body:
You just need to set a view to your title view of navigationItem for example:

sampleLabel.textAlignment = .center
sampleLabel.textColor = UIColor.white
sampleLabel.font = UIFont.systemFont(ofSize: 12, weight: .medium)
sampleLabel.frame = CGRect(x: 0, y: 0, width: 40, height: 30)
sampleLabel.text = "T"
let titleView = UIView
titleView.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
titleView.addSubview(sampleLabel)
navigationItem.titleView = titleView

You can add labels to your navigationBar like sampleLabel wherever you want.


问:
How to send myself an email with php, Windows 7, WAMP server? need SIMPLE solution
I have spent the last 15 hours trying to figure out a simple, free way to send a simple text email via a php script when a form is filled out on a html page. I don't care how it looks, as these emails are only going to be sent to me (at most 15 a day). I don't need anything except a simple email to me when the form is filled out. I understand everything except I cannot get past:

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini

What i have tried:
Playing around with the pear mail extension and using smtp.gmail.com
Downloading countless smtp mail server applications.
Using my ISP smtp and port 25: smtp-server.wi.rr.com.
Using PHPMailer.
Using the windows SMTP server.

Although all of these things should work... I am apparently too dumb to figure it out. I have read every sentence on the subject on the internet and have tried to follow instructions, but each time I try something else, I just run into more problems. Someone PLEASE give me a simple fix to this, so I can never look at PHP mail stuff again.

答:
Folks.
After many hours of trying I found that:
You don't need additional tools like mailservers or pear additions. These only provide additional potential security leaks that you have no control or insight over.
To get mail function to work on localhost, all you need to do is change the php.ini file.
I just checked my outlook account settings and copied those to the php.ini file.
So SMTP server, port, username and password.

Now,
You may think it does not work but
You should know that many mail clients reject emails if the From field has a different domain than the actual domain an email is received from.
So if the php.ini file contains for example
smtp.ziggo.nl
Be sure that the header contains:
From: info@ziggo.nl

So for making universal code on both localhost and remote host, I check for the existence of a file that I only have locally (e.g. z_local) and set the headers accordingly. If the local file does not exist I must be on the remote ISP and choose the header "From: info@remotesite.com"


问:
how to set color the selected Item of Recycler View?
I have a RecyclerView with the TextView loaded from array MyData.  Actually what I need is when I click any item in RecyclerView that Item must get color and when I click another item I want that the first one become normal.

```<code>    private static class MyOnClickListener implements View.OnClickListener {

    private final Context context;
    String PersonGenerated;

    private MyOnClickListener(Context context) {
        this.context = context;
    }

    @Override
    public void onClick(View v) {
        // removeItem(v);
        int selectedItemPosition = recyclerView.getChildPosition(v);
        RecyclerView.ViewHolder viewHolder
                = recyclerView.findViewHolderForPosition(selectedItemPosition);
        TextView textViewName
                = (TextView) viewHolder.itemView.findViewById(R.id.textview_name);
        String selectedName = (String) textViewName.getText();

  data = new ArrayList<DataModel>();
    for (int i = 0; i < MyData.nameArray.length; i++) {
        data.add(new DataModel(
                MyData.id_[i],
                MyData.nameArray[i]

        ));
    }
    }
}
</code>```

This is my Adapter Class:

```<code>public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {

private ArrayList<DataModel> dataSet;

public CustomAdapter(ArrayList<DataModel> data) {
    this.dataSet = data;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
                                       int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.adapter_persons, parent, false);

    view.setOnClickListener(Persons.myOnClickListener);

    MyViewHolder myViewHolder = new MyViewHolder(view);
    return myViewHolder;
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {

    holder.textViewName.setText(dataSet.get(listPosition).getName());

}

@Override
public int getItemCount() {
    return dataSet.size();

}

public void animate(RecyclerView.ViewHolder viewHolder) {
    final Animation animAnticipateOvershoot = AnimationUtils.loadAnimation(context, R.anim.anticipateovershoot_interpolator);
    viewHolder.itemView.setAnimation(animAnticipateOvershoot);
}

public static class MyViewHolder extends RecyclerView.ViewHolder {

    TextView textViewName;

    public MyViewHolder(View itemView) {
        super(itemView);
        this.textViewName = (TextView) itemView.findViewById(R.id.textview_name);
    }
}
}
</code>```

This is my Array Class:

```<code>public class MyData {

    static String[] nameArray = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30"};
    static Integer[] id_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};
}
</code>```

Adapter Layout

```<code><LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:background="@drawable/select_row"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true">

    <TextView
        android:layout_weight="1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        style="@style/custom_text_oval"
        android:text="1"
        android:textColor="#8F8F8F"
        android:id="@+id/textview_name" />
</code>```

Recyclerview layout

```<code>  <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/linearLayout3"
            android:layout_gravity="center_horizontal">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/my_recycler_view"
                android:scrollbars="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

        </LinearLayout>
</code>```

答:
This is an old question but it can help to somebody, I've resolved it in this way:
You need to save the selected item and the last selected to update the background.</p>

```<code>private int selectedItem = 0;
private int lastSelected = 0;
public void onBindViewHolder(ViewHolder h, int position) {
    //If is selected the color change
    int backgroundColor = (position == selectedItem) ? R.color.selected : R.color.no_selected;

    layout.setBackgroundColor(ContextCompat.getColor(context, backgroundColor));

    h.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Save the position of the last selected item
            lastSelected = selectedItem;
            //Save the position of the current selected item
            selectedItem = position;

            //This update the last item selected
            notifyItemChanged(lastSelected);

            //This update the item selected
            notifyItemChanged(selectedItem);
        }
    });
}
</code>```

Body:
I have a RecyclerView with the TextView loaded from array MyData.  Actually what I need is when I click any item in RecyclerView that Item must get color and when I click another item I want that the first one become normal.

    private static class MyOnClickListener implements View.OnClickListener {

    private final Context context;
    String PersonGenerated;

    private MyOnClickListener(Context context) {
        this.context = context;
    }

    @Override
    public void onClick(View v) {
        // removeItem(v);
        int selectedItemPosition = recyclerView.getChildPosition(v);
        RecyclerView.ViewHolder viewHolder
                = recyclerView.findViewHolderForPosition(selectedItemPosition);
        TextView textViewName
                = (TextView) viewHolder.itemView.findViewById(R.id.textview_name);
        String selectedName = (String) textViewName.getText();

  data = new ArrayList<DataModel>();
    for (int i = 0; i < MyData.nameArray.length; i++) {
        data.add(new DataModel(
                MyData.id_[i],
                MyData.nameArray[i]

        ));
    }
    }
}

This is my Adapter Class:

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {

private ArrayList<DataModel> dataSet;

public CustomAdapter(ArrayList<DataModel> data) {
    this.dataSet = data;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
                                       int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.adapter_persons, parent, false);

    view.setOnClickListener(Persons.myOnClickListener);

    MyViewHolder myViewHolder = new MyViewHolder(view);
    return myViewHolder;
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {

    holder.textViewName.setText(dataSet.get(listPosition).getName());

}

@Override
public int getItemCount() {
    return dataSet.size();

}

public void animate(RecyclerView.ViewHolder viewHolder) {
    final Animation animAnticipateOvershoot = AnimationUtils.loadAnimation(context, R.anim.anticipateovershoot_interpolator);
    viewHolder.itemView.setAnimation(animAnticipateOvershoot);
}

public static class MyViewHolder extends RecyclerView.ViewHolder {

    TextView textViewName;

    public MyViewHolder(View itemView) {
        super(itemView);
        this.textViewName = (TextView) itemView.findViewById(R.id.textview_name);
    }
}
}

This is my Array Class:

public class MyData {

    static String[] nameArray = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30"};
    static Integer[] id_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};
}

Adapter Layout

<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:background="@drawable/select_row"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true">

    <TextView
        android:layout_weight="1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        style="@style/custom_text_oval"
        android:text="1"
        android:textColor="#8F8F8F"
        android:id="@+id/textview_name" />

Recyclerview layout

  <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/linearLayout3"
            android:layout_gravity="center_horizontal">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/my_recycler_view"
                android:scrollbars="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

        </LinearLayout>

Body:
This is an old question but it can help to somebody, I've resolved it in this way:
You need to save the selected item and the last selected to update the background.

private int selectedItem = 0;
private int lastSelected = 0;
public void onBindViewHolder(ViewHolder h, int position) {
    //If is selected the color change
    int backgroundColor = (position == selectedItem) ? R.color.selected : R.color.no_selected;

    layout.setBackgroundColor(ContextCompat.getColor(context, backgroundColor));

    h.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Save the position of the last selected item
            lastSelected = selectedItem;
            //Save the position of the current selected item
            selectedItem = position;

            //This update the last item selected
            notifyItemChanged(lastSelected);

            //This update the item selected
            notifyItemChanged(selectedItem);
        }
    });
}


问:
Can't set headers after they are sent error happens with socket.io
I am writing a very simple nodejs socket.io app. Somehow this returns "can't set headers after they are sent" error. but I can't see the point where the header is set again. I've only called server.listen once and I believe socket.listen works independently so it shouldn't conflict.

I am aware that can't set headers error had been posted a multiple times. I've read them briefly and I also understand how does response.writeHead works under normal circumstances(I've experimented with some node.js apps with response.writeHead, they worked fine most cases) it seems I am missing something from here. is it due to socket.io?

```<code>const fs = require("fs");

const server = require("http").createServer();
const io = require("socket.io").listen(server);

server.listen(52273,function(){
  console.log("server up");
});

server.on("request",function(request,response){
  fs.readFile("mainpage.html",function(error,data){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.end(data);
  });
});

io.sockets.on("connection",function(socket){

  var roomName = null;
  socket.on("join", function(data){
    roomName = data;
    socket.join(data);
    console.log("client joined" + data);
  });

  socket.on("message",function(data){
    io.sockets.in(roomName).emit("message","test");
  });
});
</code>```

答:
It probably helps a bit here to understand a little bit about how socket.io works with your web server.  socket.io uses the webSocket protocol as it's base protocol.  A webSocket connection starts with an HTTP request that has special header set in it to indicate the start of a webSocket connection.  A properly functioning web server will see this webSocket header and turn the request over to the webSocket handler to initiate the webSocket connection.

But, this handler you have:

```<code>server.on("request",function(request,response){
  fs.readFile("mainpage.html",function(error,data){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.end(data);
  });
});
</code>```

Looks like it is responding to every single request that arrives and sending a response, no matter what the request was.  So, I can imagine that when the webSocket request comes in you're sending two responses, one from the webSocket server code and one from your request handler above.

Probably, you need to be able to only send your mainpage.html response for particular URLs that are not your webSocket request.

To see a little more about what's going in, insert a console.log() into here:

```<code>server.on("request",function(request,response){
  console.log(request.url);
  fs.readFile("mainpage.html",function(error,data){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.end(data);
  });
});
</code>```

And, you will probably see you are sending your mainpage.html to a webSocket request which is not what you want to do.  You will likely want to add some if logic so that your request handler is avoiding the webSocket requests.

Body:
I am writing a very simple nodejs socket.io app. Somehow this returns "can't set headers after they are sent" error. but I can't see the point where the header is set again. I've only called server.listen once and I believe socket.listen works independently so it shouldn't conflict.

I am aware that can't set headers error had been posted a multiple times. I've read them briefly and I also understand how does response.writeHead works under normal circumstances(I've experimented with some node.js apps with response.writeHead, they worked fine most cases) it seems I am missing something from here. is it due to socket.io?

const fs = require("fs");

const server = require("http").createServer();
const io = require("socket.io").listen(server);

server.listen(52273,function(){
  console.log("server up");
});

server.on("request",function(request,response){
  fs.readFile("mainpage.html",function(error,data){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.end(data);
  });
});

io.sockets.on("connection",function(socket){

  var roomName = null;
  socket.on("join", function(data){
    roomName = data;
    socket.join(data);
    console.log("client joined" + data);
  });

  socket.on("message",function(data){
    io.sockets.in(roomName).emit("message","test");
  });
});

Body:
It probably helps a bit here to understand a little bit about how socket.io works with your web server.  socket.io uses the webSocket protocol as it's base protocol.  A webSocket connection starts with an HTTP request that has special header set in it to indicate the start of a webSocket connection.  A properly functioning web server will see this webSocket header and turn the request over to the webSocket handler to initiate the webSocket connection.

But, this handler you have:

server.on("request",function(request,response){
  fs.readFile("mainpage.html",function(error,data){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.end(data);
  });
});

Looks like it is responding to every single request that arrives and sending a response, no matter what the request was.  So, I can imagine that when the webSocket request comes in you're sending two responses, one from the webSocket server code and one from your request handler above.

Probably, you need to be able to only send your mainpage.html response for particular URLs that are not your webSocket request.

To see a little more about what's going in, insert a console.log() into here:

server.on("request",function(request,response){
  console.log(request.url);
  fs.readFile("mainpage.html",function(error,data){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.end(data);
  });
});

And, you will probably see you are sending your mainpage.html to a webSocket request which is not what you want to do.  You will likely want to add some if logic so that your request handler is avoiding the webSocket requests.


问:
Check if switch from SettingsActivity is on
How can I check in my MainActivity if the on/off switch is on in the SettingsActivity. I want to check if the switch is on and if it is, I want to do something. How do I do this so that this preference is saved and will be the same when you restart the app?

Here is a part of my SettingsActivity with a switch

```<code>static int audio;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_general);
        setHasOptionsMenu(true);

        bindPreferenceSummaryToValue(findPreference("example_text"));
        bindPreferenceSummaryToValue(findPreference("example_list"));

        Preference switchPref = (Preference) findPreference("audio_switch");

        switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object o) {

                boolean isOn = (boolean) o;

                if (isOn) {
                    audio = 1;

                }else{
                    audio = 0;

                }
                    return true;
                }
            });
        }
</code>```

答:
You are saving correctly the preference value, even you are returning true from your onPreferenceChangeListener to store the new value.

```<code> Preference switchPref = (Preference) findPreference("audio_switch");

    switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object o) {

            boolean isOn = (boolean) o;

            if (isOn) {
                audio = 1;
            }else{
                audio = 0;
            }

                 //* Set true to update the state of the Preference with the new value!
                return true;
            }

        });
    }
</code>```

The value is saved correctly when you close the application, if you want to check the value you can read it from the preference:

```<code>   //Check the current value in preference.
   SharedPreferences switchPrefStatus = PreferenceManager.getDefaultSharedPreferences(getActivity());
   boolean switchPrefValue = switchPrefStatus.getBoolean("audio_switch", false);
   Toast.makeText(getActivity(), "Current value: " + switchPrefValue, Toast.LENGTH_SHORT).show();
</code>```

Here is a complete example of PreferenceFragment with PreferenceFragment:

Body:
How can I check in my MainActivity if the on/off switch is on in the SettingsActivity. I want to check if the switch is on and if it is, I want to do something. How do I do this so that this preference is saved and will be the same when you restart the app?

Here is a part of my SettingsActivity with a switch

static int audio;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_general);
        setHasOptionsMenu(true);

        bindPreferenceSummaryToValue(findPreference("example_text"));
        bindPreferenceSummaryToValue(findPreference("example_list"));

        Preference switchPref = (Preference) findPreference("audio_switch");

        switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object o) {

                boolean isOn = (boolean) o;

                if (isOn) {
                    audio = 1;

                }else{
                    audio = 0;

                }
                    return true;
                }
            });
        }

Body:
You are saving correctly the preference value, even you are returning true from your onPreferenceChangeListener to store the new value.

 Preference switchPref = (Preference) findPreference("audio_switch");

    switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object o) {

            boolean isOn = (boolean) o;

            if (isOn) {
                audio = 1;
            }else{
                audio = 0;
            }

                 //* Set true to update the state of the Preference with the new value!
                return true;
            }

        });
    }

The value is saved correctly when you close the application, if you want to check the value you can read it from the preference:

   //Check the current value in preference.
   SharedPreferences switchPrefStatus = PreferenceManager.getDefaultSharedPreferences(getActivity());
   boolean switchPrefValue = switchPrefStatus.getBoolean("audio_switch", false);
   Toast.makeText(getActivity(), "Current value: " + switchPrefValue, Toast.LENGTH_SHORT).show();

Here is a complete example of PreferenceFragment with PreferenceFragment:


问:
Improving the Speed of Filter Rows in Pentaho
I am trying to filter out records from an excel sheet with over 94000 records with a simple validation and getting them in a new Excel sheet using Pentaho . But the speed of reading the input file and filtering of the record reduces gradually to less than 50 r/s after passing 20000 records.

Is there a way to increase the speed of processing the records or maintain the initial speed which was 1000 r/s ?

答:
Place a dummy step in the place of Excel Output step and run the transformation again. If you get better throughput now, you can understand that excel writer is the culprit.

See https://support.pentaho.com/hc/en-us/articles/205715046-Best-Practices-Pentaho-Data-Integration-Performance-Tuning- to know more about performance tuning in Pentaho etl.