问:
EF 6 Parameter Sniffing
I have a dynamic query that is just too large to put here.  Safe to say that in it's current form it utilizes a CLR procedure to dynamically build joins based upon the number of search parameters passed then takes that result and joins it to more detailed tables to bring back attributes important to the end-user.  I have converted the entire query into LINQ to Entities and what I have found is that the SQL that it produces is efficient enough to do the job, however running via EF 6, the query timesout.  Taking the resulting SQL and running it in SSMS runs in 3 or less seconds.  I can only imagine that my problem is parameter sniffing.  I have tried updating statistics on every table in the database and this has not solved the problem.

My Question is:

Can I somehow embed options like an "OPTION RECOMPILE" via EF?

答:
Same for me as for @Greg, enabling this system wide was not an option, so I wrote this small utility class that can temporary add option(recompile) to queries executed within an OptionRecompileScope.

Example usage

```<code>using (new OptionRecompileScope(dbContext))
{
    return dbContext.YourEntities.Where(<YourExpression>).ToList();
}
</code>```

Implementation

```<code>public class OptionRecompileScope : IDisposable
{
    private readonly OptionRecompileDbCommandInterceptor interceptor;

    public OptionRecompileScope(DbContext context)
    {
        interceptor = new OptionRecompileDbCommandInterceptor(context);
        DbInterception.Add(interceptor);
    }

    public void Dispose()
    {
        DbInterception.Remove(interceptor);
    }

    private class OptionRecompileDbCommandInterceptor : IDbCommandInterceptor
    {
        private readonly DbContext dbContext;

        internal OptionRecompileDbCommandInterceptor(DbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
        }

        public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
        }

        public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            if (ShouldIntercept(command, interceptionContext))
            {
                AddOptionRecompile(command);
            }
        }

        public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
        }

        public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            if (ShouldIntercept(command, interceptionContext))
            {
                AddOptionRecompile(command);
            }
        }

        public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
        }

        private static void AddOptionRecompile(IDbCommand command)
        {
            command.CommandText += " option(recompile)";
        }

        private bool ShouldIntercept(IDbCommand command, DbCommandInterceptionContext interceptionContext)
        {
            return
                command.CommandType == CommandType.Text &&
                command is SqlCommand &&
                interceptionContext.DbContexts.Any(interceptionDbContext => ReferenceEquals(interceptionDbContext, dbContext));
        }
    }
}
</code>```

Title: EF 6 Parameter Sniffing

Body:
Same for me as for @Greg, enabling this system wide was not an option, so I wrote this small utility class that can temporary add option(recompile) to queries executed within an OptionRecompileScope.

Example usage

using (new OptionRecompileScope(dbContext))
{
    return dbContext.YourEntities.Where(<YourExpression>).ToList();
}

Implementation

public class OptionRecompileScope : IDisposable
{
    private readonly OptionRecompileDbCommandInterceptor interceptor;

    public OptionRecompileScope(DbContext context)
    {
        interceptor = new OptionRecompileDbCommandInterceptor(context);
        DbInterception.Add(interceptor);
    }

    public void Dispose()
    {
        DbInterception.Remove(interceptor);
    }

    private class OptionRecompileDbCommandInterceptor : IDbCommandInterceptor
    {
        private readonly DbContext dbContext;

        internal OptionRecompileDbCommandInterceptor(DbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
        }

        public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
        }

        public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            if (ShouldIntercept(command, interceptionContext))
            {
                AddOptionRecompile(command);
            }
        }

        public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
        }

        public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            if (ShouldIntercept(command, interceptionContext))
            {
                AddOptionRecompile(command);
            }
        }

        public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
        }

        private static void AddOptionRecompile(IDbCommand command)
        {
            command.CommandText += " option(recompile)";
        }

        private bool ShouldIntercept(IDbCommand command, DbCommandInterceptionContext interceptionContext)
        {
            return
                command.CommandType == CommandType.Text &&
                command is SqlCommand &&
                interceptionContext.DbContexts.Any(interceptionDbContext => ReferenceEquals(interceptionDbContext, dbContext));
        }
    }
}

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Why MapFragment(HERE-API) extends android.app.Fragment instead of android.support.v4.app.Fragment?
Why MapFragment(HERE-API) extends android.app.Fragment instead of android.support.v4.app.Fragment?

If you have a structure to maintain compatibility with oldest versions of Android you will need to change!

For example: if you have a FragmentPagerAdapter you can't use MapFragment!! Because FragmentPagerAdapter uses support.v4!

答:
You should use the FragmentPagerAdapter from the v13 support library:

android.support.v13.app.FragmentPagerAdapter

```<code>dependencies {
    compile 'com.android.support:support-v13:+'
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You should use the FragmentPagerAdapter from the v13 support library:

android.support.v13.app.FragmentPagerAdapter

dependencies {
    compile 'com.android.support:support-v13:+'
}


问:
Sliding window functions in SQL Server, advanced calculation
I have a problem that it's very easy to be solved in C# code for example, but I have no idea how to write in a SQL query.

Here is the situation: let's say I have a table with 3 columns (ID, Date, Amount), and here is some data:

```<code>ID  Date         Amount
-----------------------
1   01.01.2016    -500
2   01.02.2016    1000
3   01.03.2016    -200
4   01.04.2016     300
5   01.05.2016     500
6   01.06.2016    1000
7   01.07.2016    -100
8   01.08.2016     200
</code>```

The result I want to get from the table is this (ID, Amount .... Order By Date):

```<code>ID  Amount
-----------------------
2    300
4    300
5    500
6    900
8    200
</code>```

The idea is to distribute the amounts into installments, but the thing is when negative amount comes into play you need to remove amount from the last installment. I don't know how clear I am, so here is an example:

Let's say I have 3 Invoices with amounts 500, 200, -300.

If i start distribute these Invoices, first i distribute the amount 500, then 200. But when i come to the third one -300, then i need to remove from the last Invoice. In other workds 200 - 300 = -100, so the amount from second Invoice will disappear, but there are still -100 that needs to be substracted from first Invoice. So 500 - 100 = 400. The result i need is dataset with one row (first invoice with amount 400)

Another example when the first invoice is with negative amount (-500, 300, 500).
In this case, the first (-500) invoice will make the second disappear and another 200 will be substracted from the third. So the result will be: Third Invoice with amount 300.

This is something like Stack implementation in programming language, but i need to make it with sliding-window functions in SQL Server.

If anyone have any idea, please share.

Thanks.

答:
I solved it using TSQL. But I think what this task also can solve using recursive CTE.
I used ID for finding a prev or next row.

```<code>-- create and fill test table
CREATE TABLE Invoices(
  ID int,
  [Date] date,
  Amount float
)

INSERT Invoices(ID,Date,Amount) VALUES
(1,'20160101', -500),
(2,'20160201', 1000),
(3,'20160301', -200),
(4,'20160401',  300),
(5,'20160501',  500),
(6,'20160601', 1000),
(7,'20160701', -100),
(8,'20160801',  200)
</code>```

My solution

```<code>-- copy all the data into temp table
SELECT *
INTO #Invoices
FROM Invoices

DECLARE
  @nID int,
  @nAmount float,
  @pID int

-- run infinity loop
WHILE 1=1
BEGIN

  -- set all the variables to NULL
  SET @nID=NULL
  SET @nAmount=NULL
  SET @pID=NULL

  -- get data from the last negative row
  SELECT
    @nID=ID,
    @nAmount=Amount
  FROM
    (
      SELECT TOP 1 *
      FROM #Invoices
      WHERE Amount<0
      ORDER BY ID DESC
    ) q

  -- get prev positive row
  SELECT @pID=ID
  FROM
    (
      SELECT TOP 1 *
      FROM #Invoices
      WHERE ID<@nID
        AND Amount>0
      ORDER BY ID DESC
    ) q

  IF(@pID IS NULL)
  BEGIN
    -- get next positive row
    SELECT @pID=ID
    FROM
      (
        SELECT TOP 1 *
        FROM #Invoices
        WHERE ID>@nID
          AND Amount>0
        ORDER BY ID
      ) q
  END

  -- exit from loop
  IF(@pID IS NULL) BREAK

  -- substract amount from positive row
  UPDATE #Invoices
  SET
    Amount+=@nAmount
  WHERE ID=@pID

  -- delete used negative row
  DELETE #Invoices
  WHERE ID=@nID

END

-- show result
SELECT *
FROM #Invoices

DROP TABLE #Invoices
</code>```

Body:
I have a problem that it's very easy to be solved in C# code for example, but I have no idea how to write in a SQL query.

Here is the situation: let's say I have a table with 3 columns (ID, Date, Amount), and here is some data:

ID  Date         Amount
-----------------------
1   01.01.2016    -500
2   01.02.2016    1000
3   01.03.2016    -200
4   01.04.2016     300
5   01.05.2016     500
6   01.06.2016    1000
7   01.07.2016    -100
8   01.08.2016     200

The result I want to get from the table is this (ID, Amount .... Order By Date):

ID  Amount
-----------------------
2    300
4    300
5    500
6    900
8    200

The idea is to distribute the amounts into installments, but the thing is when negative amount comes into play you need to remove amount from the last installment. I don't know how clear I am, so here is an example:

Let's say I have 3 Invoices with amounts 500, 200, -300.

If i start distribute these Invoices, first i distribute the amount 500, then 200. But when i come to the third one -300, then i need to remove from the last Invoice. In other workds 200 - 300 = -100, so the amount from second Invoice will disappear, but there are still -100 that needs to be substracted from first Invoice. So 500 - 100 = 400. The result i need is dataset with one row (first invoice with amount 400)

Another example when the first invoice is with negative amount (-500, 300, 500).
In this case, the first (-500) invoice will make the second disappear and another 200 will be substracted from the third. So the result will be: Third Invoice with amount 300.

This is something like Stack implementation in programming language, but i need to make it with sliding-window functions in SQL Server.

If anyone have any idea, please share.

Thanks.

Body:
I solved it using TSQL. But I think what this task also can solve using recursive CTE.
I used ID for finding a prev or next row.

-- create and fill test table
CREATE TABLE Invoices(
  ID int,
  [Date] date,
  Amount float
)

INSERT Invoices(ID,Date,Amount) VALUES
(1,'20160101', -500),
(2,'20160201', 1000),
(3,'20160301', -200),
(4,'20160401',  300),
(5,'20160501',  500),
(6,'20160601', 1000),
(7,'20160701', -100),
(8,'20160801',  200)

My solution

-- copy all the data into temp table
SELECT *
INTO #Invoices
FROM Invoices

DECLARE
  @nID int,
  @nAmount float,
  @pID int

-- run infinity loop
WHILE 1=1
BEGIN

  -- set all the variables to NULL
  SET @nID=NULL
  SET @nAmount=NULL
  SET @pID=NULL

  -- get data from the last negative row
  SELECT
    @nID=ID,
    @nAmount=Amount
  FROM
    (
      SELECT TOP 1 *
      FROM #Invoices
      WHERE Amount<0
      ORDER BY ID DESC
    ) q

  -- get prev positive row
  SELECT @pID=ID
  FROM
    (
      SELECT TOP 1 *
      FROM #Invoices
      WHERE ID<@nID
        AND Amount>0
      ORDER BY ID DESC
    ) q

  IF(@pID IS NULL)
  BEGIN
    -- get next positive row
    SELECT @pID=ID
    FROM
      (
        SELECT TOP 1 *
        FROM #Invoices
        WHERE ID>@nID
          AND Amount>0
        ORDER BY ID
      ) q
  END

  -- exit from loop
  IF(@pID IS NULL) BREAK

  -- substract amount from positive row
  UPDATE #Invoices
  SET
    Amount+=@nAmount
  WHERE ID=@pID

  -- delete used negative row
  DELETE #Invoices
  WHERE ID=@nID

END

-- show result
SELECT *
FROM #Invoices

DROP TABLE #Invoices


问:
How to reduce boilerplate nested Result in Rust
I have code using a nested Result like this:

```<code>fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
    let t: Vec<_> = s.split('.').collect();
    match t[0].parse::<u8>() {
        Ok(a1) => {
            match t[1].parse::<u8>() {
                Ok(a2) => {
                    match t[2].parse::<u8>() {
                        Ok(a3) => {
                            match t[3].parse::<u8>() {
                                Ok(a4) => {
                                    Ok((a1, a2, a3, a4))
                                }
                                Err(er) => Err(er)
                            }
                        },
                        Err(er) => Err(er)
                    }
                }
                Err(er) => Err(er)
            }
        }
        Err(er) => Err(er),
    }
}
</code>```

Is there any function or composing way to reduce this? Something like Haskell or Scala programmers do:

```<code>fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
  let t: Vec<_> = s.split('.').collect();
  Result
  .lift((,,,))
  .ap(() -> t[0].parse::<u8>())
  .ap(() -> t[1].parse::<u8>())
  .ap(() -> t[2].parse::<u8>())
  .ap(() -> t[3].parse::<u8>()) // maybe more concise in Haskell or Scala but I think it's enough :)
}
</code>```

答:
You can use early returns to prevent the nesting (but not the repetition).

Note the body of the Err arms of the matches:

```<code>fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
    let t: Vec<_> = s.split('.').collect();

    let a1 = match t[0].parse::<u8>() {
        Ok(x) => x,
        Err(er) => return Err(er),
    };
    let a2 = match t[1].parse::<u8>() {
        Ok(x) => x,
        Err(er) => return Err(er),
    };
    let a3 = match t[2].parse::<u8>() {
        Ok(x) => x,
        Err(er) => return Err(er),
    };
    let a4 = match t[3].parse::<u8>() {
        Ok(x) => x,
        Err(er) => return Err(er),
    };

    (a1, a2, a3, a4)
}
</code>```

But, as the others have said, Rust already has a built-in way to parse IP addresses.

Body:
I have code using a nested Result like this:

fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
    let t: Vec<_> = s.split('.').collect();
    match t[0].parse::<u8>() {
        Ok(a1) => {
            match t[1].parse::<u8>() {
                Ok(a2) => {
                    match t[2].parse::<u8>() {
                        Ok(a3) => {
                            match t[3].parse::<u8>() {
                                Ok(a4) => {
                                    Ok((a1, a2, a3, a4))
                                }
                                Err(er) => Err(er)
                            }
                        },
                        Err(er) => Err(er)
                    }
                }
                Err(er) => Err(er)
            }
        }
        Err(er) => Err(er),
    }
}

Is there any function or composing way to reduce this? Something like Haskell or Scala programmers do:

fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
  let t: Vec<_> = s.split('.').collect();
  Result
  .lift((,,,))
  .ap(() -> t[0].parse::<u8>())
  .ap(() -> t[1].parse::<u8>())
  .ap(() -> t[2].parse::<u8>())
  .ap(() -> t[3].parse::<u8>()) // maybe more concise in Haskell or Scala but I think it's enough :)
}

Body:
You can use early returns to prevent the nesting (but not the repetition).

Note the body of the Err arms of the matches:

fn ip4(s: &str) -> Result<(u8, u8, u8, u8), num::ParseIntError> {
    let t: Vec<_> = s.split('.').collect();

    let a1 = match t[0].parse::<u8>() {
        Ok(x) => x,
        Err(er) => return Err(er),
    };
    let a2 = match t[1].parse::<u8>() {
        Ok(x) => x,
        Err(er) => return Err(er),
    };
    let a3 = match t[2].parse::<u8>() {
        Ok(x) => x,
        Err(er) => return Err(er),
    };
    let a4 = match t[3].parse::<u8>() {
        Ok(x) => x,
        Err(er) => return Err(er),
    };

    (a1, a2, a3, a4)
}

But, as the others have said, Rust already has a built-in way to parse IP addresses.


问:
Type mismatch, expected ListBuffer[Any], actual ListBuffer[CustomClass]
I don't understand the title error knowing that for this function :

```<code>def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}
</code>```

called with these parameters :

```<code>myFunction(
  objectList // :ListBuffer[CustomClass],
  customObject // :CustomObject
)
</code>```

Am i obliged to call function like this :

```<code>myFunction(
  objectList.asInstanceOf[ListBuffer[Any]],
  customObject
)
</code>```

Produces mismatch type error only for ListBuffer parameter.
So CustomObject => Any is ok but no ListBuffer[CustomObject] => ListBuffer[Any] ?

Thank you

答:
You are using parameter name object, which is a keyword in scala.

```<code>def myFunction(objectList: ListBuffer[Any], customObject: Any): Boolean = {...}
</code>```

If you want object as parameter name, use tilt symbol before it.

```<code>def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}
</code>```

Other problem is you can't make it Any using asInstanceOf. So, change ListBuffer[Any] to ListBuffer[CustomClass]

```<code>def myFunction(objectList: ListBuffer[CustomClass], customObject: Any): Boolean = {...}
</code>```

Body:
I don't understand the title error knowing that for this function :

def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}

called with these parameters :

myFunction(
  objectList // :ListBuffer[CustomClass],
  customObject // :CustomObject
)

Am i obliged to call function like this :

myFunction(
  objectList.asInstanceOf[ListBuffer[Any]],
  customObject
)

Produces mismatch type error only for ListBuffer parameter.
So CustomObject => Any is ok but no ListBuffer[CustomObject] => ListBuffer[Any] ?

Thank you

Body:
You are using parameter name object, which is a keyword in scala.

def myFunction(objectList: ListBuffer[Any], customObject: Any): Boolean = {...}

If you want object as parameter name, use tilt symbol before it.

def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}

Other problem is you can't make it Any using asInstanceOf. So, change ListBuffer[Any] to ListBuffer[CustomClass]

def myFunction(objectList: ListBuffer[CustomClass], customObject: Any): Boolean = {...}


问:
Handling threads in JNI code
I have a cache implementation in C++ that is accessed from JAVA code via JNI.
To allow concurrent access to the cache I need to lock it and I am confused what type of lock should I use in my C++ program? should I use JNI's montiorEnter/Exit as the threads that execute the jni code are java threads or std::mutex cacheMtx? Thanks</p>

答:
Take a look here for a sample code where JVM is accessed from different threads.

http://jnicookbook.owsiak.org/recipe-no-027/

In general, you want to make sure to gain access to JVM, use it, and then, release everything.

In your case, you migh have slightly different approach, as you probably won't call JVM back, but still, you can utilize pthread_mutex as you are inside the same shared library loaded from your JVM.

Title: Handling threads in JNI code


问:
Trigger event when toggling between div and textfield
Ok, so Im building an application in Laravel, but my problem is with jQuery. I am creating a comment section for some posts. Adding the comments work fine. Under each post all the comments for the particular post are listed. If the comment is made by you, an edit button is shown. If you press the edit button a few things will happen:

the p-tag containing the comment is replaced with a textarea (maintaining the same content/text)

the edit button changes text to "Save" (instead of "Edit")

the button also changes some classes and therefore styling

the button gets a class of "save-mode"

Im trying to make so that when the button has the class of save-mode, an event should get triggered, thus updating the comment in the database.
Now, almost all the pieces work fine separately but the Ajax call is not fired when the button is pressed. And I just cant see why. Its worth mentioning that the Ajax call does work. But the if-statement that is supposed to trigger it doesn't.

There must be something wrong with my logic.

Ive included a snippet, and Im guessing theres something wrong in the editComment function. Ive removed the blade syntax, styling and surrounding markup. But you can see the same problem in this snippet.

I really appreciate any help I can get to illuminate my own stupidity.
Thank you.

$("#edit-save-btn").on('click', function(e){
 e.preventDefault();
 editComment($(this));
});

function editComment(btn){
 const id = btn.attr('value');
 const comment = btn.closest('.col-md-3').prev().find('.comment-text');
 const commentHTML = $.trim(comment.text());

 if(btn.hasClass('save-mode')){
      console.log('this need to get triggered');
  //updateComment(id, commentHTML);
  return;
 }

 btn.toggleClass('save-mode');

 const editable = $('<textarea />').css({'width': '100%'});
 editable.val(commentHTML);
 comment.replaceWith(editable);
 editable.focus();
 btn.removeClass('btn-primary').addClass('btn-success').html(' Lagre');
 editable.blur(editableTextBlured);
}

function editableTextBlured() {
 $("#edit-save-btn").removeClass('btn-success save-mode').addClass('btn-primary').html(' Rediger');
 var text = $(this).val();
 viewableText = $('
');
 viewableText.html(text);
 $(this).replaceWith(viewableText);
 $(viewableText).click(editComment);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment-post clearfix">
  <div class="col-md-9">
    <p class="comment-text">
      comment
    </p>
  </div>

  <div class="col-md-3">
    <form class="pull-right right-margin" action="" method="post">
      <button value="{{$comment->id}}" class="btn edit-comment btn-primary btn-xs" id="edit-save-btn"><i class="fa fa-edit"></i> Edit</button>
  </form>
 </div>
</div></code>```

答:
Click the button will trigger the blur event of textarea.

At the function editableTextBlured, your removed the class save-mode, so btn.hasClass('save-mode') is return false, it can't trigger save.

It's like this:

blur -> remove className save-mode -> btn.hasClass('save-mode') -> false, can't trigger save.

Wish it can help for you :)

Body:
Ok, so Im building an application in Laravel, but my problem is with jQuery. I am creating a comment section for some posts. Adding the comments work fine. Under each post all the comments for the particular post are listed. If the comment is made by you, an edit button is shown. If you press the edit button a few things will happen:

the p-tag containing the comment is replaced with a textarea (maintaining the same content/text)

the edit button changes text to "Save" (instead of "Edit")

the button also changes some classes and therefore styling

the button gets a class of "save-mode"

Im trying to make so that when the button has the class of save-mode, an event should get triggered, thus updating the comment in the database.
Now, almost all the pieces work fine separately but the Ajax call is not fired when the button is pressed. And I just cant see why. Its worth mentioning that the Ajax call does work. But the if-statement that is supposed to trigger it doesn't.

There must be something wrong with my logic.

Ive included a snippet, and Im guessing theres something wrong in the editComment function. Ive removed the blade syntax, styling and surrounding markup. But you can see the same problem in this snippet.

I really appreciate any help I can get to illuminate my own stupidity.
Thank you.

$("#edit-save-btn").on('click', function(e){
 e.preventDefault();
 editComment($(this));
});

function editComment(btn){
 const id = btn.attr('value');
 const comment = btn.closest('.col-md-3').prev().find('.comment-text');
 const commentHTML = $.trim(comment.text());

 if(btn.hasClass('save-mode')){
      console.log('this need to get triggered');
  //updateComment(id, commentHTML);
  return;
 }

 btn.toggleClass('save-mode');

 const editable = $('<textarea />').css({'width': '100%'});
 editable.val(commentHTML);
 comment.replaceWith(editable);
 editable.focus();
 btn.removeClass('btn-primary').addClass('btn-success').html(' Lagre');
 editable.blur(editableTextBlured);
}

function editableTextBlured() {
 $("#edit-save-btn").removeClass('btn-success save-mode').addClass('btn-primary').html(' Rediger');
 var text = $(this).val();
 viewableText = $('
');
 viewableText.html(text);
 $(this).replaceWith(viewableText);
 $(viewableText).click(editComment);
}

      comment

    <form class="pull-right right-margin" action="" method="post">
      <button value="{{$comment->id}}" class="btn edit-comment btn-primary btn-xs" id="edit-save-btn"> Edit</button>
  </form>


问:
set path and url of youtube file downloader at run time by user
below is the code for downloading youtube files providing URL, but at present the URL is static, I'm trying to make it dynamic so that user can put URL at runtime. and secondly, I'm also trying to set the path where to save, file by the user but, somehow not able to do

(I'm working on python3 idle with windows)

```<code>from __future__ import unicode_literals
import youtube_dl
import urllib
import shutil
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://youtu.be/zhWDdy_5v2w'])
print("DONE!")
</code>```

答:
This is how it should work:

from __future__ import unicode_literals
import sys
import youtube_dl
import urllib
import shutil
ydl_opts = {'outtmpl': '~/Documents/file_name'}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  ydl.download(sys.argv[1:])
print("DONE!")```

Usage: youtube_script.py youtube_url

You can use it like this . Though I have not tested the code but it should work. If i correctly understand, you mean the user can set the url when starting the python script ?, then this is how it should be done or you can take the input in a string and then provide it to the ydl.download function.

Body:
below is the code for downloading youtube files providing URL, but at present the URL is static, I'm trying to make it dynamic so that user can put URL at runtime. and secondly, I'm also trying to set the path where to save, file by the user but, somehow not able to do

(I'm working on python3 idle with windows)

from __future__ import unicode_literals
import youtube_dl
import urllib
import shutil
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://youtu.be/zhWDdy_5v2w'])
print("DONE!")

Body:
This is how it should work:

from __future__ import unicode_literals
import sys
import youtube_dl
import urllib
import shutil
ydl_opts = {'outtmpl': '~/Documents/file_name'}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  ydl.download(sys.argv[1:])
print("DONE!")

Usage: youtube_script.py youtube_url

You can use it like this . Though I have not tested the code but it should work. If i correctly understand, you mean the user can set the url when starting the python script ?, then this is how it should be done or you can take the input in a string and then provide it to the ydl.download function.


问:
how to convert Dataset Row type to Dataset String type
I am using spark 2.2 with java 8. I have a dataset in Rowtype and I want to used this dataset into ML model so I want to convert Dataset into Dataset when I used  Dataset into model it's shown below error.

Type mismatch: cannot convert from Dataset to Dataset

I fond below solution for scala but I want to do this into java.

```<code>df.map(row => row.mkString())
val strings = df.map(row => row.mkString()).collect
</code>```

答:
first convert Row dataset into list and then convert that list into String dataset. Try this</p>

```<code>Dataset<Row> df= spark.read()...
List<String> list = df.as(Encoders.STRING()).collectAsList();
Dataset<String> df1 = session.createDataset(list, Encoders.STRING());
</code>```

Body:
I am using spark 2.2 with java 8. I have a dataset in Rowtype and I want to used this dataset into ML model so I want to convert Dataset into Dataset when I used  Dataset into model it's shown below error.

Type mismatch: cannot convert from Dataset to Dataset

I fond below solution for scala but I want to do this into java.

df.map(row => row.mkString())
val strings = df.map(row => row.mkString()).collect

Body:
first convert Row dataset into list and then convert that list into String dataset. Try this

Dataset<Row> df= spark.read()...
List<String> list = df.as(Encoders.STRING()).collectAsList();
Dataset<String> df1 = session.createDataset(list, Encoders.STRING());


问:
Todays Special: How is this done? Is there a jquery plugin or product to do it?
I saw this technique at the bottom of a web page where the TAB stays in place at the bottom of the page and can be opened and closed to display more info. I assume it can be rotated to display a different special for different days. Can you point me to anything like it or explain the technique ?  thanks.  Here is a sample:   http://www.tmdhosting.com/   look at the bottom of the page .</p>

答:
You can check out my version of this at uxspoke.com

I wrote a jQuery plugin to do it, and calling it is straightforward:

```<code>$('#about').pulloutPanel({open:true}).
    click(function() { $(this).trigger('toggle'); }) });
</code>```

I basically instrument the panel to support "open", "close" events, and the implement the appropriate animations around them. The only "hard" part is getting the height right. It also supports "toggle" so you can add a generic click handler to it to open or close it. Finally, it uses opened/closed classes to keep track of its current state. That's it!

The code's pretty coupled to the technologies on the page (Csster) and the design it is in, so I'm not sure it will work for you. You can either use Csster, or just put the CSS rules into your stylesheet and remove them from the code. The important Css attributes are the positioning and bottom.

Here it is:

```<code>$.fn.pulloutPanel = function(options) {

    var settings = $.extend({}, {
      attachTo: 'bottom',
      css: {
        left: 0,
        minHeight: 390,
        border: '1px 1px 1px 0 solid #666',
        has: [roundedCorners('tr', 10),boxShadow([0,0], 10,   phaseToColor('requirements').saturate(-30).darken(50))],
        cursor: 'pointer'
    }, options);

    return $(this).each(function() {
        var $this = $(this);

        $this.addClass('pullout_panel');

        $this.bind('open', function(event) {
            $this.animate({bottom: 0}, 'slow', 'easeOutBounce', function() {
                $this.removeClass('closed').addClass('opened');
                $this.trigger('opened');
            });
        });
        $this.bind('close', function(event) {
            var height = $this.innerHeight();
            $this.animate({bottom: -height + 50}, 'slow', 'easeOutBounce', function() {
                $this.addClass('closed').removeClass('opened');
                $this.trigger('closed');
            });
        });
        $this.bind('toggle', function(event) {
            $this.trigger($this.hasClass('opened') ? 'close' : 'open');
        });

        once(function() {
            Csster.style({
                '.pullout_panel': {
                    position: 'fixed',
                    bottom: 0,
                    has: [settings.css]
                }
            });
        });

        $this.trigger(settings.open ? 'open' : 'close');

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

ContentLicense: CC BY-SA 2.5

Body:
You can check out my version of this at uxspoke.com

I wrote a jQuery plugin to do it, and calling it is straightforward:

$('#about').pulloutPanel({open:true}).
    click(function() { $(this).trigger('toggle'); }) });

I basically instrument the panel to support "open", "close" events, and the implement the appropriate animations around them. The only "hard" part is getting the height right. It also supports "toggle" so you can add a generic click handler to it to open or close it. Finally, it uses opened/closed classes to keep track of its current state. That's it!

The code's pretty coupled to the technologies on the page (Csster) and the design it is in, so I'm not sure it will work for you. You can either use Csster, or just put the CSS rules into your stylesheet and remove them from the code. The important Css attributes are the positioning and bottom.

Here it is:

$.fn.pulloutPanel = function(options) {

    var settings = $.extend({}, {
      attachTo: 'bottom',
      css: {
        left: 0,
        minHeight: 390,
        border: '1px 1px 1px 0 solid #666',
        has: [roundedCorners('tr', 10),boxShadow([0,0], 10,   phaseToColor('requirements').saturate(-30).darken(50))],
        cursor: 'pointer'
    }, options);

    return $(this).each(function() {
        var $this = $(this);

        $this.addClass('pullout_panel');

        $this.bind('open', function(event) {
            $this.animate({bottom: 0}, 'slow', 'easeOutBounce', function() {
                $this.removeClass('closed').addClass('opened');
                $this.trigger('opened');
            });
        });
        $this.bind('close', function(event) {
            var height = $this.innerHeight();
            $this.animate({bottom: -height + 50}, 'slow', 'easeOutBounce', function() {
                $this.addClass('closed').removeClass('opened');
                $this.trigger('closed');
            });
        });
        $this.bind('toggle', function(event) {
            $this.trigger($this.hasClass('opened') ? 'close' : 'open');
        });

        once(function() {
            Csster.style({
                '.pullout_panel': {
                    position: 'fixed',
                    bottom: 0,
                    has: [settings.css]
                }
            });
        });

        $this.trigger(settings.open ? 'open' : 'close');

    });
};


问:
XML serialize complex type with attribute
I'm currently working on a .NET 4.6 console application. I try to parse/serialize a XML from a file.

Currently I'm struggling with the serialization of a Complex Type in XML.

Given is the following XML element:

```<code><cool_element>
   <master visible="true">A1</master>
</cool_element>
</code>```

as well as it's according XSD specification:

```<code><xs:element name="cool_element">
   <xs:complexType>
      <xs:sequence>
         <xs:element name="master">
            <xs:complexType>
               <xs:simpleContent>
                  <xs:extension base="xs:string">
                     <xs:attribute type="xs:string" name="visible"/>
                 </xs:extension>
              </xs:simpleContent>
            </xs:complexType>
         </xs:element>
      </xs:sequence>
   </xs:complexType>
</xs:element>
</code>```

My serialization class in C# looks like this:

```<code>[XmlRoot(ElementName = "cool_element")]
public class CoolElement
{
    [XmlElement("master")]
    public string Master { get; set; }
}
</code>```

This works fine to retrieve the string value. But I don't know how to get the attribute visible from my master element.

Do you have an idea on how to solve this?

Thank you!

答:
master should be it's own object class, I would solve it this way (note the xml attributes for value and visible):

```<code>[XmlRoot(ElementName = "cool_element")]
public class CoolElement
{
    private Master masterField;
    public Master master { get { return this.masterField; } set { this.masterField = value; } }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class Master
{
    private bool visibleField;

    private string valueField;

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public bool visible { get { return this.visibleField; } set { this.visibleField = value; } }

    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value { get { return this.valueField; } set { this.valueField = value; } }
}
</code>```

then to read the data:

```<code>        CoolElement cool = null;
        string path = @"yourxmlfilename.xml";
        XmlSerializer serializer = new XmlSerializer(typeof(CoolElement));
        using (var reader = XmlReader.Create(path))
        {
            cool = (CoolElement)serializer.Deserialize(reader);
            Console.WriteLine("master value: " + cool.master.Value);
            Console.WriteLine("attribute visible value: " + cool.master.visible);
        }
</code>```

does that help you?

Body:
I'm currently working on a .NET 4.6 console application. I try to parse/serialize a XML from a file.

Currently I'm struggling with the serialization of a Complex Type in XML.

Given is the following XML element:

<cool_element>
   <master visible="true">A1</master>
</cool_element>

as well as it's according XSD specification:

<xs:element name="cool_element">
   <xs:complexType>
      <xs:sequence>
         <xs:element name="master">
            <xs:complexType>
               <xs:simpleContent>
                  <xs:extension base="xs:string">
                     <xs:attribute type="xs:string" name="visible"/>
                 </xs:extension>
              </xs:simpleContent>
            </xs:complexType>
         </xs:element>
      </xs:sequence>
   </xs:complexType>
</xs:element>

My serialization class in C# looks like this:

[XmlRoot(ElementName = "cool_element")]
public class CoolElement
{
    [XmlElement("master")]
    public string Master { get; set; }
}

This works fine to retrieve the string value. But I don't know how to get the attribute visible from my master element.

Do you have an idea on how to solve this?

Thank you!

Body:
master should be it's own object class, I would solve it this way (note the xml attributes for value and visible):

[XmlRoot(ElementName = "cool_element")]
public class CoolElement
{
    private Master masterField;
    public Master master { get { return this.masterField; } set { this.masterField = value; } }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class Master
{
    private bool visibleField;

    private string valueField;

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public bool visible { get { return this.visibleField; } set { this.visibleField = value; } }

    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value { get { return this.valueField; } set { this.valueField = value; } }
}

then to read the data:

        CoolElement cool = null;
        string path = @"yourxmlfilename.xml";
        XmlSerializer serializer = new XmlSerializer(typeof(CoolElement));
        using (var reader = XmlReader.Create(path))
        {
            cool = (CoolElement)serializer.Deserialize(reader);
            Console.WriteLine("master value: " + cool.master.Value);
            Console.WriteLine("attribute visible value: " + cool.master.visible);
        }

does that help you?


问:
Database call in Sails.js beforeCreate() model hook causes validation error
I have a Sails.js model called "products" which is a MongoDB collection. In the model, I have a beforeCreate() hook that generates a unique productId like '170921-00001' in the format 'YYMMDD-count` where count is the record number created for the day. This is what my model looks like:

```<code>module.exports = {

    attributes: {
        name: { type: 'string', required: true },
        productId: { type: 'string', unique: true }
    },

    beforeCreate: function(values, next) {

        var moment = require('moment');

        // Generate the productId
        Products.count({
            createdAt: {
                '>=': moment().format('YYYY-MM-DD'),
                '<': moment(moment().format('YYYY-MM-DD')).add(1, 'days').format('YYYY-MM-DD')
            }
        }).exec(function(error, productCount) {

            if (error) {
                throw error;
            }

            var count = '',
                totalPlaces = 5 - productCount.toString().length;
            while (totalPlaces > 0) {
                count = count + '0';
                totalPlaces--;
            }

            values.productId = moment().format('YYMMDD') + '-' + (count + productCount);

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

The issue is, this break when I am trying to insert multiple products into the collection in a single database call. I get the following error:

```<code>debug: Error (E_VALIDATION) :: 1 attribute is invalid
MongoError: E11000 duplicate key error index: my-app.products.$productId_1 dup key: { : "170921-00002" }
    at Function.MongoError.create (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb-core/lib/error.js:31:11)
    at toError (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/utils.js:114:22)
    at /Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/collection.js:658:23
    at handleCallback (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/utils.js:95:56)
    at resultHandler (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/bulk/ordered.js:421:14)
    at /Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb-core/lib/connection/pool.js:455:18
    at /Users/Nag/Code/my-app/web-service/node_modules/async-listener/glue.js:188:31
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
    at process.fallback (/Users/Nag/Code/my-app/web-service/node_modules/async-listener/index.js:529:15)

Invalid attributes sent to undefined:
 • productId
   • A record with that `productId` already exists (`170921-00002`).
</code>```

When I insert a single record, it works fine but when I insert multiple records, the first record gets inserted but every subsequent record generates that error. Is it because the document is getting inserted before the hook computes the productId before even it has completed inserting the previous record? How do I solve this?

答:
You should make unique values before update method:

values.productId = moment().format('YYMMDD') + '-' + (count + productCount);

This line of your code might be:

values.productId = moment().format('YYMMDD') + '-' + (count + productCount)+ Math.random();

it generate always unique id.

Body:
I have a Sails.js model called "products" which is a MongoDB collection. In the model, I have a beforeCreate() hook that generates a unique productId like '170921-00001' in the format 'YYMMDD-count` where count is the record number created for the day. This is what my model looks like:

module.exports = {

    attributes: {
        name: { type: 'string', required: true },
        productId: { type: 'string', unique: true }
    },

    beforeCreate: function(values, next) {

        var moment = require('moment');

        // Generate the productId
        Products.count({
            createdAt: {
                '>=': moment().format('YYYY-MM-DD'),
                '<': moment(moment().format('YYYY-MM-DD')).add(1, 'days').format('YYYY-MM-DD')
            }
        }).exec(function(error, productCount) {

            if (error) {
                throw error;
            }

            var count = '',
                totalPlaces = 5 - productCount.toString().length;
            while (totalPlaces > 0) {
                count = count + '0';
                totalPlaces--;
            }

            values.productId = moment().format('YYMMDD') + '-' + (count + productCount);

            next();
        });
    }
};

The issue is, this break when I am trying to insert multiple products into the collection in a single database call. I get the following error:

debug: Error (E_VALIDATION) :: 1 attribute is invalid
MongoError: E11000 duplicate key error index: my-app.products.$productId_1 dup key: { : "170921-00002" }
    at Function.MongoError.create (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb-core/lib/error.js:31:11)
    at toError (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/utils.js:114:22)
    at /Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/collection.js:658:23
    at handleCallback (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/utils.js:95:56)
    at resultHandler (/Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb/lib/bulk/ordered.js:421:14)
    at /Users/Nag/Code/my-app/web-service/node_modules/sails-mongo/node_modules/mongodb-core/lib/connection/pool.js:455:18
    at /Users/Nag/Code/my-app/web-service/node_modules/async-listener/glue.js:188:31
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
    at process.fallback (/Users/Nag/Code/my-app/web-service/node_modules/async-listener/index.js:529:15)

Invalid attributes sent to undefined:
 • productId
   • A record with that `productId` already exists (`170921-00002`).

When I insert a single record, it works fine but when I insert multiple records, the first record gets inserted but every subsequent record generates that error. Is it because the document is getting inserted before the hook computes the productId before even it has completed inserting the previous record? How do I solve this?


问:
Issue in parsing Json using JsonObject
I am facing issue while parsing the JsonResponse. Getting error

```<code>org.json.JSONException: A JSONArray text must start with '[' at character 1
</code>```

Actual API Response

```<code>["fa0d30bf-49ad-47be-a840-34393493hdkjfd"]
</code>```

I need to extract the value out of this array. Below is the code that I've tried.

```<code>Gson gson = new Gson();
String jsonString = "["fa0d30bf-49ad-47be-a840-34393493hdkjfd"]"
String gsonString = gson.toJson(jsonString);
JSONArray arr = new JSONArray(gsonString);
String api = arr.getJSONObject(indexOfArray).toString(); // indexOfArray = 0
</code>```

Could someone help me here.

答:
If you are using Gson, you can try below code</p>

```<code>String jsonString = "[\"fa0d30bf-49ad-47be-a840-34393493hdkjfd\"]";

Gson gson = new Gson();
JsonArray arr = gson.fromJson (jsonString, JsonElement.class).getAsJsonArray(); //Converts the response string to JsonArray

String api = arr.get(indexOfArray).getAsString(); // indexOfArray = 0
</code>```

Title: Issue in parsing Json using JsonObject

Body:
I am facing issue while parsing the JsonResponse. Getting error

org.json.JSONException: A JSONArray text must start with '[' at character 1

Actual API Response

["fa0d30bf-49ad-47be-a840-34393493hdkjfd"]

I need to extract the value out of this array. Below is the code that I've tried.

Gson gson = new Gson();
String jsonString = "["fa0d30bf-49ad-47be-a840-34393493hdkjfd"]"
String gsonString = gson.toJson(jsonString);
JSONArray arr = new JSONArray(gsonString);
String api = arr.getJSONObject(indexOfArray).toString(); // indexOfArray = 0

Could someone help me here.

Body:
If you are using Gson, you can try below code

String jsonString = "[\"fa0d30bf-49ad-47be-a840-34393493hdkjfd\"]";

Gson gson = new Gson();
JsonArray arr = gson.fromJson (jsonString, JsonElement.class).getAsJsonArray(); //Converts the response string to JsonArray

String api = arr.get(indexOfArray).getAsString(); // indexOfArray = 0


问:
how to display two different bitmap images in canoe?
I would like to display two different images in the panel based on event, example, for light on display one bit map image, And for light off display another bitmap image.
 I already tried to browse the options in properties box there is not much information available regarding this, did anybody have solution for this issue?</p>

答: Usually you would use a Switch/Indicator control and use a bitmap that includes all states in one image. See chapter "Assigning and Creating Bitmaps" in the manual.</p>


问:
Test unique index Mysql2:Error in RSpec
I have a permalink field in my model which has uniqueness validation in Rails and a unique index in MySQL.
When I import data through my API, it happens sometimes, that two requests has the same value for permalink and they try to save at the same time.

In this case, I don't get a uniqueness validation error, I get an error:

```<code>ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'permalink123' for key 'index_products_on_permalink'
</code>```

I deal with this case by warpping save in a rescue block, adding a random value to the end of the permalink and try to save again. When the second save also produces an error, it is raised.

But how do test this behaviour in RSpec? I tried to disable the uniqueness validation during the test with

```<code>Product.class_eval do
  validates :permalink, uniqueness: false
end
</code>```

but this does not throw the MySQL error. I also don't think that stubbing the error with expect(product).to receive(:save).and_raise(Mysql2::Error) is the right way, because what happens when the error class and/or error string changes?

Is there a way, where I can produce an Mysql2:Error during my test, that is caused by a unique index error from mysql?

答:
1) Stubbing the save to raise the correct error seems fine to me if the test database isn't throwing the same error :) It's definitely not ideal but at the end of the day it's a test so you just want to ensure you're handling that case the way you expect.  A comment of why though is definitely in order!

2) I believe it's up to how you configure the test database.  From my experience FactoryGirl doesn't throw unique index errors which is particularly annoying...

Title: Test unique index Mysql2:Error in RSpec

Body:
I have a permalink field in my model which has uniqueness validation in Rails and a unique index in MySQL.
When I import data through my API, it happens sometimes, that two requests has the same value for permalink and they try to save at the same time.

In this case, I don't get a uniqueness validation error, I get an error:

ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'permalink123' for key 'index_products_on_permalink'

I deal with this case by warpping save in a rescue block, adding a random value to the end of the permalink and try to save again. When the second save also produces an error, it is raised.

But how do test this behaviour in RSpec? I tried to disable the uniqueness validation during the test with

Product.class_eval do
  validates :permalink, uniqueness: false
end

but this does not throw the MySQL error. I also don't think that stubbing the error with expect(product).to receive(:save).and_raise(Mysql2::Error) is the right way, because what happens when the error class and/or error string changes?

Is there a way, where I can produce an Mysql2:Error during my test, that is caused by a unique index error from mysql?


问:
print wpf window after it has been totally rendered which event?
how to a print wpf window after it has been totally rendered which event?

i have tried using loaded but some of the elements have not finished rendered yet

thanks

答: Read this article it shows you that there currently is no official way of getting notified of the end of the rendering but instead shows you a trick that you could use.</p>


问:
Surefire does not exclude JUnit 5 tests marked with @Tag
I have a JUnit 5 test with two test methods. One is annotated with the tag "slow" and the other with the tag "fast". I have also configured the SureFire plugin with excludeTags in that way that it should ignore the test with the "slow" tag.

I would expect that with this setup only the test with the "fast" tag would be executed but in my case both are. It seems that the @Tag annotations have no effect at all.

Here is the test class:

```<code>package junit5;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

class TaggingTest {

    @Tag("fast")
    @Test
    void fast() {
        System.out.println("*** fast ***");
    }

    @Tag("slow")
    @Test
    void slow() {
        System.out.println("*** slow ***");
    }

}
</code>```

And this is my pom.xml:

```<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>junit5</groupId>
    <artifactId>tagging</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>9</maven.compiler.source>
        <maven.compiler.target>9</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19</version>
                <configuration>
                    <properties>
                        <excludeTags>slow</excludeTags>
                    </properties>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.junit.platform</groupId>
                        <artifactId>junit-platform-surefire-provider</artifactId>
                        <version>1.0.2</version>
                    </dependency>
                    <dependency>
                        <groupId>org.junit.jupiter</groupId>
                        <artifactId>junit-jupiter-engine</artifactId>
                        <version>5.0.2</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.0.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
</code>```

When I run mvn test I've got this output:

```<code>> mvn test
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tagging 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tagging ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tagging ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tagging ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/olaf.prins/temp/junit-tagging/tagging/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tagging ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/olaf.prins/temp/junit-tagging/tagging/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.19:test (default-test) @ tagging ---

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running junit5.TaggingTest
*** fast ***
*** slow ***
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.049 sec - in junit5.TaggingTest

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.800 s
[INFO] Finished at: 2017-11-15T16:36:14+01:00
[INFO] Final Memory: 13M/512M
[INFO] ------------------------------------------------------------------------
</code>```

As you can see both test cases have been run.

As I understand the documentation I've setup up everything correctly. What do I miss?

答: This issue is caused by a bug in the maven-surefire-plugin when it runs on JDK 9: https://issues.apache.org/jira/browse/SUREFIRE-1445</p>

Body:
I have a JUnit 5 test with two test methods. One is annotated with the tag "slow" and the other with the tag "fast". I have also configured the SureFire plugin with excludeTags in that way that it should ignore the test with the "slow" tag.

I would expect that with this setup only the test with the "fast" tag would be executed but in my case both are. It seems that the @Tag annotations have no effect at all.

Here is the test class:

package junit5;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

class TaggingTest {

    @Tag("fast")
    @Test
    void fast() {
        System.out.println("*** fast ***");
    }

    @Tag("slow")
    @Test
    void slow() {
        System.out.println("*** slow ***");
    }

}

And this is my pom.xml:

<?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>junit5</groupId>
    <artifactId>tagging</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>9</maven.compiler.source>
        <maven.compiler.target>9</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19</version>
                <configuration>
                    <properties>
                        <excludeTags>slow</excludeTags>
                    </properties>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.junit.platform</groupId>
                        <artifactId>junit-platform-surefire-provider</artifactId>
                        <version>1.0.2</version>
                    </dependency>
                    <dependency>
                        <groupId>org.junit.jupiter</groupId>
                        <artifactId>junit-jupiter-engine</artifactId>
                        <version>5.0.2</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.0.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

When I run mvn test I've got this output:

> mvn test
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tagging 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tagging ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tagging ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tagging ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/olaf.prins/temp/junit-tagging/tagging/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tagging ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/olaf.prins/temp/junit-tagging/tagging/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.19:test (default-test) @ tagging ---

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running junit5.TaggingTest
*** fast ***
*** slow ***
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.049 sec - in junit5.TaggingTest

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.800 s
[INFO] Finished at: 2017-11-15T16:36:14+01:00
[INFO] Final Memory: 13M/512M
[INFO] ------------------------------------------------------------------------

As you can see both test cases have been run.

As I understand the documentation I've setup up everything correctly. What do I miss?


问:
Trigger snakemake rule-execution upon reference db update
I want to trigger a snakemake rule (essentially a BLAST call) whenever my reference DB (a moderatly-sized fasta file) is updated.

When I pull the latest version of the DB, would snakemake execute the "BLAST" rule, e.g. due to a newer time stamp of the reference file?

What about if I want to see if there is a relevant change in the DB in the first place? So I would first put the reference DB under git version control and make a git diff and execute only if the git diff is non-zero.

How would Snakemake trigger a rule based on a git diff?

答: Snakemake relies on the time stamp for triggering. You can ignore the timestamp by marking a file as ancient (see docs). Then, you can figure out whether you want to update or not and trigger the rule manually via the -R flag. Alternatively you can use a remote provider to download the DB. I guess if the modification date changes on the server, there will also always be a change in the DB.</p>


问:
Click button on page load with div content changed
I have links which change content on click. I want one of the links to be cliked on page load and stay as active. Looks like it works in the below fiddle but when I add it on website this one is loaded :

http://jsfiddle.net/0e91svrr/

I think I have some mistake in JS:

```<code>   <script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">//<![CDATA[
    $(document).ready(function() {
        $('a[class^=question]').click(function(e){
      e.preventDefault();
        var id = $(this).attr("class").replace("question","")
            $('.new_member_box_display').html($('#answer' + id).html());
        })
      document.getElementById("modal").click();

    });//end of ready
    </script>
</code>```

答:
First of all don't used Pure JS with JQuery mixed up, it look so messy :D also I sugest you think about your tags class and ids :)

Try first add event to links and then call click in document ready like this.

```<code>$('a[class^=question]').click(function(e){
    e.preventDefault();
    var id = $(this).attr("class").replace("question","")
    $('.new_member_box_display').html($('#answer' + id).html());
})

$(document).ready(function() {
  $("#modal").click();
});
</code>```

Body:
First of all don't used Pure JS with JQuery mixed up, it look so messy :D also I sugest you think about your tags class and ids :)

Try first add event to links and then call click in document ready like this.

$('a[class^=question]').click(function(e){
    e.preventDefault();
    var id = $(this).attr("class").replace("question","")
    $('.new_member_box_display').html($('#answer' + id).html());
})

$(document).ready(function() {
  $("#modal").click();
});


问:
Find Client Public IP Address Inside Controller of rest web API with out calling external api
I have a web API where I want to capture all incoming request public IP address inside my controller function.

答:
Check below code this must return you IP address of client

```<code>   protected string GetUser_IP()
    {
        string VisitorsIPAddr = string.Empty;
        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
        {
            VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
        }
    return VisitorsIPAddr;
    }
</code>```

For more help: Get public IP Address

Body:
Check below code this must return you IP address of client

   protected string GetUser_IP()
    {
        string VisitorsIPAddr = string.Empty;
        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
        {
            VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
        }
    return VisitorsIPAddr;
    }

For more help: Get public IP Address


问:
CSS Transition not working in IE 11
There is a similar question already here: Css transition not working

The problem is different. I do not use calc() anywhere, neither on the "broken" element nor any related to it.

I have a menu, for selecting the website's language, which I pushed beyond the right border by setting margin-left: 100%;. Clicking a checkbox should trigger it to fall back to margin-left: initial;, thus becoming visible to the user. Clicking the checkbox again, will make the menu disappear again (margin-left: 100%;).

There is a transition: margin-left .4s for both margin-left settings to make it more appealing to the user.

This setting works perfectly with Firefox and Chrome. The language selection slides in from the right, you can click the links for the respective language version and the menu slides out of the window smoothly. Perfectly what I intended.

However, it does not work with IE 11. The menu remains invisible. From reading the question linked above I reckoned it could be connected to not using fixed sizes for the menu. I changed that but to no avail.

In Firefox and Chrome clicking the checkbox triggers the menu to slide in and out of the window as intended. In IE11 the changes in the button's text (basically a p underneath the checkbox) are applied but the menu remains invisible.

Additional Information

Unlike in the question linked I do not use vendor prefixes. However, I tested what happens if I do so and also there I was unsuccessful. I does not seem to be linked to prefix issues either.

Code

This is the code of the element in question:

#language-selection {
 position: relative;
 margin-top: 65px;
 margin-left: 100%;
 transition: margin-left .4s;
}

#language-selection-checkbox:checked ~ #language-selection-wrapper #language-selection {
 margin-left: initial;
 transition: margin-left .4s;
}```

Please also note that adding or removing position: relative; had absolutely no effect on the issue.

答: initial value is not supported by IE , you can check it here, you can try other values, such as auto or any length you like

Title: CSS Transition not working in IE 11

Body:
There is a similar question already here: Css transition not working

The problem is different. I do not use calc() anywhere, neither on the "broken" element nor any related to it.

I have a menu, for selecting the website's language, which I pushed beyond the right border by setting margin-left: 100%;. Clicking a checkbox should trigger it to fall back to margin-left: initial;, thus becoming visible to the user. Clicking the checkbox again, will make the menu disappear again (margin-left: 100%;).

There is a transition: margin-left .4s for both margin-left settings to make it more appealing to the user.

This setting works perfectly with Firefox and Chrome. The language selection slides in from the right, you can click the links for the respective language version and the menu slides out of the window smoothly. Perfectly what I intended.

However, it does not work with IE 11. The menu remains invisible. From reading the question linked above I reckoned it could be connected to not using fixed sizes for the menu. I changed that but to no avail.

In Firefox and Chrome clicking the checkbox triggers the menu to slide in and out of the window as intended. In IE11 the changes in the button's text (basically a p underneath the checkbox) are applied but the menu remains invisible.

Additional Information

Unlike in the question linked I do not use vendor prefixes. However, I tested what happens if I do so and also there I was unsuccessful. I does not seem to be linked to prefix issues either.

Code

This is the code of the element in question:

#language-selection {
 position: relative;
 margin-top: 65px;
 margin-left: 100%;
 transition: margin-left .4s;
}

#language-selection-checkbox:checked ~ #language-selection-wrapper #language-selection {
 margin-left: initial;
 transition: margin-left .4s;
}

Please also note that adding or removing position: relative; had absolutely no effect on the issue.


问:
Check if any of the following siblings have a specified name
The structure of my xml document is as follows. I need to know at element field name = "a" if any of its following siblings have the element name repeatingGroup

```<code><messages>
   <field name = "a">
      <text value = "Cover/>
   </field>
   <field name = "b">
      <text value = "price"/>
   </field>
   <repeatingGroup>
      <field name = "c"/>
      <field name = "d"/>
   </repeatingGroup>
</messages>
</code>```

The code segment I tried so far only  provided the immediate sibling name. In this case field name = "b". Is there a way to check if any of the following siblings have the specified name without using a foreach block? My requirement is to print a value if the condition is true

```<code><xsl:if test="name(following-sibling::*)='repeatingGroup'"></xsl:if>
</code>```

答:
Just Use</p>

```<code> <xsl:if test="following-sibling::repeatingGroup">
   <!-- Your Condition -->
</xsl:if>
</code>```

Body:
The structure of my xml document is as follows. I need to know at element field name = "a" if any of its following siblings have the element name repeatingGroup

<messages>
   <field name = "a">
      <text value = "Cover/>
   </field>
   <field name = "b">
      <text value = "price"/>
   </field>
   <repeatingGroup>
      <field name = "c"/>
      <field name = "d"/>
   </repeatingGroup>
</messages>

The code segment I tried so far only  provided the immediate sibling name. In this case field name = "b". Is there a way to check if any of the following siblings have the specified name without using a foreach block? My requirement is to print a value if the condition is true

<xsl:if test="name(following-sibling::*)='repeatingGroup'"></xsl:if>

Body:
Just Use

 <xsl:if test="following-sibling::repeatingGroup">
   <!-- Your Condition -->
</xsl:if>


问:
How to stop BackgroundWorker correctly
I have a form with 2 comboboxes on it. And I want to fill combobox2.DataSource based on combobox1.Text and combobox2.Text (I assume that the user has completed input in combobox1 and is in the middle of inputting in combobox2). So I have an event handler for combobox2 like this:

```<code>private void combobox2_TextChanged(object sender, EventArgs e)
{
    if (cmbDataSourceExtractor.IsBusy)
       cmbDataSourceExtractor.CancelAsync();

    var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
       V2 = combobox2.Text};
    cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
}
</code>```

As far as building DataSource is time-consuming process (it creates a request to database and executes it) I decided that it's better to perform it in another process using BackgroundWorker. So there's a scenario when cmbDataSourceExtractor hasn't completed its work and the user types one more symbol. In this case I get an exception on this line

cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues ); about that BackgroundWorker is busy and cannot perform several actions in the same time.

How to get rid of this exception?

答:
CancelAsync doesn't actually abort your thread or anything like that. It sends a message to the worker thread that work should be cancelled via BackgroundWorker.CancellationPending. Your DoWork delegate that is being run in the background must periodically check this property and handle the cancellation itself.

The tricky part is that your DoWork delegate is probably blocking, meaning that the work you do on your DataSource must complete before you can do anything else (like check for CancellationPending). You may need to move your actual work to yet another async delegate (or maybe better yet, submit the work to the ThreadPool), and have your main worker thread poll until this inner worker thread triggers a wait state, OR it detects CancellationPending.

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync.aspx

http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx

Title: How to stop BackgroundWorker correctly

Body:
I have a form with 2 comboboxes on it. And I want to fill combobox2.DataSource based on combobox1.Text and combobox2.Text (I assume that the user has completed input in combobox1 and is in the middle of inputting in combobox2). So I have an event handler for combobox2 like this:

private void combobox2_TextChanged(object sender, EventArgs e)
{
    if (cmbDataSourceExtractor.IsBusy)
       cmbDataSourceExtractor.CancelAsync();

    var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
       V2 = combobox2.Text};
    cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
}

As far as building DataSource is time-consuming process (it creates a request to database and executes it) I decided that it's better to perform it in another process using BackgroundWorker. So there's a scenario when cmbDataSourceExtractor hasn't completed its work and the user types one more symbol. In this case I get an exception on this line

cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues ); about that BackgroundWorker is busy and cannot perform several actions in the same time.

How to get rid of this exception?


问:
Technique World tracking performance is being affected by resource constraints
While running an ARKit session with world tracking enabled, the Xcode console shows log messages about (I presume: reduced) tracking performance, even though

The AR Session is in Normal tracking state,

I am using the device in a well-lit office room with plenty of "features" to detect, and

The device moves only subtly.

TLDR: I want to understand what could be causing them, what impact they could have, and how to prevent them, or (re)act to them when they do occur—NB. not simply hide these errors.

```<code>[Technique] World tracking performance is being affected by resource constraints [0]
[Technique] World tracking performance is being affected by resource constraints [1]
</code>```

The Console app shows that these are coming from the library ARKit and fall in the logging category Technique.
Although they sound like warnings, the Console app shows their type as errors.

As expected while using world tracking, the Console app does show a lot of CoreMotion logs around the time of the errors, but those lines do not seem to contain any errors, warnings, or other info that helps me diagnose what's going on.

The moment the errors show up in the log, there are no delegate callbacks, but eventually (anything between 5 seconds or 50 seconds) the screen will freeze with the callback session failed:

```<code>Error Domain=com.apple.arkit.error Code=200 "World tracking failed." UserInfo={NSLocalizedDescription=World tracking failed., NSLocalizedFailureReason=World tracking cannot determine the device's position.}
</code>```

The ARKit source/documentation doesn't provide any hints on what "resource constraints" might have caused the inability to determine the device's position, it just reads:

World tracking has encountered a fatal error.

I've tried (without success) to stop the warnings from appearing by:

Resetting the session tracking: still errors,

Resetting the session with removal of all ARAnchors: still errors,

Disabling plane detection (once no longer needed): still errors.

Pausing the AR Session silences the warnings (makes sense, since it means the device stops tracking its movement while paused), but when resuming the session, the warnings return.

When closing the session and re-creating it (i.e. dismiss VC and recreate), while not having moved the camera (or changed lighting) the problem doesn't always re-occur.

My best guess is that blinking TL-lights are the cause for the tracking performance warnings, given Apple's explanation how world tracking works:

… visual-inertial odometry. This process combines information from the iOS device’s motion sensing hardware with computer vision analysis of the scene visible to the device’s camera. ARKit recognizes notable features in the scene image, tracks differences in the positions of those features across video frames, and compares that information with motion sensing data.

(iPhone 6S, iOS 11 beta 4, no other apps running in the background)

Questions:

What is the difference between [0] and [1]?

What can cause these errors?

What impact do they have while the ARSession hasn't failed (yet)? I'm assuming we'll see "jumpy" models as the world coordinates supplied by the frame updates aren't accurate—NB. after resetting/stopping ARAnchor tracking the errors still occurred.

Will we know if the AR session is about to fail, or will it be unexpected? (Again, the ARSession doesn't fail immediately after the tracking state changes to "limited")

Is there some way to deal with this, e.g. freeing up some of these mentioned "resources"—or other ways to avoid running into these constraints?

答: Only allowing Portrait Device Orientation resolved this error for me.

Body:
While running an ARKit session with world tracking enabled, the Xcode console shows log messages about (I presume: reduced) tracking performance, even though

The AR Session is in Normal tracking state,

I am using the device in a well-lit office room with plenty of "features" to detect, and

The device moves only subtly.

TLDR: I want to understand what could be causing them, what impact they could have, and how to prevent them, or (re)act to them when they do occur—NB. not simply hide these errors.

[Technique] World tracking performance is being affected by resource constraints [0]
[Technique] World tracking performance is being affected by resource constraints [1]

The Console app shows that these are coming from the library ARKit and fall in the logging category Technique.
Although they sound like warnings, the Console app shows their type as errors.

As expected while using world tracking, the Console app does show a lot of CoreMotion logs around the time of the errors, but those lines do not seem to contain any errors, warnings, or other info that helps me diagnose what's going on.

The moment the errors show up in the log, there are no delegate callbacks, but eventually (anything between 5 seconds or 50 seconds) the screen will freeze with the callback session failed:

Error Domain=com.apple.arkit.error Code=200 "World tracking failed." UserInfo={NSLocalizedDescription=World tracking failed., NSLocalizedFailureReason=World tracking cannot determine the device's position.}

The ARKit source/documentation doesn't provide any hints on what "resource constraints" might have caused the inability to determine the device's position, it just reads:

World tracking has encountered a fatal error.

I've tried (without success) to stop the warnings from appearing by:

Resetting the session tracking: still errors,

Resetting the session with removal of all ARAnchors: still errors,

Disabling plane detection (once no longer needed): still errors.

Pausing the AR Session silences the warnings (makes sense, since it means the device stops tracking its movement while paused), but when resuming the session, the warnings return.

When closing the session and re-creating it (i.e. dismiss VC and recreate), while not having moved the camera (or changed lighting) the problem doesn't always re-occur.

My best guess is that blinking TL-lights are the cause for the tracking performance warnings, given Apple's explanation how world tracking works:

… visual-inertial odometry. This process combines information from the iOS device’s motion sensing hardware with computer vision analysis of the scene visible to the device’s camera. ARKit recognizes notable features in the scene image, tracks differences in the positions of those features across video frames, and compares that information with motion sensing data.

(iPhone 6S, iOS 11 beta 4, no other apps running in the background)

Questions:

What is the difference between [0] and [1]?

What can cause these errors?

What impact do they have while the ARSession hasn't failed (yet)? I'm assuming we'll see "jumpy" models as the world coordinates supplied by the frame updates aren't accurate—NB. after resetting/stopping ARAnchor tracking the errors still occurred.

Will we know if the AR session is about to fail, or will it be unexpected? (Again, the ARSession doesn't fail immediately after the tracking state changes to "limited")

Is there some way to deal with this, e.g. freeing up some of these mentioned "resources"—or other ways to avoid running into these constraints?


问:
No module named yaml in python virtual env
I am using CentOS 6.4 with Python 2.6.6 to run Ansible 2.3.0. But when I go into my python virtual env which has python 3.4.1 and run "ansible --version" I get the following error:

```<code>Traceback (most recent call last):
File "/home/namaaror/Desktop/githubansible/bin/ansible", line 80, in <module>
from ansible.cli.adhoc import AdHocCLI as mycli
File "/home/namanarora/Desktop/github/ansible/lib/cli/__init__.py", line 28, in <module>
import yaml
ImportError: No module named 'yaml'
</code>```

I have even tried installing pyyaml by reffering ImportError: No Module named yaml | Ansible
but the error still persists. Is it somewhat related to yaml installation directory and sys.path?

答:
Check out your python3 dist-packages directories /usr/local/lib/pythonX.XX/dist-packages to see if pyyaml is installed there.

If they aren't there, you can install them with sudo apt-get install python3-yaml (you might need python3-setuptools and python3-wheel as well)

Body:
I am using CentOS 6.4 with Python 2.6.6 to run Ansible 2.3.0. But when I go into my python virtual env which has python 3.4.1 and run "ansible --version" I get the following error:

Traceback (most recent call last):
File "/home/namaaror/Desktop/githubansible/bin/ansible", line 80, in <module>
from ansible.cli.adhoc import AdHocCLI as mycli
File "/home/namanarora/Desktop/github/ansible/lib/cli/__init__.py", line 28, in <module>
import yaml
ImportError: No module named 'yaml'

I have even tried installing pyyaml by reffering ImportError: No Module named yaml | Ansible
but the error still persists. Is it somewhat related to yaml installation directory and sys.path?


问:
WritePrivateProfileSection writes with extra caracs
I have a little problem that is driving me crazy.
I have std::string that contains some data, which I wanna save in an INI file.

So I did as below:

```<code>std::string strBuffer;
char line[MAX_BUFFER + 1];

for (int i=0; i < NbrElts; i++)
{
    //Here I get pData filled with data

    sprintf_s(line, "%s%d=%s,%s,%s,%s,%s,%s,%s", "key", i, pData->sType, pData->sId, pData->sName, pData->sCountry, pData->sSite, pData->sCDB, pData->sShortName);
    strBuffer += line;
}

WritePrivateProfileSection("PERSONAL", strBuffer.c_str(), GetMYFile());
</code>```

so at this point, when I use debugger the content of my strBuffer is good, but when the WritePrivateProfileSection is executed I have extra caracters written into my file.

I tried to use conversion before writing in the INI file but with no success.
Any help what may be the clue?

Thank you.

Example :

strBuffer contains "HELLO WORLD" and in my file I get HELLO WORLD נננ

PS: Besides that I missed to add "\0" after each key, the main problem comes from using std::string as it doesn't handle the null
  termination, so even with adding the "\0" I still got the messy output
  ---> Have to change to char[].

答:
string.c_str() is already null-terminated, let's represent this as

```<code>{ 'H', 'i', '\0' };
</code>```

WritePrivateProfileSection expects multiple strings, separated by a single '\0', terminated by '\0\0', e.g. for the two entries x=1 and y=2

```<code>{ 'x', '=', '1', '\0', 'y', '=', '2', '\0', '\0' }
</code>```

The problem with your code is

```<code>s += line;
</code>```

which expects a zero-terminated string on the rhs. You could use:

```<code>int len = sprintf(buffer, "%s=%d\0", key, value); // TODO! Check for error!
s += std::string(line, len); // don't stop at the first '\0'!
</code>```

but at this point I'd use a std::vector<char> instead, since the std::string behavior seems too error-prone here, and we rely on the finer details of what constitutes a string.

Body:
I have a little problem that is driving me crazy.
I have std::string that contains some data, which I wanna save in an INI file.

So I did as below:

std::string strBuffer;
char line[MAX_BUFFER + 1];

for (int i=0; i < NbrElts; i++)
{
    //Here I get pData filled with data

    sprintf_s(line, "%s%d=%s,%s,%s,%s,%s,%s,%s", "key", i, pData->sType, pData->sId, pData->sName, pData->sCountry, pData->sSite, pData->sCDB, pData->sShortName);
    strBuffer += line;
}

WritePrivateProfileSection("PERSONAL", strBuffer.c_str(), GetMYFile());

so at this point, when I use debugger the content of my strBuffer is good, but when the WritePrivateProfileSection is executed I have extra caracters written into my file.

I tried to use conversion before writing in the INI file but with no success.
Any help what may be the clue?

Thank you.

Example :

strBuffer contains "HELLO WORLD" and in my file I get HELLO WORLD נננ

PS: Besides that I missed to add "\0" after each key, the main problem comes from using std::string as it doesn't handle the null
  termination, so even with adding the "\0" I still got the messy output
  ---> Have to change to char[].

Body:
string.c_str() is already null-terminated, let's represent this as

{ 'H', 'i', '\0' };

WritePrivateProfileSection expects multiple strings, separated by a single '\0', terminated by '\0\0', e.g. for the two entries x=1 and y=2

{ 'x', '=', '1', '\0', 'y', '=', '2', '\0', '\0' }

The problem with your code is

s += line;

which expects a zero-terminated string on the rhs. You could use:

int len = sprintf(buffer, "%s=%d\0", key, value); // TODO! Check for error!
s += std::string(line, len); // don't stop at the first '\0'!

but at this point I'd use a std::vector<char> instead, since the std::string behavior seems too error-prone here, and we rely on the finer details of what constitutes a string.


问:
Arduino sprintf (for TX) and scanf (for RX) , why do I get strange output?
I would like to know what I have wrong in my code.

Or is it actually correct?

Currently I have 4 code holding variables namely:

hDroid (0 to 4 digits)

pDroid (0 to 2 digits)

ooDroid (0 to 3 digits)

devDroid (0 to 4 digits)

Which I feed into in a character array (allcode) and then transmit that to the receiving side where they arrive (hopefully in same format?).

The problem is that the output has extra characters and I can't figure out why. Is it just the Arduino Serial Monitor?

Perhaps I am not setting the null character or not allocating enough memory in each or all the arrays.

I have put all into the same sketch in order to test sprintf and scanf perhaps this is the problem.

Desired is:

Send: 1234,12,123,1234

Receive: 1234,12,123,1234

My code is:

//declare "code-holding" vars for send
char hDroid[5] = {
    "1234" }; //4 or less digits/keys eg 1234 + NULL
char pDroid[3] = {
    "21" }; //2 digits/keys eg 12 + NULL
char ooDroid[4] = {
    "123" }; //3 or less digits/keys eg 123 + NULL
char devDroid[5] = {
    "1234" }; //4 or less digits/keys eg 9999 + NULL
char allDroid[18] = {
    '\0' }; //total array count including NULL's

//declare "code-holding" vars for receive
char hDroid1[5] = {
    '\0' }; //4 or less digits/keys eg 1234 + NULL
char pDroid1[3] = {
    '\0' }; //2 digits/keys eg 12 + NULL
char ooDroid1[4] = {
    '\0' }; //3 or less digits/keys eg 123 + NULL
char devDroid1[5] = {
    '\0' }; //4 or less digits/keys eg 9999 + NULL

void setup() {
    Serial.begin(9600);
}

void loop() {
    sprintf(allDroid, "%s,%s,%s,%s", hDroid, pDroid, ooDroid, devDroid);
    Serial.println("This is allDroid "); //show content of allDroid
    Serial.println(allDroid); //show content of allDroid
    delay(1000);
    sscanf(allDroid, "%s,%s,%s,%s", &hDroid1, &pDroid1, &ooDroid1, &devDroid1); // Converts a string to an array

    Serial.println("this is hDroid1,pDroid1,ooDroid1,devDroid1 "); //show content of allDroid

    Serial.println(hDroid1);

    Serial.println(pDroid1);

    Serial.println(ooDroid1);

    Serial.println(devDroid1);

    //clear the arrays
    memset(allDroid, 0, sizeof(allDroid));// This line is for reset the StringReceived
    memset(hDroid1, 0, sizeof(hDroid1));// This line is for reset the StringReceived
    memset(pDroid1, 0, sizeof(pDroid1));// This line is for reset the StringReceived
    memset(ooDroid1, 0, sizeof(ooDroid1));// This line is for reset the StringReceived
    memset(devDroid1, 0, sizeof(devDroid1));// This line is for reset the StringReceived
}
```

<p>And the output is:</p>

```This is allDroid
1234,21,123,1234
this is hDroid1,pDroid1,ooDroid1,devDroid1
1234,21,123,1234
21,123,1234
123,1234
1234
```

答:
It seems this is only when using the serial monitor on arduino IDE 1.0.5-r2, I tried the same code on Arduino IDE version 1.6.5 and the 'strange characters are gone from the output window !

    This is allDroid
    1234,21,123,1234
    this is hDroid1,pDroid1,ooDroid1,devDroid1
    1234,21,123,1234

As a sanity check could some kind soul please just check my code for correctness in terms of the arrays and their dimensions and Null terminations ?

Body:
I would like to know what I have wrong in my code.

Or is it actually correct?

Currently I have 4 code holding variables namely:

hDroid (0 to 4 digits)

pDroid (0 to 2 digits)

ooDroid (0 to 3 digits)

devDroid (0 to 4 digits)

Which I feed into in a character array (allcode) and then transmit that to the receiving side where they arrive (hopefully in same format?).

The problem is that the output has extra characters and I can't figure out why. Is it just the Arduino Serial Monitor?

Perhaps I am not setting the null character or not allocating enough memory in each or all the arrays.

I have put all into the same sketch in order to test sprintf and scanf perhaps this is the problem.

Desired is:

Send: 1234,12,123,1234

Receive: 1234,12,123,1234

My code is:

//declare "code-holding" vars for send
char hDroid[5] = {
    "1234" }; //4 or less digits/keys eg 1234 + NULL
char pDroid[3] = {
    "21" }; //2 digits/keys eg 12 + NULL
char ooDroid[4] = {
    "123" }; //3 or less digits/keys eg 123 + NULL
char devDroid[5] = {
    "1234" }; //4 or less digits/keys eg 9999 + NULL
char allDroid[18] = {
    '\0' }; //total array count including NULL's

//declare "code-holding" vars for receive
char hDroid1[5] = {
    '\0' }; //4 or less digits/keys eg 1234 + NULL
char pDroid1[3] = {
    '\0' }; //2 digits/keys eg 12 + NULL
char ooDroid1[4] = {
    '\0' }; //3 or less digits/keys eg 123 + NULL
char devDroid1[5] = {
    '\0' }; //4 or less digits/keys eg 9999 + NULL

void setup() {
    Serial.begin(9600);
}

void loop() {
    sprintf(allDroid, "%s,%s,%s,%s", hDroid, pDroid, ooDroid, devDroid);
    Serial.println("This is allDroid "); //show content of allDroid
    Serial.println(allDroid); //show content of allDroid
    delay(1000);
    sscanf(allDroid, "%s,%s,%s,%s", &hDroid1, &pDroid1, &ooDroid1, &devDroid1); // Converts a string to an array

    Serial.println("this is hDroid1,pDroid1,ooDroid1,devDroid1 "); //show content of allDroid

    Serial.println(hDroid1);

    Serial.println(pDroid1);

    Serial.println(ooDroid1);

    Serial.println(devDroid1);

    //clear the arrays
    memset(allDroid, 0, sizeof(allDroid));// This line is for reset the StringReceived
    memset(hDroid1, 0, sizeof(hDroid1));// This line is for reset the StringReceived
    memset(pDroid1, 0, sizeof(pDroid1));// This line is for reset the StringReceived
    memset(ooDroid1, 0, sizeof(ooDroid1));// This line is for reset the StringReceived
    memset(devDroid1, 0, sizeof(devDroid1));// This line is for reset the StringReceived
}

And the output is:

This is allDroid
1234,21,123,1234
this is hDroid1,pDroid1,ooDroid1,devDroid1
1234,21,123,1234
21,123,1234
123,1234
1234


问:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.

Is there a performance benefit to replacing == with ===?

Any performance improvement would be welcomed as many comparison operators exist.

If no type conversion takes place, would there be a performance gain over ==?

答:
Strict equality is for the most part better

The fact that Javascript is a loosely typed language needs to be in the front of your mind constantly as you work with it. As long as the data structure is the same there really is no reason as to not use strict equality, with regular equality you often have an implicit conversion of values that happens automatically, this can have far-reaching effects on your code. It is very easy to have problems with this conversion seeing as they happen automatically.

With strict equality there is no automatic implicit conversion as the values must already be of the correct data structure.


问:
why "abc" + null results abcnull
why "abc" + null  results abcnull

```<code>String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);
</code>```

Result: abcnull

答:
That's exactly the value that's guaranteed by the language specification. From the JLS section 15.8.1.1, which talks about the string conversions used for string concatenation:

Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

(You may be interested to hear that .NET takes a different approach, converting a null reference to an empty string. Each approach has its pros and cons - I find the Java approach more useful for creating a string for debugging, but the .NET approach more useful when building a string to be displayed to a user or saved to a data file etc.)

Title: why "abc" + null results abcnull

Body:
why "abc" + null  results abcnull

String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);

Result: abcnull