问:
C++ variadic expansion using deduction
I'm developing a library that deals with non typed C functions (SQLite) and I want to strong typing it.

The idea is to have a FieldDef strong type that allow user to tie raw types like int, double and std::string to weak db types.
My problem is that the semantic of the library is very heavy, and I would like to add some automatic type deduction.

So I have a bunch of "basic types":

```<code>namespace FieldType {
  struct Integer { using rawtype = int; };
  struct Real{ using rawtype = double; };
  struct Text{ using rawtype = std::string; };
  struct Blob{ using rawtype = std::vector<uint8_t>; };
}
</code>```

I also have a insert and a query functions that allow inserting and querying the tables without using SQL statements. The query will be plain select. Anyway. The intended use is:

```<code>FieldDef<FieldType::Integer> mId = makeFieldDef("id", FieldType::Integer()).primaryKey().autoincrement();
FieldDef<FieldType::Text> mName = makeFieldDef("name", FieldType::Text());
FieldDef<FieldType::Integer> mValue = makeFieldDef("value", FieldType::Integer());

SQLiteTable::insert(std::make_tuple(mName, mValue), std::make_tuple(record.name, record.value));

std::vector<Record> r;
SQLiteTable::query
            (std::make_tuple(mName, mValue), [&r](std::tuple<std::string, int> res) {
        r.push_back(Record{std::get<0>(res), std::get<1>(res)});
});
</code>```

I implemented the insert this way:

```<code>template <typename ...Ts, typename ...Us>
bool insert (std::tuple<Ts...> def, std::tuple<Us...> values) {
    std::ostringstream ss;
    ss << "INSERT INTO " << mName << "("
                                  << buildSqlInsertFieldList<0>(def)
                                  << ") VALUES ("
                                  << buildSqlInsertValuesListPlaceholder<0>(values)
                                  << ");";
    auto stmt = newStatement(ss.str());
    bindAllValues<0>(stmt.get(), values);
    return execute(stmt.get());
}
</code>```

This works fine, the problems come with query:

```<code>template <typename ...Ts, typename ...Us>
void query(std::tuple<Ts...> def, std::function<void(std::tuple<Us...>)> resultFeedbackFunc) {
   ...
}
</code>```

When calling it the compiler is unable to correctly deduce the types, so I guess it requires a pedantic construction:

```<code>SQLiteTable::query<FieldType::Text, FieldType::Integer, /* whatever */> (...)
</code>```

It's unpractical and verbose.

Would it be possible to simplify the query function?
Since we have a constrain in the usage, that is the Us pack can only be some type compatible with FieldType::*:rawtype, I am asking if it would be possible to use some construct that unpacks and apply a method. In case of insert, could it be simplified with something like:

```<code>template<typename Ts...>
bool insert (std::tuple<Ts...> def, std::tuple<Ts::rawtype ...> values)
</code>```

instead of using tuples, what about using Variadic Packs? I haven't tested it but I fear that using something like

```<code>template<typename Ts..., typename Us....>
bool insert (Ts... def, Us ... values)
</code>```

would confuse the compiler and would make things worse.
What do you think?

If it is possible to use the actual implementation of query, what would be a workaround to make the usage code more expressive?

Here are some details about the code, to explain:

The query function is implemented using the following pseudocode:

```<code>template <typename ...Ts, typename ...Us>
void query(std::tuple<Ts...> def, std::function<void(std::tuple<Us...>)> resultFeedbackFunc) {
    std::ostringstream ss;
    ss << "SELECT " << buildSqlInsertFieldList<0>(def) << " FROM " << mName <<";";
    auto stmt = newStatement(ss.str());

    auto r = execute(stmt.get());
    SQLiteException::throwIfNotOk(r, db()->handle());

    while (hasData(stmt.get())) {
        auto nColumns = columnCount(stmt.get());
        if (nColumns != sizeof...(Ts))
            throw std::runtime_error("Column count differs from data size");

        std::tuple<Us...> res;
        getAllValues<0>(stmt.get(), res);
        resultFeedbackFunc(res);
    }
};
</code>```

Statement is an opaque type that hides the sqlite statement structure, as do the other functions used in the query method newStatement, execute and columnsCount. The function getAllValues uses recursion to fill the tuple. So the functor resultFeedbackFunc() will be called for every row of the database. So the client code can, for example, fill a container (like a vector).

Update:

I followed  @bolov's solution, and added @massimiliano-jones's improvements.

This is the correct implementation of the inner call to the feedback function:

```<code>resultFeedbackFunc(getValueR<decltype (std::get<Is>(def).rawType())>
      (stmt.get(), Is)...);
</code>```

getValueR makes the internal call to sqlite_column_xxx(sqlite3_stmt *, int index). If I understand correctly, the unpacking works because the arguments list is a valid context for unpacking. If I wanted the calls to be made outside the arguments, I had to make a folding (or workaround since I'm using c++11).

答:
instead of using tuples, what about using Variadic Packs?

you may try something like

```<code>template<typename T,typename V>
struct FieldInsert{ V const& ref; };

template<typename T>
struct FieldDef
{
  template<typename V>
  auto operator()( V const& value ) const{ return FieldInsert<T,V>{value}; }
};

template<typename... T>
bool insert( T... args )
{
  // defines buildSqlInsertFieldList and buildSqlInsertValuesListPlaceholder the obvious way ...
}

// to be used as

SQLiteTable::insert( mName(record.name), mValue(record.value) );
</code>```

this is more readable than the tuple version: firstly, fields count is automatically equal to values count, then, each value comes next to its field, it supports 'default' field values ( via, say, mName()), ...

regarding query(), more expressive alternatives might be

```<code>// return a lazily evaluated input-range (or a coroutine?)
for( auto item: SQLiteTable::query( mName, mValue ) )
  // ...

// and/or query() simply returns a forwarding wrapper exposing, say, a chainable interface ...
SQLiteTable::query( mName, mValue ).for_each([]/*lambda*/);
</code>```

Title: C++ variadic expansion using deduction

Body:
I'm developing a library that deals with non typed C functions (SQLite) and I want to strong typing it.

The idea is to have a FieldDef strong type that allow user to tie raw types like int, double and std::string to weak db types.
My problem is that the semantic of the library is very heavy, and I would like to add some automatic type deduction.

So I have a bunch of "basic types":

namespace FieldType {
  struct Integer { using rawtype = int; };
  struct Real{ using rawtype = double; };
  struct Text{ using rawtype = std::string; };
  struct Blob{ using rawtype = std::vector<uint8_t>; };
}

I also have a insert and a query functions that allow inserting and querying the tables without using SQL statements. The query will be plain select. Anyway. The intended use is:

FieldDef<FieldType::Integer> mId = makeFieldDef("id", FieldType::Integer()).primaryKey().autoincrement();
FieldDef<FieldType::Text> mName = makeFieldDef("name", FieldType::Text());
FieldDef<FieldType::Integer> mValue = makeFieldDef("value", FieldType::Integer());

SQLiteTable::insert(std::make_tuple(mName, mValue), std::make_tuple(record.name, record.value));

std::vector<Record> r;
SQLiteTable::query
            (std::make_tuple(mName, mValue), [&r](std::tuple<std::string, int> res) {
        r.push_back(Record{std::get<0>(res), std::get<1>(res)});
});

I implemented the insert this way:

template <typename ...Ts, typename ...Us>
bool insert (std::tuple<Ts...> def, std::tuple<Us...> values) {
    std::ostringstream ss;
    ss << "INSERT INTO " << mName << "("
                                  << buildSqlInsertFieldList<0>(def)
                                  << ") VALUES ("
                                  << buildSqlInsertValuesListPlaceholder<0>(values)
                                  << ");";
    auto stmt = newStatement(ss.str());
    bindAllValues<0>(stmt.get(), values);
    return execute(stmt.get());
}

This works fine, the problems come with query:

template <typename ...Ts, typename ...Us>
void query(std::tuple<Ts...> def, std::function<void(std::tuple<Us...>)> resultFeedbackFunc) {
   ...
}

When calling it the compiler is unable to correctly deduce the types, so I guess it requires a pedantic construction:

SQLiteTable::query<FieldType::Text, FieldType::Integer, /* whatever */> (...)

It's unpractical and verbose.

Would it be possible to simplify the query function?
Since we have a constrain in the usage, that is the Us pack can only be some type compatible with FieldType::*:rawtype, I am asking if it would be possible to use some construct that unpacks and apply a method. In case of insert, could it be simplified with something like:

template<typename Ts...>
bool insert (std::tuple<Ts...> def, std::tuple<Ts::rawtype ...> values)

instead of using tuples, what about using Variadic Packs? I haven't tested it but I fear that using something like

template<typename Ts..., typename Us....>
bool insert (Ts... def, Us ... values)

would confuse the compiler and would make things worse.
What do you think?

If it is possible to use the actual implementation of query, what would be a workaround to make the usage code more expressive?

Here are some details about the code, to explain:

The query function is implemented using the following pseudocode:

template <typename ...Ts, typename ...Us>
void query(std::tuple<Ts...> def, std::function<void(std::tuple<Us...>)> resultFeedbackFunc) {
    std::ostringstream ss;
    ss << "SELECT " << buildSqlInsertFieldList<0>(def) << " FROM " << mName <<";";
    auto stmt = newStatement(ss.str());

    auto r = execute(stmt.get());
    SQLiteException::throwIfNotOk(r, db()->handle());

    while (hasData(stmt.get())) {
        auto nColumns = columnCount(stmt.get());
        if (nColumns != sizeof...(Ts))
            throw std::runtime_error("Column count differs from data size");

        std::tuple<Us...> res;
        getAllValues<0>(stmt.get(), res);
        resultFeedbackFunc(res);
    }
};

Statement is an opaque type that hides the sqlite statement structure, as do the other functions used in the query method newStatement, execute and columnsCount. The function getAllValues uses recursion to fill the tuple. So the functor resultFeedbackFunc() will be called for every row of the database. So the client code can, for example, fill a container (like a vector).

Update:

I followed  @bolov's solution, and added @massimiliano-jones's improvements.

This is the correct implementation of the inner call to the feedback function:

resultFeedbackFunc(getValueR<decltype (std::get<Is>(def).rawType())>
      (stmt.get(), Is)...);

getValueR makes the internal call to sqlite_column_xxx(sqlite3_stmt *, int index). If I understand correctly, the unpacking works because the arguments list is a valid context for unpacking. If I wanted the calls to be made outside the arguments, I had to make a folding (or workaround since I'm using c++11).

Body:
instead of using tuples, what about using Variadic Packs?

you may try something like

template<typename T,typename V>
struct FieldInsert{ V const& ref; };

template<typename T>
struct FieldDef
{
  template<typename V>
  auto operator()( V const& value ) const{ return FieldInsert<T,V>{value}; }
};

template<typename... T>
bool insert( T... args )
{
  // defines buildSqlInsertFieldList and buildSqlInsertValuesListPlaceholder the obvious way ...
}

// to be used as

SQLiteTable::insert( mName(record.name), mValue(record.value) );

this is more readable than the tuple version: firstly, fields count is automatically equal to values count, then, each value comes next to its field, it supports 'default' field values ( via, say, mName()), ...

regarding query(), more expressive alternatives might be

// return a lazily evaluated input-range (or a coroutine?)
for( auto item: SQLiteTable::query( mName, mValue ) )
  // ...

// and/or query() simply returns a forwarding wrapper exposing, say, a chainable interface ...
SQLiteTable::query( mName, mValue ).for_each([]/*lambda*/);


来源: stackexchange

问:
Change color of drawableLeft icon in android textview
How to change the color of drawable icon which is set to textview in android using drawableLeft?</p>

答:
Create a png/jpeg file of icon with specific color and use it in xml file

```<code> android:drawableLeft="@drawable/icon_With_Custom_color"
</code>```

For custom Icons refrer following image

ContentLicense: CC BY-SA 3.0

Body:
Create a png/jpeg file of icon with specific color and use it in xml file

 android:drawableLeft="@drawable/icon_With_Custom_color"

For custom Icons refrer following image


问:
Getting out of memory error while reading parquet file in spark submit job
```<code>[Stage 0:>                                                          (0 + 0) / 8]SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
[Stage 1:=====================================================>   (43 + 3) / 46]17/11/16 13:11:18 ERROR Executor: Exception in task 0.0 in stage 2.0 (TID 54)
java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3236)
    at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118)
    at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93)
    at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153)
    at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1877)
    at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1786)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1189)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:44)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:84)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:240)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
17/11/16 13:11:18 ERROR SparkUncaughtExceptionHandler: Uncaught exception in thread Thread[Executor task launch worker-4,5,main]
java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3236)
    at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118)
    at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93)
    at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153)
    at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1877)
    at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1786)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1189)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:44)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:84)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:240)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
17/11/16 13:11:18 WARN TaskSetManager: Lost task 0.0 in stage 2.0 (TID 54, localhost): java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3236)
    at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118)
    at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93)
    at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153)
    at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1877)
    at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1786)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1189)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:44)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:84)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:240)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

This is my code-

```<code>val sqlContext = new SQLContext(sc)
    //sqlContext.setConf("spark.sql.inMemoryColumnarStorage.compressed", "true")
    log.setLevel(Level.INFO)
    val config = HBaseConfiguration.create()
    val newDataDF = sqlContext.read.parquet(file)
    newDataDF.registerTempTable("newDataDF")
    //sqlContext.cacheTable("newDataDF")
    val result = sqlContext.sql("SELECT rec FROM newDataDF")
    val rows = result.map(t => t(0)).collect()
    //val rows = result.map(t => t.getAs[String]("rec"))
</code>```

It throws out of memory at below line
//val rows = result.map(t => t(0)).collect()

Have tried all options of memory tuning and increasing executor/driver memory increase, but nothing seems to work.
Any advise would be greatly appreciated.

答: you have to increase spark.driver.memory which default value is 1gb. you can check the driver and executor memory using --verbose command. For more information check this link and set the memory as per your requirement. https://spark.apache.org/docs/latest/configuration.html

Body:
[Stage 0:>                                                          (0 + 0) / 8]SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
[Stage 1:=====================================================>   (43 + 3) / 46]17/11/16 13:11:18 ERROR Executor: Exception in task 0.0 in stage 2.0 (TID 54)
java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3236)
    at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118)
    at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93)
    at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153)
    at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1877)
    at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1786)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1189)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:44)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:84)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:240)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
17/11/16 13:11:18 ERROR SparkUncaughtExceptionHandler: Uncaught exception in thread Thread[Executor task launch worker-4,5,main]
java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3236)
    at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118)
    at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93)
    at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153)
    at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1877)
    at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1786)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1189)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:44)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:84)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:240)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
17/11/16 13:11:18 WARN TaskSetManager: Lost task 0.0 in stage 2.0 (TID 54, localhost): java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3236)
    at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118)
    at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93)
    at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153)
    at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1877)
    at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1786)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1189)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:44)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:84)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:240)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

This is my code-

val sqlContext = new SQLContext(sc)
    //sqlContext.setConf("spark.sql.inMemoryColumnarStorage.compressed", "true")
    log.setLevel(Level.INFO)
    val config = HBaseConfiguration.create()
    val newDataDF = sqlContext.read.parquet(file)
    newDataDF.registerTempTable("newDataDF")
    //sqlContext.cacheTable("newDataDF")
    val result = sqlContext.sql("SELECT rec FROM newDataDF")
    val rows = result.map(t => t(0)).collect()
    //val rows = result.map(t => t.getAs[String]("rec"))

It throws out of memory at below line
//val rows = result.map(t => t(0)).collect()

Have tried all options of memory tuning and increasing executor/driver memory increase, but nothing seems to work.
Any advise would be greatly appreciated.


问:
Can/Should I Use an Asynchronous Controller Here? (ASP.NET MVC 3)
I have this [HttpPost] action method:

```<code>[HttpPost]
public ActionResult AddReview(Review review)
{
   repository.Add(review);
   repository.Save();
   repository.UpdateSystemScoring(review.Id); // call SPROC with new Review ID.
   return View("Success", review);
}
</code>```

So, basically a user clicks a button, i add it to my database (via Entity Framework 4.0), save changes, and then i call a stored procedure with the identity field, which is that second last line of code.

This needs to be done after the review is saved (as the identity field is only created once Save is called, and EF persists the changes), and it is a system-wide calculation.

From the user point of view, he/she doesn't/shouldn't care that this calculation is happening.

This procedure can take anywhere from 0-20 seconds. It does not return anything.

Is this a candidate for an asynchronous controller?

Is there a way i can add the Review, and let another asynchronous controller handle the long-running SPROC call, so the user can be taken to the Success page immediately?

I must admit (partially ashamed of this): this is a rewrite of an existing system, and in the original system (ASP.NET Web Forms), i fired off another thread in order to achieve the above task - which is why i was wondering if the same principal can be applied to ASP.NET MVC 3.

I always try and avoid multi-threading in ASP.NET but user experience is the #1 priority, and i do not want the page timing out.

So - is this possible? Also happy to hear any other ideas. Also - i can't use triggers here, don't really want to go into too much detail why - but i can't.

答:
Since the scoring system takes so long to run I would recommend using a scheduled task in SQL Server or Windows to update the scores every x amount of minutes.  Since the user doesn't know about the request it don't matter to run immediately.

You could add the ID's to a queue and process the queue every 30 minutes.

Otherwise if there is a reason this needs to be run immediately you could do an asyc call or see if you could trim some fat of the stored proc.

ContentLicense: CC BY-SA 2.5

Body:
I have this [HttpPost] action method:

[HttpPost]
public ActionResult AddReview(Review review)
{
   repository.Add(review);
   repository.Save();
   repository.UpdateSystemScoring(review.Id); // call SPROC with new Review ID.
   return View("Success", review);
}

So, basically a user clicks a button, i add it to my database (via Entity Framework 4.0), save changes, and then i call a stored procedure with the identity field, which is that second last line of code.

This needs to be done after the review is saved (as the identity field is only created once Save is called, and EF persists the changes), and it is a system-wide calculation.

From the user point of view, he/she doesn't/shouldn't care that this calculation is happening.

This procedure can take anywhere from 0-20 seconds. It does not return anything.

Is this a candidate for an asynchronous controller?

Is there a way i can add the Review, and let another asynchronous controller handle the long-running SPROC call, so the user can be taken to the Success page immediately?

I must admit (partially ashamed of this): this is a rewrite of an existing system, and in the original system (ASP.NET Web Forms), i fired off another thread in order to achieve the above task - which is why i was wondering if the same principal can be applied to ASP.NET MVC 3.

I always try and avoid multi-threading in ASP.NET but user experience is the #1 priority, and i do not want the page timing out.

So - is this possible? Also happy to hear any other ideas. Also - i can't use triggers here, don't really want to go into too much detail why - but i can't.


问:
Toad format sql statement in one row
How can I change the formatter in toad or maybe sql developer to format my sql statements automatically in one row statement.

Here one Example:
This is my start which I wanna to format.

```<code>BEGIN
    db_package.drop_table ('test');
END;

CREATE TABLE mytable
(
    Column                     VARCHAR2 (1 CHAR)
);
...
</code>```

This is my goal formatted statement.

```<code>BEGIN    db_package.drop_table ('test');END;
CREATE TABLE mytable(    Column                     VARCHAR2 (1 CHAR));
...
</code>```

So I want to format the statements so that I get every statement in one row.

答:
TOAD FOR ORACLE

SHIFT+CTRL+F should help you

To format a statement Select the statement you want to select and click » on the Edit toolbar.

To format an entire script Click » on the Edit toolbar.

Tip:You can also right-click the script and select Formatting Tools |
Format Code.

To achieve the exact formatting you may need to play around with the 'Oracle Formatter Options'

Title: Toad format sql statement in one row

Body:
How can I change the formatter in toad or maybe sql developer to format my sql statements automatically in one row statement.

Here one Example:
This is my start which I wanna to format.

BEGIN
    db_package.drop_table ('test');
END;

CREATE TABLE mytable
(
    Column                     VARCHAR2 (1 CHAR)
);
...

This is my goal formatted statement.

BEGIN    db_package.drop_table ('test');END;
CREATE TABLE mytable(    Column                     VARCHAR2 (1 CHAR));
...

So I want to format the statements so that I get every statement in one row.


问:
How do i display a FormArray of GroupLists?
I am trying to make an interactive form that on each row lists an item together with a remove button (called verwijderen in my example). These items are retrieved from the database and each instantiated as a custom object called LaborPeriod.

These objects are then transformed into FormGroup object and then added to a FormArray. The definition of this formgroup is the following:

```<code>  let formGroup = this.fb.group({
    id: this.account.laborperiods[i].id,
    beginDate: this.account.laborperiods[i].beginDate,
    endDate: this.account.laborperiods[i].endDate,
    hours: this.account.laborperiods[i].hours,
    account: this.account.laborperiods[i].account
  })
  if(!this.laborPeriodArray){
    this.laborPeriodArray = new FormArray([])
  }
  this.laborPeriodArray.push(formGroup)
}
</code>```

The definition of the laborPeriodArray in the main FormGroup is also laborPeriodArray. The main FormGroup looks like the following:

```<code>  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private router: Router,
              private accountService: AccountService) {
    this.title = "Account aanpassen";
    //console.log(this.account.enabled + " : " + this.account.role)
    this.accountUpdateForm = this.fb.group({
      name: [''],
      username: ['', [Validators.required, Validators.email]],
      status: '',
      permission:'',
      laborPeriodArray:this.fb.array([])
    });
  }
</code>```

The entire component looks like this: Here you can see that laborPeriodArray gets initialized in the onInit method.

```<code>  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private router: Router,
              private accountService: AccountService) {
    this.title = "Account aanpassen";
    //console.log(this.account.enabled + " : " + this.account.role)
    this.accountUpdateForm = this.fb.group({
      name: [''],
      username: ['', [Validators.required, Validators.email]],
      status: '',
      permission:'',
      laborPeriodArray:this.fb.array([])
    });
  }

  ngOnInit(): void {
    let formGroupArray: FormGroup[] = [];
    this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.accountService.getAccount(params.get("id")))
      .subscribe(account => {
        this.account = account;
        for(let i=0; i < account.laborperiods.length; i++){
          let formGroup = this.fb.group({
            id: this.account.laborperiods[i].id,
            beginDate: this.account.laborperiods[i].beginDate,
            endDate: this.account.laborperiods[i].endDate,
            hours: this.account.laborperiods[i].hours,
            account: this.account.laborperiods[i].account
          })
          if(!this.laborPeriodArray){
            this.laborPeriodArray = new FormArray([])
          }
          this.laborPeriodArray.push(formGroup)
        }
        console.log("laborPeriod" + JSON.stringify(this.laborPeriodArray.length))

        this.ngOnChanges();
      });
  }

  ngOnChanges(): void {
    if (this.account !== undefined) {
      this.accountUpdateForm.reset({
        name: this.account.name,
        username: this.account.username,
        status: this.account.enabled,
        permission: this.account.admin,
        laborPeriodArray: this.laborPeriodArray
      });
    }
  }
</code>```

All the FormGroup items are added but not displayed. The rows are blank. This is the relevant snippet from my HTML page

```<code><table class="table table-hover">
      <thead>
      <tr>
        <th>Begin datum</th>
        <th>Eind datum</th>
        <th>Aantal uren</th>
        <th>Actie</th>
      </tr>
      </thead>
      <tbody>
      <tr formArrayName="laborPeriodArray" *ngFor = "let laborperiod of laborPeriodArray.controls; let i = index" [formGroupName]="i">
        <td formControlName="beginDate">{{laborperiod.value.get('beginDate') | date:'yyyy-MM-dd'}}</td>
        <td formControlName="endDate">{{laborperiod.value.get('endDate') | date:'yyyy-MM-dd'}}</td>
        <td formControlName="hours">{{laborperiod.value.get('hours')}}</td>
        <button type="button" class="btn btn-default">
          <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
          Verwijderen
        </button>
      </tr>
</code>```

This is giving me the browser error ERROR Error: Cannot find control with unspecified name attribute but I am specifying the formControlName for each td row. So I don't understand what is causing the error. Furthermore I would also like to know how I can link the Remove button to the data corresponding to each row. I take it I have to use the index I for this but i'm not sure.

EDIT:

After applying AJT_82's solution I still don't have it working. It appears to have something to do with the database retrieved data itself. When I add the example account array of AJT_82 to my ngOnInit() like so:

```<code>  account1 = { laborperiods: [{ id: 1, hours:11 }, { id: 2, hours:22 }, { id: 3, hours:33 }] }

  ngOnInit(): void {
    this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.accountService.getAccount(params.get("id")))
      .subscribe(account => {
        this.account = account;
        for(let i=0; i < account.laborperiods.length; i++){
          let formGroup = this.fb.group({
            id: this.account1.laborperiods[i].id,
            beginDate: this.account.laborperiods[i].beginDate,
            endDate: this.account.laborperiods[i].endDate,
            hours: this.account1.laborperiods[i].hours,
            account: this.account.laborperiods[i].account
          })
          this.laborPeriodArray.push(formGroup)
        }
        console.log(JSON.stringify(account.laborperiods[0].beginDate))
        this.ngOnChanges();
      });
  }
</code>```

it works but it shows only 3 rows. That's the total length of the example account array.

This is the account class:

```<code>export class Account {
  id: number;
  username: string;
  name: string;
  enabled: boolean
  password: string;
  person: Person;
  admin: boolean;
  laborperiods: LaborPeriod[]
  remainingLeaveHours:number;
}
</code>```

and this is the LaborPeriod class:

```<code>export class LaborPeriod{
    id: number
    beginDate: Date
    endDate: Date
    hours: number
    account: Account
}
</code>```

Is there anything wrong with its field declarations?

答:
Try replacing

```<code>laborperiod.value.get('beginDate')
</code>```

By

```<code>laborperiod.value['beginDate']
</code>```

I also recommande that you FormGroup variable to be a Class attribute and not a OnInit() one.

I also recommande using ReactiveForms with it's API FormControls.

Let me know what happened

Body:
I am trying to make an interactive form that on each row lists an item together with a remove button (called verwijderen in my example). These items are retrieved from the database and each instantiated as a custom object called LaborPeriod.

These objects are then transformed into FormGroup object and then added to a FormArray. The definition of this formgroup is the following:

  let formGroup = this.fb.group({
    id: this.account.laborperiods[i].id,
    beginDate: this.account.laborperiods[i].beginDate,
    endDate: this.account.laborperiods[i].endDate,
    hours: this.account.laborperiods[i].hours,
    account: this.account.laborperiods[i].account
  })
  if(!this.laborPeriodArray){
    this.laborPeriodArray = new FormArray([])
  }
  this.laborPeriodArray.push(formGroup)
}

The definition of the laborPeriodArray in the main FormGroup is also laborPeriodArray. The main FormGroup looks like the following:

  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private router: Router,
              private accountService: AccountService) {
    this.title = "Account aanpassen";
    //console.log(this.account.enabled + " : " + this.account.role)
    this.accountUpdateForm = this.fb.group({
      name: [''],
      username: ['', [Validators.required, Validators.email]],
      status: '',
      permission:'',
      laborPeriodArray:this.fb.array([])
    });
  }

The entire component looks like this: Here you can see that laborPeriodArray gets initialized in the onInit method.

  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private router: Router,
              private accountService: AccountService) {
    this.title = "Account aanpassen";
    //console.log(this.account.enabled + " : " + this.account.role)
    this.accountUpdateForm = this.fb.group({
      name: [''],
      username: ['', [Validators.required, Validators.email]],
      status: '',
      permission:'',
      laborPeriodArray:this.fb.array([])
    });
  }

  ngOnInit(): void {
    let formGroupArray: FormGroup[] = [];
    this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.accountService.getAccount(params.get("id")))
      .subscribe(account => {
        this.account = account;
        for(let i=0; i < account.laborperiods.length; i++){
          let formGroup = this.fb.group({
            id: this.account.laborperiods[i].id,
            beginDate: this.account.laborperiods[i].beginDate,
            endDate: this.account.laborperiods[i].endDate,
            hours: this.account.laborperiods[i].hours,
            account: this.account.laborperiods[i].account
          })
          if(!this.laborPeriodArray){
            this.laborPeriodArray = new FormArray([])
          }
          this.laborPeriodArray.push(formGroup)
        }
        console.log("laborPeriod" + JSON.stringify(this.laborPeriodArray.length))

        this.ngOnChanges();
      });
  }

  ngOnChanges(): void {
    if (this.account !== undefined) {
      this.accountUpdateForm.reset({
        name: this.account.name,
        username: this.account.username,
        status: this.account.enabled,
        permission: this.account.admin,
        laborPeriodArray: this.laborPeriodArray
      });
    }
  }

All the FormGroup items are added but not displayed. The rows are blank. This is the relevant snippet from my HTML page

        Begin datum
        Eind datum
        Aantal uren
        Actie

        {{laborperiod.value.get('beginDate') | date:'yyyy-MM-dd'}}
        {{laborperiod.value.get('endDate') | date:'yyyy-MM-dd'}}
        {{laborperiod.value.get('hours')}}
        <button type="button" class="btn btn-default">

          Verwijderen
        </button>

This is giving me the browser error ERROR Error: Cannot find control with unspecified name attribute but I am specifying the formControlName for each td row. So I don't understand what is causing the error. Furthermore I would also like to know how I can link the Remove button to the data corresponding to each row. I take it I have to use the index I for this but i'm not sure.

EDIT:

After applying AJT_82's solution I still don't have it working. It appears to have something to do with the database retrieved data itself. When I add the example account array of AJT_82 to my ngOnInit() like so:

  account1 = { laborperiods: [{ id: 1, hours:11 }, { id: 2, hours:22 }, { id: 3, hours:33 }] }

  ngOnInit(): void {
    this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.accountService.getAccount(params.get("id")))
      .subscribe(account => {
        this.account = account;
        for(let i=0; i < account.laborperiods.length; i++){
          let formGroup = this.fb.group({
            id: this.account1.laborperiods[i].id,
            beginDate: this.account.laborperiods[i].beginDate,
            endDate: this.account.laborperiods[i].endDate,
            hours: this.account1.laborperiods[i].hours,
            account: this.account.laborperiods[i].account
          })
          this.laborPeriodArray.push(formGroup)
        }
        console.log(JSON.stringify(account.laborperiods[0].beginDate))
        this.ngOnChanges();
      });
  }

it works but it shows only 3 rows. That's the total length of the example account array.

This is the account class:

export class Account {
  id: number;
  username: string;
  name: string;
  enabled: boolean
  password: string;
  person: Person;
  admin: boolean;
  laborperiods: LaborPeriod[]
  remainingLeaveHours:number;
}

and this is the LaborPeriod class:

export class LaborPeriod{
    id: number
    beginDate: Date
    endDate: Date
    hours: number
    account: Account
}

Is there anything wrong with its field declarations?

Body:
Try replacing

laborperiod.value.get('beginDate')

By

laborperiod.value['beginDate']

I also recommande that you FormGroup variable to be a Class attribute and not a OnInit() one.

I also recommande using ReactiveForms with it's API FormControls.

Let me know what happened


问:
How to add right sliding pane without extending width of page?
I'm not quite sure how to title this better, so edits are welcome.

Basically I wanted to animate a right side sliding-in panel in a page over a fixed div panel.

My jQuery ajax does what its supposed to do to animate it. However, I just noticed that after adding the sliding-panel there was a horizontal scroll bar. Indeed it was my sliding-panel.

How can I "hide" it without extending or allowing the user to scroll horizontally and find the empty panel?

My HTML looks like this:

```<code><div class="left-pane">
    <div id="left-conent"></div>
</div>
<div class="sliding-panel" style="position: absolute;z-index: 1000;width: 400px;height: 90%;background-color: whitesmoke;right: -400px;">
    <div id="pane-content-edit" class="pane-content">
    </div>
</div>
<div id="right-pane" class="right-pane">
    <div id="pane-content" class="pane-content">
       ...
    </div>
</div>
</code>```

CSS:

```<code>.right-pane{
    width:400px;
    height:90%;
    background-color: whitesmoke;
    z-index: 999;
    right: 0;
    position: absolute;
</code>```

答:
Apply to body if no overflow is needed. Read about overflow

.right-pane {
  width: 400px;
  height: 90%;
  background-color: whitesmoke;
  z-index: 999;
  right: 0;
  position: absolute;
}

body {
  overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="left-pane">
  <div id="left-conent"></div>
</div>
<div class="sliding-panel" style="position: absolute;z-index: 1000;width: 400px;height: 90%;background-color: whitesmoke;right: -400px;">
  <div id="pane-content-edit" class="pane-content">
  </div>
</div>
<div id="right-pane" class="right-pane">
  <div id="pane-content" class="pane-content">
    ...
  </div>
</div></code>```

Body:
I'm not quite sure how to title this better, so edits are welcome.

Basically I wanted to animate a right side sliding-in panel in a page over a fixed div panel.

My jQuery ajax does what its supposed to do to animate it. However, I just noticed that after adding the sliding-panel there was a horizontal scroll bar. Indeed it was my sliding-panel.

How can I "hide" it without extending or allowing the user to scroll horizontally and find the empty panel?

My HTML looks like this:

       ...

CSS:

.right-pane{
    width:400px;
    height:90%;
    background-color: whitesmoke;
    z-index: 999;
    right: 0;
    position: absolute;

Body:
Apply to body if no overflow is needed. Read about overflow

.right-pane {
  width: 400px;
  height: 90%;
  background-color: whitesmoke;
  z-index: 999;
  right: 0;
  position: absolute;
}

body {
  overflow: hidden;
}

<div class="left-pane">
  <div id="left-conent"></div>
</div>
<div class="sliding-panel" style="position: absolute;z-index: 1000;width: 400px;height: 90%;background-color: whitesmoke;right: -400px;">
  <div id="pane-content-edit" class="pane-content">
  </div>
</div>
<div id="right-pane" class="right-pane">
  <div id="pane-content" class="pane-content">
    ...
  </div>
</div>


问:
How to pass password to scp?
I know it is not recommended, but is it at all possible to pass the user's password to scp?

I'd like to copy a file via scp as part of a batch job and the receiving server does, of course, need a password and, no, I cannot easily change that to key-based authentication.

答:
curl can be used as a alternative to scp to copy a file and it supports a password on the commandline. </p>

```<code>curl --insecure --user username:password -T /path/to/sourcefile sftp://desthost/path/
</code>```

OwnerDisplayName: Argelbargel

Title: How to pass password to scp?

Body:
curl can be used as a alternative to scp to copy a file and it supports a password on the commandline.

curl --insecure --user username:password -T /path/to/sourcefile sftp://desthost/path/


问:
Jmeter JSon Extract multiple values
I am trying to extract multiple values from a JSON document through the JMETER JSON Extractor with the following expression: $..VoidTransactionReferenceNumber;$..CILAmount

However, I am unable to get desired response, which is the VoidTransactionReferenceNumber and CLIAmount.

The JSON document is:

```<code>{
    "VoidTransactionReferenceNumber": "23456",
    "TransactionDTM": "2017-11-16T10:09:16.343Z",
    "CardBalance": 2350,
    "CardSequenceNumber": 0,
    "CILAmount": 0,
    "AutoloadAmount": 0,
    "CardBlockState": false,
    "VoidedAmount": 570,
    "SalesReferenceNumber": "2051609371",
    "VoidSalesReferenceNumber": "2051609371",
    "CardNumber": "3085220112345678"
}
</code>```

答:
You need to provide the same amount of Default Values as for JSON Path Expresions and Variable Names.

Add JSON Extractor as a child of the request which returns the above JSON

Configure it as follows:

Variable names: VoidTransactionReferenceNumber;CILAmount

JSON Path Expressions: $.VoidTransactionReferenceNumber;$.CILAmount

Default values: NOT_FOUND; NOT_FOUND

As a result you will have the following JMeter Variables defined

You will be able to refer them as ${VoidTransactionReferenceNumber} and ${CILAmount} where required.

More information: API Testing With JMeter and the JSON Extractor

Title: Jmeter JSon Extract multiple values

Body:
I am trying to extract multiple values from a JSON document through the JMETER JSON Extractor with the following expression: $..VoidTransactionReferenceNumber;$..CILAmount

However, I am unable to get desired response, which is the VoidTransactionReferenceNumber and CLIAmount.

The JSON document is:

{
    "VoidTransactionReferenceNumber": "23456",
    "TransactionDTM": "2017-11-16T10:09:16.343Z",
    "CardBalance": 2350,
    "CardSequenceNumber": 0,
    "CILAmount": 0,
    "AutoloadAmount": 0,
    "CardBlockState": false,
    "VoidedAmount": 570,
    "SalesReferenceNumber": "2051609371",
    "VoidSalesReferenceNumber": "2051609371",
    "CardNumber": "3085220112345678"
}


问:
Bootstrap v4 beta 2 - New display classes on rows
I'm migrating my frontend from V4 Alpha 6 to the latest (at the time of writing this) Beta 2 release.

However in one portion of my UI I have some 'row' elements that are hidden via 'hidden-*-down' previously.

With the new display classes, is intentional to use something like:

```<code>...
<div class="row d-none d-md-flex">
...
</code>```

Since rows use 'flex' display normally?
It just feels incorrect doing it this way for some reason.

Cheers

答:
That's the only correct way to do this now.

Shouldn't mess anything up, it just declares flex two times when the elements are visible.

Body:
I'm migrating my frontend from V4 Alpha 6 to the latest (at the time of writing this) Beta 2 release.

However in one portion of my UI I have some 'row' elements that are hidden via 'hidden-*-down' previously.

With the new display classes, is intentional to use something like:

...

...

Since rows use 'flex' display normally?
It just feels incorrect doing it this way for some reason.

Cheers


答:
As a possible solution - use overflow-x: hidden on the body tag. But in case the user doesn't have a screen big enough to show the whole, horizontal scrollbar will not appear. Hence the usability of your website will be significantly reduced.

I can suggest you to have a look at this css library in order to achieve the effect of sliding panel - https://daneden.github.io/animate.css/. Then you just need to care about hiding your panel with display: none and when you need to show it - add bounceInRight class to it.

Title: How to add right sliding pane without extending width of page?


问:
Bootstrap input and span inside td on the same line
I have a problem displaying input and span on the same line. They are inside first cell in the table.

What I've already tried is to use form-inline class, but both elements are still displayed in separate lines.

What am I doing wrong?

Code example from code pen.

Source:

```<code><table id="tblJEEVUG" class="table table-hover table-bordered table-striped table-condensed">
    <thead>
      <tr>
        <th>Datum</th>
        <th>Št. oseb</th>
        <th>Opomba</th>
        <th>Skupina</th>
        <th></th>
      </tr>
    </thead>
    <tbody>

            <tr data-ievug_key="170000536">

              <td id="devug_dst" style="width:200px;"><input class="form-control datetimepicker form-inline bounddtp" value="" style="width:70%;">
                <span id="spanOK" class="glyphicon glyphicon-ok form-inline" style="color: green; font-weight: bold; font-size: 20px; width: 5%;"></span></td>
              <td id="ievug_nop" style="width:50px;"><input class="form-control cbeh-number"></td>
              <td id="cevug_nto"><input class="form-control" value="zdaj pa en komnetar tule notri zapišem jaz"></td>
              <td id="igrop_key">

                <select class="form-control" data-editable="1">
                  <option></option>
                      <option value="100000030">Oddelek za transport</option>
                      <option value="100000029">Catering strežba</option>
                      <option value="100000504" selected="">Catering vodje prireditve</option>
                      <option value="100000748">HKJ-odgovorni kuharji </option>
                      <option value="100000028">HKJ-kuharji </option>

                </select>

              </td>
              <td style="vertical-align:middle;text-align:center;">
                <span class="glyphicon glyphicon-remove" title="Izbriši" style="color:red;cursor:pointer;display:block;" onclick="PopUpJEEVUS.RemoveRowJEEVUG(this);"></span>
              </td>

            </tr>
            <tr data-ievug_key="170000537">

              <td id="devug_dst" style="width:200px;"><input class="form-control datetimepicker form-inline bounddtp" value="15.11.2017 10:30" style="width:70%;">
                <span id="spanOK" class="glyphicon glyphicon-ok form-inline" style="color: green; font-weight: bold; font-size: 20px; width: 25%;"></span></td>
              <td id="ievug_nop" style="width:50px;"><input class="form-control cbeh-number" value="44"></td>
              <td id="cevug_nto"><input class="form-control" value="transtport pa bom dal en manjši komentar za tale transport sedaj"></td>
              <td id="igrop_key">

                <select class="form-control" data-editable="1">
                  <option></option>
                      <option value="100000030" selected="">Oddelek za transport</option>
                      <option value="100000029">Catering strežba</option>
                      <option value="100000504">Catering vodje prireditve</option>
                      <option value="100000748">HKJ-odgovorni kuharji </option>
                      <option value="100000028">HKJ-kuharji </option>

                </select>

              </td>
              <td style="vertical-align:middle;text-align:center;">
                <span class="glyphicon glyphicon-remove" title="Izbriši" style="color:red;cursor:pointer;display:block;" onclick="PopUpJEEVUS.RemoveRowJEEVUG(this);"></span>
              </td>

            </tr>
            <tr data-ievug_key="170000535">

              <td id="devug_dst" style="width:200px;"><input class="form-control datetimepicker form-inline bounddtp" value="16.11.2017 10:30" style="width:70%;">
                <span id="spanOK" class="glyphicon glyphicon-ok form-inline" style="color: green; font-weight: bold; font-size: 20px; width: 25%;"></span></td>
              <td id="ievug_nop" style="width:50px;"><input class="form-control cbeh-number" value="44"></td>
              <td id="cevug_nto"><input class="form-control" value="fffffffffffffffffffff"></td>
              <td id="igrop_key">

                <select class="form-control" data-editable="1">
                  <option></option>
                      <option value="100000030">Oddelek za transport</option>
                      <option value="100000029" selected="">Catering strežba</option>
                      <option value="100000504">Catering vodje prireditve</option>
                      <option value="100000748">HKJ-odgovorni kuharji </option>
                      <option value="100000028">HKJ-kuharji </option>

                </select>

              </td>
              <td style="vertical-align:middle;text-align:center;">
                <span class="glyphicon glyphicon-remove" title="Izbriši" style="color:red;cursor:pointer;display:block;" onclick="PopUpJEEVUS.RemoveRowJEEVUG(this);"></span>
              </td>

            </tr>

    </tbody>
  </table>
</code>```

答:
Just add float:left to form control class and margin-right to make it look good.
https://codepen.io/lionelchris/pen/dZVqoO

Body:
I have a problem displaying input and span on the same line. They are inside first cell in the table.

What I've already tried is to use form-inline class, but both elements are still displayed in separate lines.

What am I doing wrong?

Code example from code pen.

Source:

        Datum
        Št. oseb
        Opomba
        Skupina

              <input class="form-control datetimepicker form-inline bounddtp" value="" style="width:70%;">

              <input class="form-control cbeh-number">
              <input class="form-control" value="zdaj pa en komnetar tule notri zapišem jaz">

                <select class="form-control" data-editable="1">
                  <option></option>
                      <option value="100000030">Oddelek za transport</option>
                      <option value="100000029">Catering strežba</option>
                      <option value="100000504" selected="">Catering vodje prireditve</option>
                      <option value="100000748">HKJ-odgovorni kuharji </option>
                      <option value="100000028">HKJ-kuharji </option>

                </select>

              <input class="form-control datetimepicker form-inline bounddtp" value="15.11.2017 10:30" style="width:70%;">

              <input class="form-control cbeh-number" value="44">
              <input class="form-control" value="transtport pa bom dal en manjši komentar za tale transport sedaj">

                <select class="form-control" data-editable="1">
                  <option></option>
                      <option value="100000030" selected="">Oddelek za transport</option>
                      <option value="100000029">Catering strežba</option>
                      <option value="100000504">Catering vodje prireditve</option>
                      <option value="100000748">HKJ-odgovorni kuharji </option>
                      <option value="100000028">HKJ-kuharji </option>

                </select>

              <input class="form-control datetimepicker form-inline bounddtp" value="16.11.2017 10:30" style="width:70%;">

              <input class="form-control cbeh-number" value="44">
              <input class="form-control" value="fffffffffffffffffffff">

                <select class="form-control" data-editable="1">
                  <option></option>
                      <option value="100000030">Oddelek za transport</option>
                      <option value="100000029" selected="">Catering strežba</option>
                      <option value="100000504">Catering vodje prireditve</option>
                      <option value="100000748">HKJ-odgovorni kuharji </option>
                      <option value="100000028">HKJ-kuharji </option>

                </select>


问:
Send email with PhpMailer without waiting for return
I'm using PhpMailer to send e-mails. It's working fine.

But in some cases I don't want to wait for the send function to return, specially because it can take a while sometimes. I just want to send and finish the funcition right away.

Is it possible to achieve this?

This is a sample code I'm using (nothing different from the basics).

```<code>try {
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->SMTPDebug = 0;
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = 'tls';
    // ...other options...
    $mail->send();

    return true;
} catch (Exception $e) {
    return $e;
}
</code>```

答: You don't need to use ajax or configure your own queueing system to do this. Just use a local mail server - which implicitly has a built-in queueing system that you don't need to configure - and you can submit messages to it in a fraction of a second. There is some performance advice on the PHPMailer wiki.</p>

Body:
I'm using PhpMailer to send e-mails. It's working fine.

But in some cases I don't want to wait for the send function to return, specially because it can take a while sometimes. I just want to send and finish the funcition right away.

Is it possible to achieve this?

This is a sample code I'm using (nothing different from the basics).

try {
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->SMTPDebug = 0;
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = 'tls';
    // ...other options...
    $mail->send();

    return true;
} catch (Exception $e) {
    return $e;
}


问:
Error while compiling xcode. ibtools could not find class named UIImage
I got this error message in Xcode while compiling a project which was passed down to me:

```<code>CompileStoryboard proj1/Base.lproj/Main.storyboard
    cd /Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    export XCODE_DEVELOPER_USR_PATH=/Applications/Xcode.app/Contents/Developer/usr/bin/..
    /Applications/Xcode.app/Contents/Developer/usr/bin/ibtool --errors --warnings --notices --module proj1 --output-partial-info-plist /Users/user1/Library/Developer/Xcode/DerivedData/proj1-aevyxfxutfenlmbqvkeyzpywwekg/Build/Intermediates.noindex/proj1.build/Debug-iphonesimulator/proj1.build/Main-SBPartialInfo.plist --auto-activate-custom-fonts --target-device iphone --minimum-deployment-target 8 --output-format human-readable-text --compilation-directory /Users/user1/Library/Developer/Xcode/DerivedData/proj1-aevyxfxutfenlmbqvkeyzpywwekg/Build/Intermediates.noindex/proj1.build/Debug-iphonesimulator/proj1.build/Base.lproj /Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard
2017-11-16 17:12:26.655 ibtoold[20474:699803] *** Assertion failure in -[IBBinaryUnarchiver classForClassName:], /Library/Caches/com.apple.xbs/Sources/IDEInterfaceBuilder/IDEInterfaceBuilder-13529/Foundation/Utilities/IBBinaryUnarchiver.m:316
/* com.apple.ibtool.document.warnings */
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:TiJ-pH-k9k: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:iOT-6X-DYN: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:U3p-FK-Uaj: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:HrH-hF-d04: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:g6v-21-vpr: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:FyA-39-0eM: warning: Prototype collection view cells must have reuse identifiers
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:hHE-SH-oro: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:mf7-kd-Iuk: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:3lL-wL-gSf: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:sdL-YA-l1j: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:QgI-8L-Hco: warning: Automatic Preferred Max Layout Width before iOS 8.0
/* com.apple.ibtool.errors */
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard: error: Exception while running ibtool: Could not find class named UIImage
</code>```

I have tried cleaning and deleting the derived data folder and rebuilding but still the same error. I am running on Xcode 9.1.

Please help. Thanks.

答:
import uikit into header file of your view controller.

like in viewcontroller.h

add below line
#import <UIKit/UIKit.h>

i think this will resolve your issue.

Body:
I got this error message in Xcode while compiling a project which was passed down to me:

CompileStoryboard proj1/Base.lproj/Main.storyboard
    cd /Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    export XCODE_DEVELOPER_USR_PATH=/Applications/Xcode.app/Contents/Developer/usr/bin/..
    /Applications/Xcode.app/Contents/Developer/usr/bin/ibtool --errors --warnings --notices --module proj1 --output-partial-info-plist /Users/user1/Library/Developer/Xcode/DerivedData/proj1-aevyxfxutfenlmbqvkeyzpywwekg/Build/Intermediates.noindex/proj1.build/Debug-iphonesimulator/proj1.build/Main-SBPartialInfo.plist --auto-activate-custom-fonts --target-device iphone --minimum-deployment-target 8 --output-format human-readable-text --compilation-directory /Users/user1/Library/Developer/Xcode/DerivedData/proj1-aevyxfxutfenlmbqvkeyzpywwekg/Build/Intermediates.noindex/proj1.build/Debug-iphonesimulator/proj1.build/Base.lproj /Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard
2017-11-16 17:12:26.655 ibtoold[20474:699803] *** Assertion failure in -[IBBinaryUnarchiver classForClassName:], /Library/Caches/com.apple.xbs/Sources/IDEInterfaceBuilder/IDEInterfaceBuilder-13529/Foundation/Utilities/IBBinaryUnarchiver.m:316
/* com.apple.ibtool.document.warnings */
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:TiJ-pH-k9k: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:iOT-6X-DYN: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:U3p-FK-Uaj: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:HrH-hF-d04: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:g6v-21-vpr: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:FyA-39-0eM: warning: Prototype collection view cells must have reuse identifiers
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:hHE-SH-oro: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:mf7-kd-Iuk: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:3lL-wL-gSf: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:sdL-YA-l1j: warning: Automatic Preferred Max Layout Width before iOS 8.0
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard:QgI-8L-Hco: warning: Automatic Preferred Max Layout Width before iOS 8.0
/* com.apple.ibtool.errors */
/Users/user1/Documents/Projects/MyProject/iOS/MyProject_iOS/proj1/Base.lproj/Main.storyboard: error: Exception while running ibtool: Could not find class named UIImage

I have tried cleaning and deleting the derived data folder and rebuilding but still the same error. I am running on Xcode 9.1.

Please help. Thanks.


问:
Persistence postprocessing in three.js with 2 renderTargets
I am trying to implement this effect. As it is explained in the video, I have to make 2 extra renderTargets, blend the current image with renderTarget #1 into renderTarget #2, but I am having difficulties with implementing it in three.js. You can check my code here

let w = window.innerWidth
let h = window.innerHeight

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(60, w / h, 0.1, 1000)
const renderer = new THREE.WebGLRenderer()
const clock = new THREE.Clock()

let frontBuffer = createRenderTarget()
let backBuffer  = frontBuffer.clone()
let readBuffer  = frontBuffer
let writeBuffer = backBuffer

const renderScene = new THREE.Scene()
const renderCamera = new THREE.OrthographicCamera(-w / 2, w / 2, -h / 2, h / 2, -1000, 1000)
const renderMaterial = new THREE.ShaderMaterial({
  uniforms: {
    tDiffuse: { value: writeBuffer.texture }
  },
  vertexShader: `
    varying vec2 vUv;

    void main () {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

      vUv = uv;
    }
  `,
  fragmentShader: `
    uniform sampler2D tDiffuse;

    varying vec2 vUv;

    void main () {
      gl_FragColor = texture2D(tDiffuse, vUv);
    }
  `
})
const renderMesh = new THREE.Mesh(
  new THREE.PlaneBufferGeometry(w, h),
  renderMaterial
)
renderMesh.rotation.x += Math.PI
renderScene.add(renderMesh)

let timeElapsed = 0
let shape

setMainScene()
renderFrame()

function createRenderTarget () {
  let type = THREE.FloatType
  if( renderer.extensions.get( 'OES_texture_float_linear' ) === null ) type = THREE.HalfFloatType

  let renderTarget = new THREE.WebGLRenderTarget( 1, 1, {
    type,
    wrapS: THREE.ClampToEdgeWrapping,
    wrapT: THREE.ClampToEdgeWrapping,
    format: THREE.RGBAFormat,
    minFilter: THREE.NearestFilter,
    magFilter: THREE.NearestFilter,
    stencilBuffer: false,
    depthBuffer: true
  })

  renderTarget.texture.generateMipmaps = false
  renderTarget.setSize(w, h)

  return renderTarget
}

function swapBuffers () {
  if (readBuffer === frontBuffer) {
    readBuffer  = backBuffer
    writeBuffer = frontBuffer
  } else {
    readBuffer  = frontBuffer
    writeBuffer = backBuffer
  }
}

function setMainScene () {
  renderer.setSize(w, h)
  renderer.setClearColor(0x111111)
  renderer.setPixelRatio(window.devicePixelRatio || 1)
  document.body.appendChild(renderer.domElement)

  camera.position.set(0, 20, 100)
  camera.lookAt(new THREE.Vector3())

  shape = new THREE.Mesh(
    new THREE.SphereBufferGeometry(10, 20, 20),
    new THREE.MeshBasicMaterial({ color: 0xFF0000 })
  )
  scene.add(shape)
}

function renderFrame () {
  requestAnimationFrame(renderFrame)

  renderer.render(scene, camera, writeBuffer)
  renderer.render(renderScene, renderCamera)
  swapBuffers()

  timeElapsed += clock.getDelta()

  shape.position.x = Math.sin(timeElapsed) * 20.0
  shape.position.y = Math.cos(timeElapsed * Math.PI) * 20.0
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0; padding: 0; }</code>```

```
</div>
</div>
</p>

<p>First, I create my two extra framebuffers:</p>

```let frontBuffer = createRenderTarget()
let backBuffer  = frontBuffer.clone()
let readBuffer  = frontBuffer
let writeBuffer = backBuffer

function createRenderTarget () {
  let type = THREE.FloatType
  if( renderer.extensions.get( 'OES_texture_float_linear' ) === null ) type = THREE.HalfFloatType

  let renderTarget = new THREE.WebGLRenderTarget( 1, 1, {
    type,
    wrapS: THREE.ClampToEdgeWrapping,
    wrapT: THREE.ClampToEdgeWrapping,
    format: THREE.RGBAFormat,
    minFilter: THREE.NearestFilter,
    magFilter: THREE.NearestFilter,
    stencilBuffer: false,
    depthBuffer: true
  })

  renderTarget.texture.generateMipmaps = false
  renderTarget.setSize(w, h)

  return renderTarget
}
```

<p>Then I create an extra scene, a plane (to which I will render my main scene) covering the screen and a orthographic camera. I pass the result image of the main scene render as a uniform to my post-processing plane:</p>

```const renderScene = new THREE.Scene()
const renderCamera = new THREE.OrthographicCamera(-w / 2, w / 2, -h / 2, h / 2, -1000, 1000)
const renderMaterial = new THREE.ShaderMaterial({
  uniforms: {
    tDiffuse: { value: writeBuffer.texture }
  },
  vertexShader: `
    varying vec2 vUv;

    void main () {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

      vUv = uv;
    }
  `,
  fragmentShader: `
    uniform sampler2D tDiffuse;

    varying vec2 vUv;

    void main () {
      gl_FragColor = texture2D(tDiffuse, vUv);
    }
  `
})
```

<p>Finally, in my animation loop, I first render the main scene to the current fbo and then render my post-processing plane and I swap my buffers:</p>

```function swapBuffers () {
  if (readBuffer === frontBuffer) {
    readBuffer  = backBuffer
    writeBuffer = frontBuffer
  } else {
    readBuffer  = frontBuffer
    writeBuffer = backBuffer
  }
}

function renderFrame () {
  requestAnimationFrame(renderFrame)

  renderer.render(scene, camera, writeBuffer)
  renderer.render(renderScene, renderCamera)
  swapBuffers()

  timeElapsed += clock.getDelta()

  shape.position.x = Math.sin(timeElapsed) * 20.0
  shape.position.y = Math.cos(timeElapsed * Math.PI) * 20.0
}
```

<p>This is all fine and good and I can see my main scene render shown on the post-processing plane, but I can't understand how to blend it with the previous framebuffer. I guess I am very wrong in my current implementation, but information is scarce and I simply can't wrap my head around how to achieve this blending.</p>

<p>I tried passing both of my buffers as textures and then blending between them in GLSL, like this:</p>

```// js
uniforms: {
    tDiffuse1: { value: writeBuffer.texture },
    tDiffuse2: { value: readBuffer.texture }
  }

// glsl
gl_FragColor = mix(texture2D(tDiffuse1, vUv), texture2D(tDiffuse2, vUv), 0.5);
```

But visually I don't see any blending going on.

答:
You need 3 render targets. Let's call them sceneTarget, previousTarget, resultTarget

Step 1: Render your scene to the sceneTarget.

You now have your scene in sceneTarget.texture

Step 2: Blend sceneTarget.texture with previousTarget.texture into resultTarget

This one you need 2 textures as input like you mentioned at the bottom of your question. You need to update the material uniforms to use the correct textures every frame

```<code>renderMaterial.uniforms.tDiffuse1.value = previousTarget.texture;
renderMaterial.uniforms.tDiffuse2.value = sceneTarget.texture;
</code>```

Now you have a blended result in resultTarget.texture

Step 3: render resultTarget.texture to the canvas.

Now you can actually see the result.

Step 4: swap resultTarget and previousTarget

let w = window.innerWidth
let h = window.innerHeight

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(60, w / h, 0.1, 1000)
const renderer = new THREE.WebGLRenderer()
const clock = new THREE.Clock()

let sceneTarget = createRenderTarget()
let previousTarget  = sceneTarget.clone();
let resultTarget  = sceneTarget.clone();

const blendScene = new THREE.Scene();
const blendCamera = new THREE.OrthographicCamera(-w/2, w/2, -h/2, h/2, -1000, 1000);
const blendMaterial = new THREE.ShaderMaterial({
  uniforms: {
    tDiffuse1: { value: previousTarget.texture },
    tDiffuse2: { value: sceneTarget.texture },
  },
  vertexShader: `
    varying vec2 vUv;

    void main () {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

      vUv = uv;
    }
  `,
  fragmentShader: `
    uniform sampler2D tDiffuse1;
    uniform sampler2D tDiffuse2;

    varying vec2 vUv;

    void main () {
      gl_FragColor = mix(texture2D(tDiffuse1, vUv), texture2D(tDiffuse2, vUv), 0.25);
    }
  `,
});
const blendMesh = new THREE.Mesh(
  new THREE.PlaneBufferGeometry(w, h),
  blendMaterial
);
blendMesh.rotation.x = Math.PI;
blendScene.add(blendMesh);

const resultScene = new THREE.Scene();
const resultCamera = new THREE.OrthographicCamera(-w/2, w/2, -h/2, h/2, -1000, 1000);
const resultMaterial = new THREE.MeshBasicMaterial({
  map: resultTarget.texture,
});
const resultMesh = new THREE.Mesh(
  new THREE.PlaneBufferGeometry(w, h),
  resultMaterial
);
resultMesh.rotation.x = Math.PI;
resultScene.add(resultMesh);

let shape

setMainScene()
renderFrame(0)

function createRenderTarget () {
  let type = THREE.FloatType
  if( renderer.extensions.get( 'OES_texture_float_linear' ) === null ) type = THREE.HalfFloatType

  let renderTarget = new THREE.WebGLRenderTarget( 1, 1, {
    type,
    wrapS: THREE.ClampToEdgeWrapping,
    wrapT: THREE.ClampToEdgeWrapping,
    format: THREE.RGBAFormat,
    minFilter: THREE.NearestFilter,
    magFilter: THREE.NearestFilter,
    stencilBuffer: false,
    depthBuffer: true
  })

  renderTarget.texture.generateMipmaps = false
  renderTarget.setSize(w, h)

  return renderTarget
}

function swapBuffers () {
  const temp = previousTarget;
  previousTarget = resultTarget;
  resultTarget = temp;
}

function setMainScene () {
  renderer.setSize(w, h)
  renderer.setClearColor(0x111111)
  renderer.setPixelRatio(window.devicePixelRatio || 1)
  document.body.appendChild(renderer.domElement)

  camera.position.set(0, 20, 100);
  camera.lookAt(new THREE.Vector3());

  shape = new THREE.Mesh(
    new THREE.SphereBufferGeometry(10, 20, 20),
    new THREE.MeshBasicMaterial({ color: 0xFF0000 })
  );
  scene.add(shape);
}

function renderFrame (timeElapsed) {
  timeElapsed *= 0.001;

  renderer.render(scene, camera, sceneTarget);

  blendMaterial.uniforms.tDiffuse1.value = previousTarget.texture;
  blendMaterial.uniforms.tDiffuse2.value = sceneTarget.texture;
  renderer.render(blendScene, blendCamera, resultTarget);

  resultMaterial.map = resultTarget.texture;
  renderer.render(resultScene, resultCamera);
  swapBuffers();

  shape.position.x = Math.sin(timeElapsed) * 20.0;
  shape.position.y = Math.cos(timeElapsed * Math.PI) * 20.0;

  requestAnimationFrame(renderFrame);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0; padding: 0; }</code>```

```
</div>
</div>
</p>

<p>Let me also add that's not really a good persistence affect. I'm not sure what the best one is. The problem with the one above is the higher you set the persistence the less you see of the current frame.</p>

<p>A better one, though it requires choosing a fade out color, would be something like this. Only 2 targets needed, <code>previousTarget</code> and <code>currentTarget</code></p>

<ol>
<li><p>Render <code>previousTarget.texture</code> to <code>currentTarget</code> with a shader
that fades to a certain color. <code>mix(tex, color, 0.05)</code> or something like that.</p></li>
<li><p>Render the scene to <code>currentTarget</code> as well</p></li>
<li><p>Render <code>currentTarget.texture</code> to canvas</p></li>
<li><p>Swap <code>currentTarget</code> and <code>previousTarget</code></p></li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let w = window.innerWidth
let h = window.innerHeight

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(60, w / h, 0.1, 1000)
const renderer = new THREE.WebGLRenderer()
const clock = new THREE.Clock()

let currentTarget = createRenderTarget()
let previousTarget  = currentTarget.clone();

const fadeScene = new THREE.Scene();
const fadeCamera = new THREE.OrthographicCamera(-w/2, w/2, -h/2, h/2, -1000, 1000);
const fadeMaterial = new THREE.ShaderMaterial({
  uniforms: {
    tDiffuse: { value: previousTarget.texture },
  },
  vertexShader: `
    varying vec2 vUv;

    void main () {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

      vUv = uv;
    }
  `,
  fragmentShader: `
    uniform sampler2D tDiffuse;

    varying vec2 vUv;

    void main () {
      vec4 fadeColor = vec4(0,0,0,1);
      gl_FragColor = mix(texture2D(tDiffuse, vUv), fadeColor, 0.05);
    }
  `,
});
const fadeMesh = new THREE.Mesh(
  new THREE.PlaneBufferGeometry(w, h),
  fadeMaterial
);
fadeMesh.rotation.x = Math.PI;
fadeScene.add(fadeMesh);

const resultScene = new THREE.Scene();
const resultCamera = new THREE.OrthographicCamera(-w/2, w/2, -h/2, h/2, -1000, 1000);
const resultMaterial = new THREE.MeshBasicMaterial({
  map: currentTarget.texture,
});
const resultMesh = new THREE.Mesh(
  new THREE.PlaneBufferGeometry(w, h),
  resultMaterial
);
resultMesh.rotation.x = Math.PI;
resultScene.add(resultMesh);

let shape

setMainScene()
renderFrame(0)

function createRenderTarget () {
  let type = THREE.FloatType
  if( renderer.extensions.get( 'OES_texture_float_linear' ) === null ) type = THREE.HalfFloatType

  let renderTarget = new THREE.WebGLRenderTarget( 1, 1, {
    type,
    wrapS: THREE.ClampToEdgeWrapping,
    wrapT: THREE.ClampToEdgeWrapping,
    format: THREE.RGBAFormat,
    minFilter: THREE.NearestFilter,
    magFilter: THREE.NearestFilter,
    stencilBuffer: false,
    depthBuffer: true
  })

  renderTarget.texture.generateMipmaps = false
  renderTarget.setSize(w, h)

  return renderTarget
}

function swapBuffers () {
  const temp = previousTarget;
  previousTarget = currentTarget;
  currentTarget = temp;
}

function setMainScene () {
  renderer.setSize(w, h)
  renderer.setClearColor(0x111111)
  renderer.setPixelRatio(window.devicePixelRatio || 1)
  renderer.autoClearColor = false;
  document.body.appendChild(renderer.domElement)

  camera.position.set(0, 20, 100);
  camera.lookAt(new THREE.Vector3());

  shape = new THREE.Mesh(
    new THREE.SphereBufferGeometry(10, 20, 20),
    new THREE.MeshBasicMaterial({ color: 0xFF0000 })
  );
  scene.add(shape);
}

function renderFrame (timeElapsed) {
  timeElapsed *= 0.001;

  fadeMaterial.uniforms.tDiffuse.value = previousTarget.texture;
  renderer.render(fadeScene, fadeCamera, currentTarget);

  renderer.render(scene, camera, currentTarget);

  resultMaterial.map = currentTarget.texture;
  renderer.render(resultScene, resultCamera);
  swapBuffers();

  shape.position.x = Math.sin(timeElapsed) * 20.0;
  shape.position.y = Math.cos(timeElapsed * Math.PI) * 20.0;

  requestAnimationFrame(renderFrame);

}</code>```

* { margin: 0; padding: 0; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script></code>```

Body:
I am trying to implement this effect. As it is explained in the video, I have to make 2 extra renderTargets, blend the current image with renderTarget #1 into renderTarget #2, but I am having difficulties with implementing it in three.js. You can check my code here

let w = window.innerWidth
let h = window.innerHeight

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(60, w / h, 0.1, 1000)
const renderer = new THREE.WebGLRenderer()
const clock = new THREE.Clock()

let frontBuffer = createRenderTarget()
let backBuffer  = frontBuffer.clone()
let readBuffer  = frontBuffer
let writeBuffer = backBuffer

const renderScene = new THREE.Scene()
const renderCamera = new THREE.OrthographicCamera(-w / 2, w / 2, -h / 2, h / 2, -1000, 1000)
const renderMaterial = new THREE.ShaderMaterial({
  uniforms: {
    tDiffuse: { value: writeBuffer.texture }
  },
  vertexShader: `
    varying vec2 vUv;

    void main () {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

      vUv = uv;
    }
  `,
  fragmentShader: `
    uniform sampler2D tDiffuse;

    varying vec2 vUv;

    void main () {
      gl_FragColor = texture2D(tDiffuse, vUv);
    }
  `
})
const renderMesh = new THREE.Mesh(
  new THREE.PlaneBufferGeometry(w, h),
  renderMaterial
)
renderMesh.rotation.x += Math.PI
renderScene.add(renderMesh)

let timeElapsed = 0
let shape

setMainScene()
renderFrame()

function createRenderTarget () {
  let type = THREE.FloatType
  if( renderer.extensions.get( 'OES_texture_float_linear' ) === null ) type = THREE.HalfFloatType

  let renderTarget = new THREE.WebGLRenderTarget( 1, 1, {
    type,
    wrapS: THREE.ClampToEdgeWrapping,
    wrapT: THREE.ClampToEdgeWrapping,
    format: THREE.RGBAFormat,
    minFilter: THREE.NearestFilter,
    magFilter: THREE.NearestFilter,
    stencilBuffer: false,
    depthBuffer: true
  })

  renderTarget.texture.generateMipmaps = false
  renderTarget.setSize(w, h)

  return renderTarget
}

function swapBuffers () {
  if (readBuffer === frontBuffer) {
    readBuffer  = backBuffer
    writeBuffer = frontBuffer
  } else {
    readBuffer  = frontBuffer
    writeBuffer = backBuffer
  }
}

function setMainScene () {
  renderer.setSize(w, h)
  renderer.setClearColor(0x111111)
  renderer.setPixelRatio(window.devicePixelRatio || 1)
  document.body.appendChild(renderer.domElement)

  camera.position.set(0, 20, 100)
  camera.lookAt(new THREE.Vector3())

  shape = new THREE.Mesh(
    new THREE.SphereBufferGeometry(10, 20, 20),
    new THREE.MeshBasicMaterial({ color: 0xFF0000 })
  )
  scene.add(shape)
}

function renderFrame () {
  requestAnimationFrame(renderFrame)

  renderer.render(scene, camera, writeBuffer)
  renderer.render(renderScene, renderCamera)
  swapBuffers()

  timeElapsed += clock.getDelta()

  shape.position.x = Math.sin(timeElapsed) * 20.0
  shape.position.y = Math.cos(timeElapsed * Math.PI) * 20.0
}

* { margin: 0; padding: 0; }

First, I create my two extra framebuffers:

let frontBuffer = createRenderTarget()
let backBuffer  = frontBuffer.clone()
let readBuffer  = frontBuffer
let writeBuffer = backBuffer

function createRenderTarget () {
  let type = THREE.FloatType
  if( renderer.extensions.get( 'OES_texture_float_linear' ) === null ) type = THREE.HalfFloatType

  let renderTarget = new THREE.WebGLRenderTarget( 1, 1, {
    type,
    wrapS: THREE.ClampToEdgeWrapping,
    wrapT: THREE.ClampToEdgeWrapping,
    format: THREE.RGBAFormat,
    minFilter: THREE.NearestFilter,
    magFilter: THREE.NearestFilter,
    stencilBuffer: false,
    depthBuffer: true
  })

  renderTarget.texture.generateMipmaps = false
  renderTarget.setSize(w, h)

  return renderTarget
}

Then I create an extra scene, a plane (to which I will render my main scene) covering the screen and a orthographic camera. I pass the result image of the main scene render as a uniform to my post-processing plane:

const renderScene = new THREE.Scene()
const renderCamera = new THREE.OrthographicCamera(-w / 2, w / 2, -h / 2, h / 2, -1000, 1000)
const renderMaterial = new THREE.ShaderMaterial({
  uniforms: {
    tDiffuse: { value: writeBuffer.texture }
  },
  vertexShader: `
    varying vec2 vUv;

    void main () {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

      vUv = uv;
    }
  `,
  fragmentShader: `
    uniform sampler2D tDiffuse;

    varying vec2 vUv;

    void main () {
      gl_FragColor = texture2D(tDiffuse, vUv);
    }
  `
})

Finally, in my animation loop, I first render the main scene to the current fbo and then render my post-processing plane and I swap my buffers:

function swapBuffers () {
  if (readBuffer === frontBuffer) {
    readBuffer  = backBuffer
    writeBuffer = frontBuffer
  } else {
    readBuffer  = frontBuffer
    writeBuffer = backBuffer
  }
}

function renderFrame () {
  requestAnimationFrame(renderFrame)

  renderer.render(scene, camera, writeBuffer)
  renderer.render(renderScene, renderCamera)
  swapBuffers()

  timeElapsed += clock.getDelta()

  shape.position.x = Math.sin(timeElapsed) * 20.0
  shape.position.y = Math.cos(timeElapsed * Math.PI) * 20.0
}

This is all fine and good and I can see my main scene render shown on the post-processing plane, but I can't understand how to blend it with the previous framebuffer. I guess I am very wrong in my current implementation, but information is scarce and I simply can't wrap my head around how to achieve this blending.

I tried passing both of my buffers as textures and then blending between them in GLSL, like this:

// js
uniforms: {
    tDiffuse1: { value: writeBuffer.texture },
    tDiffuse2: { value: readBuffer.texture }
  }

// glsl
gl_FragColor = mix(texture2D(tDiffuse1, vUv), texture2D(tDiffuse2, vUv), 0.5);

But visually I don't see any blending going on.

Body:
You need 3 render targets. Let's call them sceneTarget, previousTarget, resultTarget

Step 1: Render your scene to the sceneTarget.

You now have your scene in sceneTarget.texture

Step 2: Blend sceneTarget.texture with previousTarget.texture into resultTarget

This one you need 2 textures as input like you mentioned at the bottom of your question. You need to update the material uniforms to use the correct textures every frame

renderMaterial.uniforms.tDiffuse1.value = previousTarget.texture;
renderMaterial.uniforms.tDiffuse2.value = sceneTarget.texture;

Now you have a blended result in resultTarget.texture

Step 3: render resultTarget.texture to the canvas.

Now you can actually see the result.

Step 4: swap resultTarget and previousTarget

let w = window.innerWidth
let h = window.innerHeight

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(60, w / h, 0.1, 1000)
const renderer = new THREE.WebGLRenderer()
const clock = new THREE.Clock()

let sceneTarget = createRenderTarget()
let previousTarget  = sceneTarget.clone();
let resultTarget  = sceneTarget.clone();

const blendScene = new THREE.Scene();
const blendCamera = new THREE.OrthographicCamera(-w/2, w/2, -h/2, h/2, -1000, 1000);
const blendMaterial = new THREE.ShaderMaterial({
  uniforms: {
    tDiffuse1: { value: previousTarget.texture },
    tDiffuse2: { value: sceneTarget.texture },
  },
  vertexShader: `
    varying vec2 vUv;

    void main () {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

      vUv = uv;
    }
  `,
  fragmentShader: `
    uniform sampler2D tDiffuse1;
    uniform sampler2D tDiffuse2;

    varying vec2 vUv;

    void main () {
      gl_FragColor = mix(texture2D(tDiffuse1, vUv), texture2D(tDiffuse2, vUv), 0.25);
    }
  `,
});
const blendMesh = new THREE.Mesh(
  new THREE.PlaneBufferGeometry(w, h),
  blendMaterial
);
blendMesh.rotation.x = Math.PI;
blendScene.add(blendMesh);

const resultScene = new THREE.Scene();
const resultCamera = new THREE.OrthographicCamera(-w/2, w/2, -h/2, h/2, -1000, 1000);
const resultMaterial = new THREE.MeshBasicMaterial({
  map: resultTarget.texture,
});
const resultMesh = new THREE.Mesh(
  new THREE.PlaneBufferGeometry(w, h),
  resultMaterial
);
resultMesh.rotation.x = Math.PI;
resultScene.add(resultMesh);

let shape

setMainScene()
renderFrame(0)

function createRenderTarget () {
  let type = THREE.FloatType
  if( renderer.extensions.get( 'OES_texture_float_linear' ) === null ) type = THREE.HalfFloatType

  let renderTarget = new THREE.WebGLRenderTarget( 1, 1, {
    type,
    wrapS: THREE.ClampToEdgeWrapping,
    wrapT: THREE.ClampToEdgeWrapping,
    format: THREE.RGBAFormat,
    minFilter: THREE.NearestFilter,
    magFilter: THREE.NearestFilter,
    stencilBuffer: false,
    depthBuffer: true
  })

  renderTarget.texture.generateMipmaps = false
  renderTarget.setSize(w, h)

  return renderTarget
}

function swapBuffers () {
  const temp = previousTarget;
  previousTarget = resultTarget;
  resultTarget = temp;
}

function setMainScene () {
  renderer.setSize(w, h)
  renderer.setClearColor(0x111111)
  renderer.setPixelRatio(window.devicePixelRatio || 1)
  document.body.appendChild(renderer.domElement)

  camera.position.set(0, 20, 100);
  camera.lookAt(new THREE.Vector3());

  shape = new THREE.Mesh(
    new THREE.SphereBufferGeometry(10, 20, 20),
    new THREE.MeshBasicMaterial({ color: 0xFF0000 })
  );
  scene.add(shape);
}

function renderFrame (timeElapsed) {
  timeElapsed *= 0.001;

  renderer.render(scene, camera, sceneTarget);

  blendMaterial.uniforms.tDiffuse1.value = previousTarget.texture;
  blendMaterial.uniforms.tDiffuse2.value = sceneTarget.texture;
  renderer.render(blendScene, blendCamera, resultTarget);

  resultMaterial.map = resultTarget.texture;
  renderer.render(resultScene, resultCamera);
  swapBuffers();

  shape.position.x = Math.sin(timeElapsed) * 20.0;
  shape.position.y = Math.cos(timeElapsed * Math.PI) * 20.0;

  requestAnimationFrame(renderFrame);

}

* { margin: 0; padding: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script>

Let me also add that's not really a good persistence affect. I'm not sure what the best one is. The problem with the one above is the higher you set the persistence the less you see of the current frame.

A better one, though it requires choosing a fade out color, would be something like this. Only 2 targets needed, previousTarget and currentTarget

Render previousTarget.texture to currentTarget with a shader
that fades to a certain color. mix(tex, color, 0.05) or something like that.

Render the scene to currentTarget as well

Render currentTarget.texture to canvas

Swap currentTarget and previousTarget

let w = window.innerWidth
let h = window.innerHeight

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(60, w / h, 0.1, 1000)
const renderer = new THREE.WebGLRenderer()
const clock = new THREE.Clock()

let currentTarget = createRenderTarget()
let previousTarget  = currentTarget.clone();

const fadeScene = new THREE.Scene();
const fadeCamera = new THREE.OrthographicCamera(-w/2, w/2, -h/2, h/2, -1000, 1000);
const fadeMaterial = new THREE.ShaderMaterial({
  uniforms: {
    tDiffuse: { value: previousTarget.texture },
  },
  vertexShader: `
    varying vec2 vUv;

    void main () {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

      vUv = uv;
    }
  `,
  fragmentShader: `
    uniform sampler2D tDiffuse;

    varying vec2 vUv;

    void main () {
      vec4 fadeColor = vec4(0,0,0,1);
      gl_FragColor = mix(texture2D(tDiffuse, vUv), fadeColor, 0.05);
    }
  `,
});
const fadeMesh = new THREE.Mesh(
  new THREE.PlaneBufferGeometry(w, h),
  fadeMaterial
);
fadeMesh.rotation.x = Math.PI;
fadeScene.add(fadeMesh);

const resultScene = new THREE.Scene();
const resultCamera = new THREE.OrthographicCamera(-w/2, w/2, -h/2, h/2, -1000, 1000);
const resultMaterial = new THREE.MeshBasicMaterial({
  map: currentTarget.texture,
});
const resultMesh = new THREE.Mesh(
  new THREE.PlaneBufferGeometry(w, h),
  resultMaterial
);
resultMesh.rotation.x = Math.PI;
resultScene.add(resultMesh);

let shape

setMainScene()
renderFrame(0)

function createRenderTarget () {
  let type = THREE.FloatType
  if( renderer.extensions.get( 'OES_texture_float_linear' ) === null ) type = THREE.HalfFloatType

  let renderTarget = new THREE.WebGLRenderTarget( 1, 1, {
    type,
    wrapS: THREE.ClampToEdgeWrapping,
    wrapT: THREE.ClampToEdgeWrapping,
    format: THREE.RGBAFormat,
    minFilter: THREE.NearestFilter,
    magFilter: THREE.NearestFilter,
    stencilBuffer: false,
    depthBuffer: true
  })

  renderTarget.texture.generateMipmaps = false
  renderTarget.setSize(w, h)

  return renderTarget
}

function swapBuffers () {
  const temp = previousTarget;
  previousTarget = currentTarget;
  currentTarget = temp;
}

function setMainScene () {
  renderer.setSize(w, h)
  renderer.setClearColor(0x111111)
  renderer.setPixelRatio(window.devicePixelRatio || 1)
  renderer.autoClearColor = false;
  document.body.appendChild(renderer.domElement)

  camera.position.set(0, 20, 100);
  camera.lookAt(new THREE.Vector3());

  shape = new THREE.Mesh(
    new THREE.SphereBufferGeometry(10, 20, 20),
    new THREE.MeshBasicMaterial({ color: 0xFF0000 })
  );
  scene.add(shape);
}

function renderFrame (timeElapsed) {
  timeElapsed *= 0.001;

  fadeMaterial.uniforms.tDiffuse.value = previousTarget.texture;
  renderer.render(fadeScene, fadeCamera, currentTarget);

  renderer.render(scene, camera, currentTarget);

  resultMaterial.map = currentTarget.texture;
  renderer.render(resultScene, resultCamera);
  swapBuffers();

  shape.position.x = Math.sin(timeElapsed) * 20.0;
  shape.position.y = Math.cos(timeElapsed * Math.PI) * 20.0;

  requestAnimationFrame(renderFrame);

}

* { margin: 0; padding: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script>


问:
Updating a big table in oracle without drooping the base table
I am trying to update a table in sql query. My table contains half a million records and it is taking around 10 minutes of time. It is my dev environment.

When i will go for UAT or prod, the table there will contain a lot more data than the dev environment. updating the whole table and then putting a commit will consume a lot of memory. Can someone suggest me a good way of updating a table in batches.

I have gone through net and the most common solution i found is creating a new table by "create new_table as select (update ) from old_table." But in my case i can not use this as in my prod environment i can not drop  and create table.

Thanks
Ankit.

答: If "Create Table as Select" is not an option, then your best bet is to write a PL/SQL stored proc that takes advantage of BULK COLLECT and FORALL statements. This is a good starting point http://www.oracle.com/technetwork/issue-archive/2012/12-sep/o52plsql-1709862.html


答:
Put display: inline-block css in form-control and if you are using Bootstrap4, in that case, you can put .d-inline-block class in the input.

This will run your code correctly.

Title: Bootstrap input and span inside td on the same line