问:
Oracle Golden Gate Version 12.1.2 DBLOGIN throws error
I am not able to login in GGS_OWNER from within GGSCI. I am able to login from  sqlplus but when I try to login thorugh GGSCI it throws an error:

GG Version: 12.1.2
  Database version: 12c
  Type of replication: Integrated Capture
  Replication setup: Unidirectional DML replication

```<code>Source Context :
SourceModule            : [ggapp.util.pcs]
SourceID                : [/scratch/aime1/adestore/views/aime1_adc4150327/oggcore/OpenSys/src/gglib/ggapp/pcsutl.c]
SourceFunction          : [AbendHandler]
SourceLine              : [1005]
ThreadBacktrace         : [21] elements
                      : [/ggsadmin/app/ggate/12.1.2/libgglog.so(CMessageContext::AddThreadContext()+0x1e) [0x7f79191a286e]]
                      : [/ggsadmin/app/ggate/12.1.2/libgglog.so(CMessageFactory::CreateMessage(CSourceContext*, unsigned int, ...)+0x340) [0x7f791919d580]]
                      : [/ggsadmin/app/ggate/12.1.2/libgglog.so(_MSG_ERR_SIGNAL_RECEIVED(CSourceContext*, int, char const*, CMessageFactory::MessageDisposition)+0x3b) [0x7f791918078b]]
                      : [ggsci [0x50f653]]
                      : [/lib64/libpthread.so.0 [0x36b940eca0]]
                      : [/lib64/libpthread.so.0(pthread_mutex_lock+0) [0x36b9408dd0]]
                      : [ggsci(ggs::gglib::MultiThreading::Mutex::Lock()+0x9) [0x5449c9]]
                      : [ggsci(CContextItem::operator char const*() const+0x15) [0x4e2b3f]]
                      : [ggsci(DBOCI_init_connection_logon(ggs::gglib::ggapp::CLoginName const&, ggs::gglib::ggapp::CDBObjName<(DBObjType)12> const&, char const*, int, int, int, char*)+0x1e5) [0x553b85]]
                      : [ggsci [0x566ba4]]
                      : [ggsci(gl_db_login(char const*, char const*,   ggs::gglib::ggapp::CDBObjName<(DBObjType)11>&, ggs::gglib::ggapp::CDBObjName<(DBObjType)12>&, short, char (&) [2048])+0x5f) [0x566edf]]
                      : [ggsci [0x4a4d12]]
                      : [ggsci(GGSCIDB_get_command(char const*, char const*, char const*, short, short, char (&) [2048])+0x11b) [0x4a525b]]
                       : [ggsci(do_cmd(char*, unsigned long, char*, unsigned long)+0xb14) [0x4dd654]]
                      : [ggsci [0x4e145b]]
                      : [ggsci(ggs::gglib::MultiThreading::MainThread::ExecMain()+0x4f) [0x54241f]]
                      : [ggsci(ggs::gglib::MultiThreading::Thread::RunThread(ggs::gglib::MultiThreading::Thread::ThreadArgs*)+0x104) [0x542624]]
                      : [ggsci(ggs::gglib::MultiThreading::MainThread::Run(int, char**)+0x8b) [0x54273b]]
                      : [ggsci(main+0x3f) [0x4bc94f]]
                      : [/lib64/libc.so.6(__libc_start_main+0xf4) [0x36b841d9f4]]
                      : [ggsci [0x49c379]]

2015-09-24 08:35:18  ERROR   OGG-01117  Received signal: Segmentation violation (11).

2015-09-24 08:35:18  ERROR   OGG-01668  PROCESS ABENDING.
</code>```

Segmentation fault

答:
Just a suggestion that you should always login to GGSCI from OGG_HOME path only. Because, when you login to GGSCI, GGSCI tries to read the params from the current path (and not the absolute path). This may lead to a few params not getting loaded when you login to GGSCI from any location other than OGG_HOME.

i.e.

cd $OGG_HOME

./ggsci

BUT NOT AS :

cd $OGG_HOME/dirprm  (for example)

../ggsci

Body:
I am not able to login in GGS_OWNER from within GGSCI. I am able to login from  sqlplus but when I try to login thorugh GGSCI it throws an error:

GG Version: 12.1.2
  Database version: 12c
  Type of replication: Integrated Capture
  Replication setup: Unidirectional DML replication

Source Context :
SourceModule            : [ggapp.util.pcs]
SourceID                : [/scratch/aime1/adestore/views/aime1_adc4150327/oggcore/OpenSys/src/gglib/ggapp/pcsutl.c]
SourceFunction          : [AbendHandler]
SourceLine              : [1005]
ThreadBacktrace         : [21] elements
                      : [/ggsadmin/app/ggate/12.1.2/libgglog.so(CMessageContext::AddThreadContext()+0x1e) [0x7f79191a286e]]
                      : [/ggsadmin/app/ggate/12.1.2/libgglog.so(CMessageFactory::CreateMessage(CSourceContext*, unsigned int, ...)+0x340) [0x7f791919d580]]
                      : [/ggsadmin/app/ggate/12.1.2/libgglog.so(_MSG_ERR_SIGNAL_RECEIVED(CSourceContext*, int, char const*, CMessageFactory::MessageDisposition)+0x3b) [0x7f791918078b]]
                      : [ggsci [0x50f653]]
                      : [/lib64/libpthread.so.0 [0x36b940eca0]]
                      : [/lib64/libpthread.so.0(pthread_mutex_lock+0) [0x36b9408dd0]]
                      : [ggsci(ggs::gglib::MultiThreading::Mutex::Lock()+0x9) [0x5449c9]]
                      : [ggsci(CContextItem::operator char const*() const+0x15) [0x4e2b3f]]
                      : [ggsci(DBOCI_init_connection_logon(ggs::gglib::ggapp::CLoginName const&, ggs::gglib::ggapp::CDBObjName<(DBObjType)12> const&, char const*, int, int, int, char*)+0x1e5) [0x553b85]]
                      : [ggsci [0x566ba4]]
                      : [ggsci(gl_db_login(char const*, char const*,   ggs::gglib::ggapp::CDBObjName<(DBObjType)11>&, ggs::gglib::ggapp::CDBObjName<(DBObjType)12>&, short, char (&) [2048])+0x5f) [0x566edf]]
                      : [ggsci [0x4a4d12]]
                      : [ggsci(GGSCIDB_get_command(char const*, char const*, char const*, short, short, char (&) [2048])+0x11b) [0x4a525b]]
                       : [ggsci(do_cmd(char*, unsigned long, char*, unsigned long)+0xb14) [0x4dd654]]
                      : [ggsci [0x4e145b]]
                      : [ggsci(ggs::gglib::MultiThreading::MainThread::ExecMain()+0x4f) [0x54241f]]
                      : [ggsci(ggs::gglib::MultiThreading::Thread::RunThread(ggs::gglib::MultiThreading::Thread::ThreadArgs*)+0x104) [0x542624]]
                      : [ggsci(ggs::gglib::MultiThreading::MainThread::Run(int, char**)+0x8b) [0x54273b]]
                      : [ggsci(main+0x3f) [0x4bc94f]]
                      : [/lib64/libc.so.6(__libc_start_main+0xf4) [0x36b841d9f4]]
                      : [ggsci [0x49c379]]

2015-09-24 08:35:18  ERROR   OGG-01117  Received signal: Segmentation violation (11).

2015-09-24 08:35:18  ERROR   OGG-01668  PROCESS ABENDING.

Segmentation fault


来源: stackexchange

问:
request.getParameter() on submit buttons name returns always null
I have a contact form in my website and I am trying to make it send an email to me. Email Sender class works fine the problem is when I try to get parameter from the form it always returns null. I tested in another simple form, the code worked but it doesnt work on my own form. This is the form from jsp file.

  <form id="contact" class="contact-form row" role="form" method="post">

        Your message has been sent successfully.

        There was a problem validating the form please check!

        <input class="input-lg form-full" id="form-name" type="text" name="name" placeholder="Your Name" required />

        <input class="input-lg form-full" id="form-email" type="email" name="email" placeholder="Email" required />

        <input class="input-lg form-full" id="form-subject" type="text" name="subject" placeholder="Subject" />

        <textarea class="home-contact-txt-msg input-lg form-full" id="form-message" rows="7" name="message" placeholder="Your Message" required></textarea>

      <input class="btn-contact-submit btn btn-lg btn-black" type="submit" name="submit" value="Send Message">

  </form>

```

<p>This is the part I need to get parameter.</p>

```

  <input class="btn-contact-submit btn btn-lg btn-black" type="submit" name="submit" value="Send Message">

```

<p>And this is the email sending code.</p>

```<%
    String status = null;
    String parameter = null;

    //If request is submit, sending email.
    if (request.getParameter("submit") != null) {

        EmailSender email = new EmailSender();
        email.setMailServerProperties();

        //Email subject.
        String emailSubject = "Message from asdasd.com";
        //Email body.
        String emailBody = "";

        //If name is not empty, adding name to email body.
        if (request.getParameter("name") != null) {
            emailBody = "Sender Name: " + request.getParameter("name") + "
";
        }

        //If email is not empty, adding email to email body.
        if (request.getParameter("email") != null) {
            emailBody = emailBody + "Sender Email: " + request.getParameter("email") + "
";
        }

        //If subject is not empty, adding subject to email body.
        if (request.getParameter("subject") != null) {
            emailBody = emailBody + "Subject: " + request.getParameter("subject") + "
";
        }

        //If message is not empty, adding message to email body.
        if (request.getParameter("message") != null) {
            emailBody = emailBody + "Message: " + request.getParameter("message") + "
";
        }

        //Creating email object with emailSubject and emailBody.
        email.createEmailMessage(emailSubject, emailBody);

        /*
        try {
            //Sending email.
            email.sendEmail();
        } catch (MessagingException me) {
            out.print(me.getMessage());
        }
        */
        status = "Email sent.";
        parameter = request.getParameter("submit");
        out.print(status + parameter);
    } else {
        status = "Email not sent.";
        parameter = request.getParameter("submit");
        out.print(status + parameter);
    }
%>
```

How can I make this part (request.getParameter("submit") != null) true when the forms submit button is clicked?

Edit: I noticed something. I can't get parameter of any field in this page, not only submit button.

Edit2: After many tries the working code started not to work. Is the problem can be related to apache tomcat? Is there any way to test this consistently without server issues.

答: Are you adding the libraries in the JSP file? Like <%@ page import = "java.io.*,java.util.*" %>

ContentLicense: CC BY-SA 3.0

Body:
I have a contact form in my website and I am trying to make it send an email to me. Email Sender class works fine the problem is when I try to get parameter from the form it always returns null. I tested in another simple form, the code worked but it doesnt work on my own form. This is the form from jsp file.

  <form id="contact" class="contact-form row" role="form" method="post">

        Your message has been sent successfully.

        There was a problem validating the form please check!

        <input class="input-lg form-full" id="form-name" type="text" name="name" placeholder="Your Name" required />

        <input class="input-lg form-full" id="form-email" type="email" name="email" placeholder="Email" required />

        <input class="input-lg form-full" id="form-subject" type="text" name="subject" placeholder="Subject" />

        <textarea class="home-contact-txt-msg input-lg form-full" id="form-message" rows="7" name="message" placeholder="Your Message" required></textarea>

      <input class="btn-contact-submit btn btn-lg btn-black" type="submit" name="submit" value="Send Message">

  </form>

This is the part I need to get parameter.

  <input class="btn-contact-submit btn btn-lg btn-black" type="submit" name="submit" value="Send Message">

And this is the email sending code.

<%
    String status = null;
    String parameter = null;

    //If request is submit, sending email.
    if (request.getParameter("submit") != null) {

        EmailSender email = new EmailSender();
        email.setMailServerProperties();

        //Email subject.
        String emailSubject = "Message from asdasd.com";
        //Email body.
        String emailBody = "";

        //If name is not empty, adding name to email body.
        if (request.getParameter("name") != null) {
            emailBody = "Sender Name: " + request.getParameter("name") + "
";
        }

        //If email is not empty, adding email to email body.
        if (request.getParameter("email") != null) {
            emailBody = emailBody + "Sender Email: " + request.getParameter("email") + "
";
        }

        //If subject is not empty, adding subject to email body.
        if (request.getParameter("subject") != null) {
            emailBody = emailBody + "Subject: " + request.getParameter("subject") + "
";
        }

        //If message is not empty, adding message to email body.
        if (request.getParameter("message") != null) {
            emailBody = emailBody + "Message: " + request.getParameter("message") + "
";
        }

        //Creating email object with emailSubject and emailBody.
        email.createEmailMessage(emailSubject, emailBody);

        /*
        try {
            //Sending email.
            email.sendEmail();
        } catch (MessagingException me) {
            out.print(me.getMessage());
        }
        */
        status = "Email sent.";
        parameter = request.getParameter("submit");
        out.print(status + parameter);
    } else {
        status = "Email not sent.";
        parameter = request.getParameter("submit");
        out.print(status + parameter);
    }
%>

How can I make this part (request.getParameter("submit") != null) true when the forms submit button is clicked?

Edit: I noticed something. I can't get parameter of any field in this page, not only submit button.

Edit2: After many tries the working code started not to work. Is the problem can be related to apache tomcat? Is there any way to test this consistently without server issues.


问:
How do I build webpages that can communicate with iOS devices?
I've got a pretty good handle on Objective C and my next step is to learn to build webpages that can communicate with iOS devices.

I want to be able to create text on the iPhone and push it to a webpage and vice versa.
I want to be able to push video and picture to the website and vice versa from the iPhone.
I want to be able to access SQL databases on a website as well as push data into an online SQL database from CoreData on the iPhone using SQL as persistent store.

Which languages, technologies and development environments do I need to get and learn?

Thanks.

-A

答:
So I'm just doing this myself :).

A lot of questions, but to keep it simple... I would recommend building REST based JSON web-services exposed from your website.  This seems to be the most commononly used method these days.  Hopefully you can keep it simple and not worry about authentication, but if you do you can always use some basic HTTP authentication.  Otherwise, if you want something more complex take a look at OAuth2 (http://oauth.net/2/).

For technologies, PHP seems to be the easiest to get up and running and you can find a ton of PHP REST/JSON web-service examples out there.

ContentLicense: CC BY-SA 2.5


问:
convert row into column in access
I have a dataset in the below format:

```<code> ID   A  B  C  D
 1    x  x  x  x
 2    x  x  x  x
 3    x  x  x  x
 4    x  x  x  x
</code>```

I want to convert it into a format where ID is duplicated with the values of the rows, e.g. to look something like below:

```<code>ID    Letter    Value
1       A         x
1       B         x
1       C         x
1       D         x
2       A         x
2       B         x
2       C         x
2       D         X
</code>```

and so on....

Many thanks in advance.

答:
useful link:

Columns to Rows in MS Access

Title: convert row into column in access

Body:
I have a dataset in the below format:

 ID   A  B  C  D
 1    x  x  x  x
 2    x  x  x  x
 3    x  x  x  x
 4    x  x  x  x

I want to convert it into a format where ID is duplicated with the values of the rows, e.g. to look something like below:

ID    Letter    Value
1       A         x
1       B         x
1       C         x
1       D         x
2       A         x
2       B         x
2       C         x
2       D         X

and so on....

Many thanks in advance.


问:
Why does my background flicker through my meshes in DirectX 12 Release build?
I have been developing this game in C++ in Visual Studio using DirectX 12. I used the Debug build configuration during development and the graphics were smooth as butter.

When I was preparing to publish the game on the Windows Store so I could share it with friends as play testers, I switched to Release build configuration. As soon as I did that I started getting this flicker of the back-ground color coming through my wall meshes.

Here is a short video that shows the flicker.
Here is a longer video that I made before switching to Release build configuration that shows there is no flicker.

I am new to DirectX 12. This project was my teacher. I studied Microsoft's Direct3D 12 Graphics, and I studied the DirectX 12 templates in Visual Studio.
I felt quite pleased that I was able to master DirectX 12 well enough to produce this game as well as I did. Then the Release thing, and the flicker thing, and I am at a loss.

Is this likely to be a shader issue? or a command queue issue? or a texture issue? or something else?

答:
DirectX 12 is an API designed for graphics experts and provides a great deal of application control compared to say Direct3D 11. The cost of that control is that you the application developer are responsible for getting everything right, making sure it works across a broad range of hardware, and robustly handling stress scenarios and error cases all yourself.

There are numerous ways you can get 'blinking' effects in DirectX 12. A common one is failure to keep your graphics memory with constants, IBs, VBs, etc. unchanged between the time you call Draw and the time the actual draw completes on the GPU which often happens a few frames later. This synchronization is a key challenge of using the API properly. For an example solution, see GraphicsMemory in DirectX Tool Kit for DirectX 12.

If you are new to DirectX development, I strongly advise starting with DirectX 11. It's basically the same functionality, but takes care of buffer renaming, resource barriers, fences, VRAM overcommit, etc.


问:
How do you create a custom user role in Azure AD?
Found this article on how to setup roles but it uses the legacy azure portal to accomplish this.

How do you create user roles in the latest Azure portal?

How do you assign multiple roles to a user afterwards?

答:
From December 2015, you can create your own RBAC roles.

You can get clear idea via this Custom Roles in Azure RBAC


问:
Jsp iterate through object list
I'm having troubles iterating with jsp trough list/lists. Here is my object class called Table:

```<code>public class Table{

private String name;
private List<String> columns;
private List<Row> rows;

... continuing with getters and setters nothing more here

}
</code>```

In my Row class I have just Strings(ex: String name), no lists no nothing.

Currently I have some List
 and I'm iterating trough it like this:

```<code><c:forEach var='table' items='${requestScope.tables}'>
        <c:out value="{table.name}"></c:out>
</c:forEach>
</code>```

Just for testing .. and it prints just {table.name} x times(the correct number of table objects in the table list).

My final goal is something like this (pseudo code):

```<code>for each table in table list
     print name
     for each column in colum list
         print column
     end column list for
     for each Row in row list
         print Row.name
     end row list for
end table list for
</code>```

Could someone help me out with syntax?

答:
```<code><c:forEach var="table" items='${requestScope.tables}'>
        <c:out value="${table.name}"></c:out>

        <c:forEach var="column" items='${table.columns}'>
           <c:out value="${column}"></c:out>
        </c:forEach>

        <c:forEach var="row" items='${table.rows}'>
           <c:out value="${row.name}"></c:out>
        </c:forEach>

</c:forEach>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Jsp iterate through object list

Body:
I'm having troubles iterating with jsp trough list/lists. Here is my object class called Table:

public class Table{

private String name;
private List<String> columns;
private List<Row> rows;

... continuing with getters and setters nothing more here

}

In my Row class I have just Strings(ex: String name), no lists no nothing.

Currently I have some List
 and I'm iterating trough it like this:

<c:forEach var='table' items='${requestScope.tables}'>
        <c:out value="{table.name}"></c:out>
</c:forEach>

Just for testing .. and it prints just {table.name} x times(the correct number of table objects in the table list).

My final goal is something like this (pseudo code):

for each table in table list
     print name
     for each column in colum list
         print column
     end column list for
     for each Row in row list
         print Row.name
     end row list for
end table list for

Could someone help me out with syntax?


问:
typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here
I am trying to use Typescript for my AWS Lambda and i am getting the following errors where ever I use promises.

```
error TS2693: 'Promise' only refers to a type, but is being used as a value here.
```

I tried using the following variations in the code

Using the Promise constructor

```<code>responsePromise = new Promise((resolve, reject) => {
                    return reject(new Error(`missing is needed data`))
                })
</code>```

using Promise.reject

```<code>responsePromise = Promise.reject(new Error(`Unsupported method "${request.httpMethod}"`));
</code>```

Versions

Following are the versions in my dev dependencies:

```<code>"typescript": "^2.2.2"
"@types/aws-lambda": "0.0.9",
"@types/core-js": "^0.9.40",
"@types/node": "^7.0.12",
</code>```

Contents of tsconfig.json

```<code>{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "commonjs",
        // "typeRoots" : ["./typings", "./node_modules/@types"],
        "target": "es5",
        // "types" : [ "core-js" ],
        "noImplicitAny": true,
        "strictNullChecks": true,
        "allowJs": true,
        "noEmit": true,
        "alwaysStrict": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "outDir": "dist",
        "moduleResolution": "Node",
        "declaration": true,
        "lib": [
            "es6"
        ]
    },
    "include": [
        "index.ts",
        "lib/**/*.ts"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}
</code>```

I am using grunt-ts with the following configuration for running ts task.

```<code>ts: {
            app: {
                tsconfig: {
                    tsconfig: "./tsconfig.json",
                    ignoreSettings: true
                }
            },
...
</code>```

I tried with the solution mentioned in I get: [ts] 'Promise' only refers to a type, but is being used as a value here but no luck.

答:
Core-js did not work for me as it caused other issues, however, simply installing the latest version of npm i @types/es6-promise --save-dev got rid of the issues. The issues for me stemmed from compiling an sdk that was using rxjs. Here is the error I was getting:

```<code>`node_modules/rxjs/Observable.d.ts(59,60): error TS2693: Promise only refers to a type, but is being used as a value here.`
</code>```

Body:
I am trying to use Typescript for my AWS Lambda and i am getting the following errors where ever I use promises.

error TS2693: 'Promise' only refers to a type, but is being used as a value here.

I tried using the following variations in the code

Using the Promise constructor

responsePromise = new Promise((resolve, reject) => {
                    return reject(new Error(`missing is needed data`))
                })

using Promise.reject

responsePromise = Promise.reject(new Error(`Unsupported method "${request.httpMethod}"`));

Versions

Following are the versions in my dev dependencies:

"typescript": "^2.2.2"
"@types/aws-lambda": "0.0.9",
"@types/core-js": "^0.9.40",
"@types/node": "^7.0.12",

Contents of tsconfig.json

{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "commonjs",
        // "typeRoots" : ["./typings", "./node_modules/@types"],
        "target": "es5",
        // "types" : [ "core-js" ],
        "noImplicitAny": true,
        "strictNullChecks": true,
        "allowJs": true,
        "noEmit": true,
        "alwaysStrict": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "outDir": "dist",
        "moduleResolution": "Node",
        "declaration": true,
        "lib": [
            "es6"
        ]
    },
    "include": [
        "index.ts",
        "lib/**/*.ts"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

I am using grunt-ts with the following configuration for running ts task.

ts: {
            app: {
                tsconfig: {
                    tsconfig: "./tsconfig.json",
                    ignoreSettings: true
                }
            },
...

I tried with the solution mentioned in I get: [ts] 'Promise' only refers to a type, but is being used as a value here but no luck.

Body:
Core-js did not work for me as it caused other issues, however, simply installing the latest version of npm i @types/es6-promise --save-dev got rid of the issues. The issues for me stemmed from compiling an sdk that was using rxjs. Here is the error I was getting:

`node_modules/rxjs/Observable.d.ts(59,60): error TS2693: Promise only refers to a type, but is being used as a value here.`


问:
Is it possible in MySQL to search a table for where a column only contains 1 comma?
I have this column in a table which is comma delimited to separate the values.

Here's the sample data:

```<code>2003,2004
2003,2005
2003,2006
2003,2004,2005
2003,2007
</code>```

I want to get all data that contains only 1 comma.

I've been playing around with the '%' and '_' wildcards, but I can't seem to get the results I need.

SELECT column FROM table WHERE column like '%_,%'

答:
You can also use find_in_set()  method which searches a value in comma separated list, by picking the last value of column using substring_index we can then check result of  find_in_set should be 2 so that its the second and last value from list

```<code>select *
from demo
where find_in_set(substring_index(data,',',-1),data) = 2
</code>```

Demo

Body:
I have this column in a table which is comma delimited to separate the values.

Here's the sample data:

2003,2004
2003,2005
2003,2006
2003,2004,2005
2003,2007

I want to get all data that contains only 1 comma.

I've been playing around with the '%' and '_' wildcards, but I can't seem to get the results I need.

SELECT column FROM table WHERE column like '%_,%'

Body:
You can also use find_in_set()  method which searches a value in comma separated list, by picking the last value of column using substring_index we can then check result of  find_in_set should be 2 so that its the second and last value from list

select *
from demo
where find_in_set(substring_index(data,',',-1),data) = 2

Demo


问:
How to get primary keys after batch insert in MyBatis
use annotation @Options(useGeneratedKeys = true, keyProperty = "id") to get the generated primary key for single insert is fine for me , but when I use annotation @InsertProvider to make a batch insert , I have no idea how to get the generated primary keys , any comments will be appreciated . thx in advance</p>

答:
```<code>import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;

public interface TestMapper {

  ...

  @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
  @Insert({
    "<script>",
      "INSERT INTO test_table",
        "(column_one, column_two)",
      "VALUES" +
        "<foreach item='item' collection='list' open='' separator=',' close=''>" +
          "(" +
            "#{item.columnOne,jdbcType=VARCHAR},",
            "#{item.columnTwo,jdbcType=VARCHAR}" +
          ")" +
        "</foreach>",
    "</script>"})
  void insertBatchTestTable(@Param("list") List<TestObject> testObjs);

}
</code>```

ps.:

Set keyColumn and keyProperty

Use @Param("list")

MyBatis will set objects keyProperty by reflection

Body:
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;

public interface TestMapper {

  ...

  @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
  @Insert({
    "<script>",
      "INSERT INTO test_table",
        "(column_one, column_two)",
      "VALUES" +
        "<foreach item='item' collection='list' open='' separator=',' close=''>" +
          "(" +
            "#{item.columnOne,jdbcType=VARCHAR},",
            "#{item.columnTwo,jdbcType=VARCHAR}" +
          ")" +
        "</foreach>",
    "</script>"})
  void insertBatchTestTable(@Param("list") List<TestObject> testObjs);

}

ps.:

Set keyColumn and keyProperty

Use @Param("list")

MyBatis will set objects keyProperty by reflection


问:
copy dynamic ranges from excel to word vba
I have a sheet of data and the range vary each week meaning last used row and last used column vary. I hope to copy 3 ranges at a time and paste it as picture into word using vba. This is part of a larger codes so that is why I am hoping to achieve it by writing vba.

The reason behind 3 ranges at a time is because of the picture size fits best in word. Headers are merged in row 2 and 3. I am showing you 4 ranges but sometimes I get 2 ranges and sometimes 6 ranges. i.e. 3 ranges or below should just be one picture and from 4-6 ranges will mean I have 2 pictures in word.

Right now when I run my codes, nothing is pasted in word.

```<code>Sub Table()

    Dim wdapp As Word.Application
    Set wdapp = New Word.Application

    With wdapp
        .Visible = True
        .Activate
        .Documents.Add
    End With

    With ThisWorkbook.Worksheets("Table")
        Dim a, b, c, RR As Range
  '1
        Set a = .Cells.Find("Header1", LookIn:=xlValues)

        If Not a Is Nothing Then
            Dim firstAddress As String
            firstAddress = a.Address
            Do
' 2
  Set b = .Cells.Find("Header1", a, LookIn:=xlValues)
' 3
  Set c = .Cells.Find("Header1", b, LookIn:=xlValues)
'Union
Set RR = Union(Range(a.End(xlDown).End(xlDown), a.Resize(, 7)), Range(b.End(xlDown).End(xlDown), b.Resize(, 7)), Range(c.End(xlDown).End(xlDown), a.Resize(, 20)))
    RR.CopyPicture Appearance:=xlScreen, Format:=xlPicture
                wdapp.Selection.Paste
                Set a = .UsedRange.FindNext(a)
                If a Is Nothing Then Exit Do
            Loop While a.Address <> firstAddress

        End If
    End With

End Sub
</code>```

答:
I just changed your dim statements, since those will not work with 2016 on win 7

```<code>Dim wdapp As Object
Dim d As Range
Set wdapp = CreateObject("Word.Application")
</code>```

Then it worked just fine.

Body:
I have a sheet of data and the range vary each week meaning last used row and last used column vary. I hope to copy 3 ranges at a time and paste it as picture into word using vba. This is part of a larger codes so that is why I am hoping to achieve it by writing vba.

The reason behind 3 ranges at a time is because of the picture size fits best in word. Headers are merged in row 2 and 3. I am showing you 4 ranges but sometimes I get 2 ranges and sometimes 6 ranges. i.e. 3 ranges or below should just be one picture and from 4-6 ranges will mean I have 2 pictures in word.

Right now when I run my codes, nothing is pasted in word.

Sub Table()

    Dim wdapp As Word.Application
    Set wdapp = New Word.Application

    With wdapp
        .Visible = True
        .Activate
        .Documents.Add
    End With

    With ThisWorkbook.Worksheets("Table")
        Dim a, b, c, RR As Range
  '1
        Set a = .Cells.Find("Header1", LookIn:=xlValues)

        If Not a Is Nothing Then
            Dim firstAddress As String
            firstAddress = a.Address
            Do
' 2
  Set b = .Cells.Find("Header1", a, LookIn:=xlValues)
' 3
  Set c = .Cells.Find("Header1", b, LookIn:=xlValues)
'Union
Set RR = Union(Range(a.End(xlDown).End(xlDown), a.Resize(, 7)), Range(b.End(xlDown).End(xlDown), b.Resize(, 7)), Range(c.End(xlDown).End(xlDown), a.Resize(, 20)))
    RR.CopyPicture Appearance:=xlScreen, Format:=xlPicture
                wdapp.Selection.Paste
                Set a = .UsedRange.FindNext(a)
                If a Is Nothing Then Exit Do
            Loop While a.Address <> firstAddress

        End If
    End With

End Sub

Body:
I just changed your dim statements, since those will not work with 2016 on win 7

Dim wdapp As Object
Dim d As Range
Set wdapp = CreateObject("Word.Application")

Then it worked just fine.


问:
geting error/warning for plurals : "The quantity 'one' matches more than one specific number..."

Background

I work on an app that has many translations inside it.

I have the next English plural strings:

```<code><plurals name="something">
    <item quantity="one">added photo</item>
    <item quantity="other">added %d photos</item>
</plurals>
</code>```

and the French translation:

```<code><plurals name="something">
    <item quantity="one">a ajouté une photo</item>
    <item quantity="other">a ajouté %d photos</item>
</plurals>
</code>```

The problem

For both the French and Russian, I get the next warning:

The quantity 'one' matches more than one specific number in this
  locale, but the message did not include a formatting argument (such as
  %d). This is usually an internationalization error. See full issue
  explanation for more.

when choosing to show details , it says:

Thins is, I don't get what should be done to fix it, and if there is even a problem...

The question

What exactly should I do with those strings? What should I tell the translators?

答:
In French singular form is used when count is 0 or 1. In English singular form is used only when count is 1. 0 uses a plural form.

This is why you need to insert a placeholder (%d) in your French singular pattern.

Body:
Background

I work on an app that has many translations inside it.

I have the next English plural strings:

<plurals name="something">
    <item quantity="one">added photo</item>
    <item quantity="other">added %d photos</item>
</plurals>

and the French translation:

<plurals name="something">
    <item quantity="one">a ajouté une photo</item>
    <item quantity="other">a ajouté %d photos</item>
</plurals>

The problem

For both the French and Russian, I get the next warning:

The quantity 'one' matches more than one specific number in this
  locale, but the message did not include a formatting argument (such as
  %d). This is usually an internationalization error. See full issue
  explanation for more.

when choosing to show details , it says:

Thins is, I don't get what should be done to fix it, and if there is even a problem...

The question

What exactly should I do with those strings? What should I tell the translators?


问:
How to CREATE TABLE with formatted column
I need to create a new empty table, where each new value should be validated by server using format of its column. Like, ###-###-##, where each # is a digit from 0 to 9, and it should contain those - symbols. How?

答:
Use CHECK Constraint:

```<code>CREATE TABLE YourTable (
    Col1 VARCHAR(10),
    CONSTRAINT MyContraint CHECK (Col1 LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9]')
                );
</code>```

Body:
Use CHECK Constraint:

CREATE TABLE YourTable (
    Col1 VARCHAR(10),
    CONSTRAINT MyContraint CHECK (Col1 LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9]')
                );


问:
Finding connections between objects to the nth degree
For the following models:

```<code>class Entity(models.Model):
    name = models.CharField(max_length=256)

class Entry(models.Model):
    """ A <subj> has a <connection> to an <obj>
    """
    subj = models.ForeignKey(Entity, related_name='subject')
    connection = models.CharField(max_length=512)
    obj = models.ForeignKey(Entity, related_name='object')
</code>```

I have this kind of data stored:

A works at Z

B works at Z

B is the brother of C

C lives next door to D

where A, B, C, D and Z are Entity instances
and "works at", etc are stored in the 'relation' field of the Entry model.

Now, how do I proceed to find a link between A and D, considering there are many connections between all of the Entities? I would like to be able to print out something like:

A is connected to D in the 4th degree (and show the steps in the meanwhile).

I've tagged this as a Django question as the intent is to use this on a Django-powered website, but I wonder whether Django's ORM can help here.

Thanks in advance!

答: You need to look into an algorithm like Modified Pre-Order Tree Traversal, which allows you to store this kind of information in the database. There's a good Django implementation called django-mptt.</p>

Body:
For the following models:

class Entity(models.Model):
    name = models.CharField(max_length=256)

class Entry(models.Model):
    """ A <subj> has a <connection> to an <obj>
    """
    subj = models.ForeignKey(Entity, related_name='subject')
    connection = models.CharField(max_length=512)
    obj = models.ForeignKey(Entity, related_name='object')

I have this kind of data stored:

A works at Z

B works at Z

B is the brother of C

C lives next door to D

where A, B, C, D and Z are Entity instances
and "works at", etc are stored in the 'relation' field of the Entry model.

Now, how do I proceed to find a link between A and D, considering there are many connections between all of the Entities? I would like to be able to print out something like:

A is connected to D in the 4th degree (and show the steps in the meanwhile).

I've tagged this as a Django question as the intent is to use this on a Django-powered website, but I wonder whether Django's ORM can help here.

Thanks in advance!


问:
Nodejs: Mongoose find latest entry of the DB with filter
So, I've been trying to find the right answer to my problem and even if some questions come pretty close, I'm not sure any of them apply to my particular situation:

I have a MongoDB that is constantly being fed by info and I would like to query the latest document but specifying a filter:

```<code>return new Promise((resolve, reject) => {
    model.findOne({ bar: "foo" }, {}, { sort: { n: -1 } }, function(
      err,
      obj
    ) {
      resolve(obj);
    });
  });
</code>```

The code above doesn't achieve what I'm trying to do properly... My guess is that it looks first for a document with the key bar / value foo and then sorts the results however, since the "results" are really just a single result, it sorts 'nothing' per se and therefore returns the first 'foo' document that was found in the DB.

The DB has many 'foo' documents and I want to query the latest.

Thanks in advance.

答:
I guess you intend to get the latest document containing foo at bar key ,so this will return the latest document.</p>

```<code> return new Promise((resolve, reject) => {
        model.findOne({ bar: "foo" }, {}, { sort: { '_id': -1 } }, function(
          err,
          obj
        ) {
          resolve(obj);
        });
      });
</code>```

Body:
So, I've been trying to find the right answer to my problem and even if some questions come pretty close, I'm not sure any of them apply to my particular situation:

I have a MongoDB that is constantly being fed by info and I would like to query the latest document but specifying a filter:

return new Promise((resolve, reject) => {
    model.findOne({ bar: "foo" }, {}, { sort: { n: -1 } }, function(
      err,
      obj
    ) {
      resolve(obj);
    });
  });

The code above doesn't achieve what I'm trying to do properly... My guess is that it looks first for a document with the key bar / value foo and then sorts the results however, since the "results" are really just a single result, it sorts 'nothing' per se and therefore returns the first 'foo' document that was found in the DB.

The DB has many 'foo' documents and I want to query the latest.

Thanks in advance.

Body:
I guess you intend to get the latest document containing foo at bar key ,so this will return the latest document.

 return new Promise((resolve, reject) => {
        model.findOne({ bar: "foo" }, {}, { sort: { '_id': -1 } }, function(
          err,
          obj
        ) {
          resolve(obj);
        });
      });


问:
Python 'height' is not defined
Python is saying that the name 'height' is not defined, and I have no idea why that is, as according to my logic, I return the variable height, so I would be able to access it within my for loop?

Can someone point me in the right direction?
Thanks.
Edit: the get_int() is a function inside the cs50 library.

```<code>import cs50

def main():

    print("Enter a number between 0 and 26: ", end="")

    i = get_height("Enter height: ", end="")

def get_height():
    while True:
        height = get_int()
        if height <= 0 or height >= 23:
            break
    return height

for i in range(height):
    print(" " * (height - i), end="")
    print("#" * (i + 2), end="")
    print("")

if __name__ == "__main__":
    main()
</code>```

答:
```<code>def get_int():
    tx = input("Enter height: ")
    if tx.isdigit():
        return int(tx)
    return None

def get_height():
    while True:
        height = get_int()
        if height and height > 0 and height < 26:
            return height

if __name__ == "__main__":
    print("Enter a number between 0 and 26: ")

    height = get_height()
    for i in range(height):
        print(" " * (height - i), end='')
        print("#" * (i + 2), end='')
        print("")
</code>```

get_int doesn't exists

height was out of scope

height on the while loop was not visible from the def scope

get_height get no param

for in range was out of the main scope

Title: Python 'height' is not defined

Body:
Python is saying that the name 'height' is not defined, and I have no idea why that is, as according to my logic, I return the variable height, so I would be able to access it within my for loop?

Can someone point me in the right direction?
Thanks.
Edit: the get_int() is a function inside the cs50 library.

import cs50

def main():

    print("Enter a number between 0 and 26: ", end="")

    i = get_height("Enter height: ", end="")

def get_height():
    while True:
        height = get_int()
        if height <= 0 or height >= 23:
            break
    return height

for i in range(height):
    print(" " * (height - i), end="")
    print("#" * (i + 2), end="")
    print("")

if __name__ == "__main__":
    main()

Body:
def get_int():
    tx = input("Enter height: ")
    if tx.isdigit():
        return int(tx)
    return None

def get_height():
    while True:
        height = get_int()
        if height and height > 0 and height < 26:
            return height

if __name__ == "__main__":
    print("Enter a number between 0 and 26: ")

    height = get_height()
    for i in range(height):
        print(" " * (height - i), end='')
        print("#" * (i + 2), end='')
        print("")

get_int doesn't exists

height was out of scope

height on the while loop was not visible from the def scope

get_height get no param

for in range was out of the main scope


问:
compile error: ByRef argument type mismatch, What am I missing?
I'm not understanding what the problem is.

I have the following code:

```<code>Public Sub SetupForm()
    Dim wbMain As Workbook
    Dim wsToner As Worksheet
    Set wbMain = ActiveWorkbook
    Set wsToner = wbMain.Sheets("Toner")
    With DashboardForm
        'Parent nodes
        Dim Brands() As String
        Brands() = GetTonerBrand(wsToner)
</code>```

The last line is calling the following function:

```<code>Private Function GetTonerBrand(wsSheet As Worksheet) As String
    Dim col, Counter
    Dim LastCol
    Counter = 0
    Dim LastRow
    Dim Brands() As String
    With wsSheet
        LastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
        Dim RowCount
        RowCount = LastRow
    End With
    Dim dict
    Set dict = CreateObject("Scripting.Dictionary")
    Do While RowCount > 3
        If Not dict.exists(wsToner.Cells(RowCount, 2).Value) Then
            dict.Add wsToner.Cells(RowCount, 2).Value, 0
        End If
        RowCount = RowCount - 1
    Loop
    ReDim Brands(0 To dict.Count)
    Brands() = dict.keys()
    GetTonerBrand Brands
End Function
</code>```

When I attempt to run this I get the error below:

Compile error: ByRef argument type mismatch

I thought that if I update the type of the array and function then it would work.

So I changed the Function to String and the Brands() arrays as well were changed to String. Then I get an error:

Compile error: Can't assign to array

in the SetupForm sub on the line Brands() = GetTonerBrand(wsToner)

Obviouly I'm missing something, I just don't see what it is.

UPDATE

I have seen this other question with a similar name, it isn't helpful.

答:
Good points were made in the comments to your question, but none addressed the fact that VBA won't magically cast your dictionary keys, a Variant array, to a String array.

I suggest you modify your function to return a Variant array. In your calling code, you'd have to modify your declarartion:

```<code>'Parent nodes
Dim Brands() As Variant
</code>```

In the code below, notice that superflous variables were eliminated, while remaining variables were declared with a suitable type. At the end, to return the value, the function's name is assigned the dictionary's keys.

```<code>Private Function GetTonerBrand(wsSheet As Worksheet) As Variant()
    Dim row As Long
    Dim tonerBrands As Object
    Dim tonerBrand As String

    With wsSheet
        row = .Cells(.Rows.Count, 2).End(xlUp).row
    End With

    Set tonerBrands = CreateObject("Scripting.Dictionary")

    Do While row > 3
        tonerBrand = CStr(wsToner.Cells(row, 2).Value)
        If Not tonerBrands.Exists(tonerBrand) Then
            tonerBrands.Add tonerBrand, 0
        End If
        row = row - 1
    Loop

    GetTonerBrand = tonerBrands.Keys()
End Function
</code>```

A cool thing about variant arrays is that you can iterate through them using a variant-type variable, with a simple For Each.

Body:
I'm not understanding what the problem is.

I have the following code:

Public Sub SetupForm()
    Dim wbMain As Workbook
    Dim wsToner As Worksheet
    Set wbMain = ActiveWorkbook
    Set wsToner = wbMain.Sheets("Toner")
    With DashboardForm
        'Parent nodes
        Dim Brands() As String
        Brands() = GetTonerBrand(wsToner)

The last line is calling the following function:

Private Function GetTonerBrand(wsSheet As Worksheet) As String
    Dim col, Counter
    Dim LastCol
    Counter = 0
    Dim LastRow
    Dim Brands() As String
    With wsSheet
        LastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
        Dim RowCount
        RowCount = LastRow
    End With
    Dim dict
    Set dict = CreateObject("Scripting.Dictionary")
    Do While RowCount > 3
        If Not dict.exists(wsToner.Cells(RowCount, 2).Value) Then
            dict.Add wsToner.Cells(RowCount, 2).Value, 0
        End If
        RowCount = RowCount - 1
    Loop
    ReDim Brands(0 To dict.Count)
    Brands() = dict.keys()
    GetTonerBrand Brands
End Function

When I attempt to run this I get the error below:

Compile error: ByRef argument type mismatch

I thought that if I update the type of the array and function then it would work.

So I changed the Function to String and the Brands() arrays as well were changed to String. Then I get an error:

Compile error: Can't assign to array

in the SetupForm sub on the line Brands() = GetTonerBrand(wsToner)

Obviouly I'm missing something, I just don't see what it is.

UPDATE

I have seen this other question with a similar name, it isn't helpful.

Body:
Good points were made in the comments to your question, but none addressed the fact that VBA won't magically cast your dictionary keys, a Variant array, to a String array.

I suggest you modify your function to return a Variant array. In your calling code, you'd have to modify your declarartion:

'Parent nodes
Dim Brands() As Variant

In the code below, notice that superflous variables were eliminated, while remaining variables were declared with a suitable type. At the end, to return the value, the function's name is assigned the dictionary's keys.

Private Function GetTonerBrand(wsSheet As Worksheet) As Variant()
    Dim row As Long
    Dim tonerBrands As Object
    Dim tonerBrand As String

    With wsSheet
        row = .Cells(.Rows.Count, 2).End(xlUp).row
    End With

    Set tonerBrands = CreateObject("Scripting.Dictionary")

    Do While row > 3
        tonerBrand = CStr(wsToner.Cells(row, 2).Value)
        If Not tonerBrands.Exists(tonerBrand) Then
            tonerBrands.Add tonerBrand, 0
        End If
        row = row - 1
    Loop

    GetTonerBrand = tonerBrands.Keys()
End Function

A cool thing about variant arrays is that you can iterate through them using a variant-type variable, with a simple For Each.


问:
Patching macvim remote editing, file netrw.vim
So there's a problem with macvim when doing remote editing through
:e scp://path/to/file
Every time I try to save :w, macvim complains E382: Cannot write, 'buftype' option is set.
The quick fix to solving this is to do :set buftype:""
However, there are patches out there to solve the issue. So I downloaded a patch file to fix this problem. The problem is located in the netrw.vim file. When I try to patch the file netrw.vim through patch -p1 < file.patch, it gives me an error that says
patch: **** Can't rename file netrw.vim to netrw.vim.orig : Permission denied

I tried chmod for netrw.vim, but it doesn't let me.
Any help is appreciated!
p.s. I'm running on OSX 10.9.5

答: if you opened a remote directory and selected a file to edit you need create the tmp file in you local and set this command :set by=acwrite or :set buftype=acwrite and finally save your changes :w.


问:
Efficiently convert an unsigned short to a char*
What would be an efficient, portable way to convert a unsigned short to a char* (i.e. convert 25 to '25').

I'd like to avoid things such as getting (std::string) strings involved.  Performance is important in this case since this conversion will need to happen quickly and often.

I was looking into things such as using sprintf but would like to explorer any and all ideas.

答:
First off, do it right, then do it fast--only optimize if you can see for certain that a piece of code is not performant.

snprintf() into a buffer will do what you want. Is it the fastest possible solution? Not at all. But it is among the simplest, and it will suffice to get your code into a working state. From there, if you see that those calls to snprintf() are so laborious that they need to be optimized, then and only then seek out a faster solution.


问:
How to invalidate that which column having data type mismatch
I have table with some records in one user and another table with empty records. I want to migrate the data of that table from one user to another but I got one error ORA: 01722 because the datatype of the target table is slightly mismatch. What should I do resolve this problem without changes the datatype.
Data type of the source table is-

Description of the target table-

In both table in different user only one column is mismatch datatype LOTFRONTAGE. In source table datatype is varchar2 and in target table datatype is Number.

How to invalidate that which column having data type mismatch.

答:
How to invalidate that which column having data type mismatch.

What do you mean by invalidating a column?. There is no such facility available to you in Oracle.

All you can do is to try to identify the non-numeric characters in your LOTFRONTAGE . Run this query to find what values are non-numeric.

```<code>SELECT
        ID,
        LOTFRONTAGE
FROM
        yoursourcetable
WHERE   REGEXP_LIKE(LOTFRONTAGE, '[^0-9]+');
</code>```

Once you get the ids and column values, you can update those values or replace them in your insert.

```<code>update yoursourcetable SET LOTFRONTAGE = <numeric_value>
where ID = <id> and  LOTFRONTAGE = '<non-numeric value>;
</code>```

and run INSERT.

OR

```<code>INSERT INTO yourdesttable
        (col1,col2...
        )
SELECT ID, REPLACE (LOTFRONTAGE ,<non-numeric>,<numeric>),... from yoursourcetable ;
</code>```

Body:
How to invalidate that which column having data type mismatch.

What do you mean by invalidating a column?. There is no such facility available to you in Oracle.

All you can do is to try to identify the non-numeric characters in your LOTFRONTAGE . Run this query to find what values are non-numeric.

SELECT
        ID,
        LOTFRONTAGE
FROM
        yoursourcetable
WHERE   REGEXP_LIKE(LOTFRONTAGE, '[^0-9]+');

Once you get the ids and column values, you can update those values or replace them in your insert.

update yoursourcetable SET LOTFRONTAGE = <numeric_value>
where ID = <id> and  LOTFRONTAGE = '<non-numeric value>;

and run INSERT.

OR

INSERT INTO yourdesttable
        (col1,col2...
        )
SELECT ID, REPLACE (LOTFRONTAGE ,<non-numeric>,<numeric>),... from yoursourcetable ;


问:
I register object in parent class but subscribe events in child class, yet it still works why?
So this is exactly how I want it to work but I'm just confused on why it works. I register the object in parent class but subscribe events in child class.

By registering the object in the parent class, wouldn't EventBus be seeing type parent class(only events subscribed in parent class)?

If that's the case, how is it able to see the events that are subscribed in child class then?

If someone can clarify this that would be awesome thanks!

答: "No, the child classes inherit the parent's methods. But the type when register(class) is called at runtime will be the type of the child, not the parent (class instanceOf Child). Hence EventBus only discovers the @Subscribed methods in the child class."</p>


问:
sqlloader loading unix timestamp
I cannot seem to load a unix timestamp using SQLLDR.

```<code>load data infile 'AST_BusinessService_export.csv'
append into table ccp.services_temp
 fields terminated by ',' optionally enclosed by '"' TRAILING NULLCOLS
 (NAME, SHORT_DESCRIPTION, CREATE_DATE EXPRESSION "(cast(:CREATE_DATE)as date) - TO_DATE('01/01/1970 00:00:00', 'MM-DD-YYYY HH24:MI:SS')) *
24 * 60 * 60")
</code>```

I am trying to pass

```<code>TEST-CI-GO,TIER2_H1_2 FW,1233817523
</code>```

Error I receive is SQL*Loader-291: Invalid bind variable CREATE_DATE in SQL string for column CREATE_DATE.

UPDATE

```<code>load data infile 'AST_BusinessService_export.csv'
append into table ccp.services_temp
 fields terminated by ',' optionally enclosed by '"' TRAILING NULLCOLS
 (NAME, SHORT_DESCRIPTION, CREATE_DATE EXPRESSION to_date('19700101', 'YYYYMMDD') + ( 1 / 24 / 60 / 60 ) * CREATE_DATE
</code>```

error is Expecting SQL string, found "to_date".
 (NAME, SHORT_DESCRIPTION, CREATE_DATE EXPRESSION to_date('19700101',

答:
If your input looks like:

```<code>TEST-CI-GO,TIER2_H1_2 FW,1233817523
</code>```

I believe you want to convert to date by doing something like:

```<code>select to_date('19700101', 'YYYYMMDD') + ( 1 / 24 / 60 / 60 ) * 1233817523
from dual;
</code>```

Output:

```<code>2/5/2009 7:05:23 AM
</code>```

So start at the epoch and add that many seconds (converted to days since thats what Oracle wants for adding to dates)

EDIT:

For a table like this:

```<code>create table test_unixdate
(
id number,
secs_since_epoch number,
converted_date date
);
</code>```

And data like this:

```<code>1,1233817521
2,1243817522
3,1253817523
4,
5,1263817525
</code>```

Your sqlldr might look like:

```<code>LOAD DATA
infile 'test_unixdate.csv'
badfile 'test_unixdate.bad'
discardfile 'test_unixdate.dis'
APPEND
INTO TABLE test_unixdate
Fields terminated by ","
Optionally enclosed by '"'
trailing nullcols
(
id nullif id=blanks,
secs_since_epoch nullif secs_since_epoch=blanks,
converted_date "to_date('19700101', 'YYYYMMDD') + ( 1 / 24 / 60 / 60 ) * :secs_since_epoch"
)
</code>```

Output (select * from test_unixdate):

```<code>1   1233817521  2/5/2009 7:05:21 AM
2   1243817522  6/1/2009 12:52:02 AM
3   1253817523  9/24/2009 6:38:43 PM
4
5   1263817525  1/18/2010 12:25:25 PM
</code>```

Title: sqlloader loading unix timestamp

Body:
I cannot seem to load a unix timestamp using SQLLDR.

load data infile 'AST_BusinessService_export.csv'
append into table ccp.services_temp
 fields terminated by ',' optionally enclosed by '"' TRAILING NULLCOLS
 (NAME, SHORT_DESCRIPTION, CREATE_DATE EXPRESSION "(cast(:CREATE_DATE)as date) - TO_DATE('01/01/1970 00:00:00', 'MM-DD-YYYY HH24:MI:SS')) *
24 * 60 * 60")

I am trying to pass

TEST-CI-GO,TIER2_H1_2 FW,1233817523

Error I receive is SQL*Loader-291: Invalid bind variable CREATE_DATE in SQL string for column CREATE_DATE.

UPDATE

load data infile 'AST_BusinessService_export.csv'
append into table ccp.services_temp
 fields terminated by ',' optionally enclosed by '"' TRAILING NULLCOLS
 (NAME, SHORT_DESCRIPTION, CREATE_DATE EXPRESSION to_date('19700101', 'YYYYMMDD') + ( 1 / 24 / 60 / 60 ) * CREATE_DATE

error is Expecting SQL string, found "to_date".
 (NAME, SHORT_DESCRIPTION, CREATE_DATE EXPRESSION to_date('19700101',

Body:
If your input looks like:

TEST-CI-GO,TIER2_H1_2 FW,1233817523

I believe you want to convert to date by doing something like:

select to_date('19700101', 'YYYYMMDD') + ( 1 / 24 / 60 / 60 ) * 1233817523
from dual;

Output:

2/5/2009 7:05:23 AM

So start at the epoch and add that many seconds (converted to days since thats what Oracle wants for adding to dates)

EDIT:

For a table like this:

create table test_unixdate
(
id number,
secs_since_epoch number,
converted_date date
);

And data like this:

1,1233817521
2,1243817522
3,1253817523
4,
5,1263817525

Your sqlldr might look like:

LOAD DATA
infile 'test_unixdate.csv'
badfile 'test_unixdate.bad'
discardfile 'test_unixdate.dis'
APPEND
INTO TABLE test_unixdate
Fields terminated by ","
Optionally enclosed by '"'
trailing nullcols
(
id nullif id=blanks,
secs_since_epoch nullif secs_since_epoch=blanks,
converted_date "to_date('19700101', 'YYYYMMDD') + ( 1 / 24 / 60 / 60 ) * :secs_since_epoch"
)

Output (select * from test_unixdate):

1   1233817521  2/5/2009 7:05:21 AM
2   1243817522  6/1/2009 12:52:02 AM
3   1253817523  9/24/2009 6:38:43 PM
4
5   1263817525  1/18/2010 12:25:25 PM


问:
php generate date/ time in the same format appears mysql datatime
I would like to know if there is a function in php to generate data/time format like in mysql : 0000-00-00 00:00:00 .
I know you can generate data/time in the sql query with CURDATE() but I would like to know if it's possible to generate it with php in the same format mysql datatime format .</p>

答: Sure is! Give this a go date('Y-m-d H:i:s')


问:
Hashing Access time with multi variable key
Suppose a dictionary has 2 variable keys instead of 1 like

```<code>dictionary[3,5] = Something
dictionry[1,2] = Something
dictionary[3,1] = Something
</code>```

Would the search time still be O(1).In case I need to find if dictionary[1,5] exists would it yield constant time?

Thanks in advance.

答:
When you do a lookup in a hash table, the cost involved is the cost of

hashing the item to look up, and

comparing that item against (an expected O(1) number of) other other entries in the table.

We can write the expected cost of a hash table lookup as O(hash-cost + compare-cost).

In your case, the cost of hashing a pair instead of a single element is still O(1) - just hash each element of the pair and apply some hash combination step to the two values. Similarly, the cost of comparing two pairs is also O(1) (assuming each individual element of the pair can be compared in constant time). As a result, a lookup will still be (expected) constant time.

The above argument generalizes to any fixed size triple as a key. You typically have to worry about the cost of hashing and comparing keys when they have variable length, as would be the case if you were hashing strings with no length restriction.

Body:
Suppose a dictionary has 2 variable keys instead of 1 like

dictionary[3,5] = Something
dictionry[1,2] = Something
dictionary[3,1] = Something

Would the search time still be O(1).In case I need to find if dictionary[1,5] exists would it yield constant time?

Thanks in advance.


问:
Scan QRcode with inverted colors using Vision API
After struggling a few hours on making my app detect this QRCode:

I realized that the problem was the in the QRCode appearance. After inverting the colors, the detection was working perfectly..

Is there a way to make Vision API detect the first QRCode? I tried to enable all symbologies but it did not work. I guess it is possible because the app QR Code Reader detects it.

答:
I think this is still an open issue, please see link for details. One workaround for this as stated by a developer:

Right, the barcode API generally doesn't support color-inverted codes. There's no parameter or option to control this at the moment. Though some APIs support them, I don't believe it's a common feature.

For a workaround, you could preprocess the colors in the bitmap before passing them to the barcode API (perhaps inverting colors on alternate frames).

Hope this helps.


问:
console.log in express.js route not logging mongodb ._id field
I have a weird situation and I'm unable to figure out why.
I'm learning MEAN and have the following setup:

My PUG file:

```<code>    br
  for product in products
    div.container
      div.row.border
        div.col-md-3
          p= product.name
          p= product._id
        div.col-md-3
          p= product.description
        div.col-md-3
          p= "$" + " " +product.price
        div.col-md-3
          form(action="/cart", method="post")
            input(type="hidden", value="#{product._id}" , name="id")
            button(type="Submit") Add To Cart
</code>```

My index.js file (basic one just to display my documents and delete them)

```<code>    var express = require('express');
var router = express.Router();
var cart = require('../lib/Cart.js');
var db = require('../lib/db.js');
var database = require('../database.js')

var mongoose = require('mongoose');
var Products = mongoose.model('Product');
var User = mongoose.model('User');

mongoose.connect = ('mongodb://localhost/products');

/* GET home page. */
router.get('/', function (req, res) {
    // console.log(sayHelloEnglish());

    Products.find(function (err, products) {
        res.render('index', { title: 'Express 2017 ', products: products });
        console.log(products);
    });
});

router.post('/', function (req, res) {
   // var newUser = new User ({name : req.body.name});
   // newUser.save(function(err, users){
     //   res.render('index', {title: "whatever"})
    //});

     var newProduct = new Products({ name: req.body.name, description: req.body.description, price: req.body.price });
    newProduct.save(function (err, products) {
        res.render('index', { title: "PRODUCTS", products: products });
    });
});

 //console.log is logging #{product._id} and not the value???
router.post('/cart', (function (req, res) {
    var id = req.body.id
    console.log(id);
    res.render('cart', {title: "Cart"});
}));

module.exports = router;
</code>```

Here is the question:
My console.log result is

```<code>#{product._id}
</code>```

It's not logging the actual id which is something like this: 5a0341e2ff549f2de8e307be
Any insight would be greatly appreciated as I'm unable to figure it out.
why console.log is showing the @{product._id} and not the actual id value?

答:
This style of attribute is no longer supported in pug:

```<code> input(type="hidden", value="#{product._id}" , name="id")
</code>```

use this instead:

```<code> input(type="hidden", value=product._id , name="id")
</code>```

More examples in the migration guide here: https://pugjs.org/api/migration-v2.html#attribute-interpolation

Body:
I have a weird situation and I'm unable to figure out why.
I'm learning MEAN and have the following setup:

My PUG file:

    br
  for product in products
    div.container
      div.row.border
        div.col-md-3
          p= product.name
          p= product._id
        div.col-md-3
          p= product.description
        div.col-md-3
          p= "$" + " " +product.price
        div.col-md-3
          form(action="/cart", method="post")
            input(type="hidden", value="#{product._id}" , name="id")
            button(type="Submit") Add To Cart

My index.js file (basic one just to display my documents and delete them)

    var express = require('express');
var router = express.Router();
var cart = require('../lib/Cart.js');
var db = require('../lib/db.js');
var database = require('../database.js')

var mongoose = require('mongoose');
var Products = mongoose.model('Product');
var User = mongoose.model('User');

mongoose.connect = ('mongodb://localhost/products');

/* GET home page. */
router.get('/', function (req, res) {
    // console.log(sayHelloEnglish());

    Products.find(function (err, products) {
        res.render('index', { title: 'Express 2017 ', products: products });
        console.log(products);
    });
});

router.post('/', function (req, res) {
   // var newUser = new User ({name : req.body.name});
   // newUser.save(function(err, users){
     //   res.render('index', {title: "whatever"})
    //});

     var newProduct = new Products({ name: req.body.name, description: req.body.description, price: req.body.price });
    newProduct.save(function (err, products) {
        res.render('index', { title: "PRODUCTS", products: products });
    });
});

 //console.log is logging #{product._id} and not the value???
router.post('/cart', (function (req, res) {
    var id = req.body.id
    console.log(id);
    res.render('cart', {title: "Cart"});
}));

module.exports = router;

Here is the question:
My console.log result is

#{product._id}

It's not logging the actual id which is something like this: 5a0341e2ff549f2de8e307be
Any insight would be greatly appreciated as I'm unable to figure it out.
why console.log is showing the @{product._id} and not the actual id value?

Body:
This style of attribute is no longer supported in pug:

 input(type="hidden", value="#{product._id}" , name="id")

use this instead:

 input(type="hidden", value=product._id , name="id")

More examples in the migration guide here: https://pugjs.org/api/migration-v2.html#attribute-interpolation


问:
Need help with text box input
It's actually a grid column but it functions just like a textbox. I need it to be able to accept numbers only, but it has to be able to accept numbers with leading 0's. What would I use as a mask to get this result? If I do any kind of numeric mask then it will cut off the leading 0's, eg 002456841. If I don't use a numeric mask, then characters will be accepted which is unacceptable.

Am I not thinking outside of the box enough with this? I was also thinking like maybe instead of a mask using a loop or something to make sure it's only numbers and erase/pop up a message if it's not...but I just don't know, I would rather just have the box so it only accepts numbers but any number.

答: I figured it out, I was using a RegEx '\d{1,10}' but it was still not working, I had the data type in the setters and getters as an int which wasn't working, so I set it as string and then parsed/cast it as an int when I needed to use it that way which worked. </p>

Title: Need help with text box input


问:
Install git via homebrew on mac osx 10.10 results in: Error: Permission denied - /usr/local/lib/perl5/site_perl/5.18.2
Hi I just tried installing git via homebrew on my mac - something is wrong. I had the github for mac app installed, but I tried removing that. The current git version in my system is:

```<code>Nielsk@~: $ git --version
git version 1.9.3 (Apple Git-50)
</code>```

This is what happens if I try to install git via homebrew:

```<code>Nielsk@~: $ brew install git
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/git-2.1.3.y
######################################################################## 100,0%
==> Pouring git-2.1.3.yosemite.bottle.tar.gz
==> Caveats
The OS X keychain credential helper has been installed to:
  /usr/local/bin/git-credential-osxkeychain

The 'contrib' directory has been installed to:
  /usr/local/share/git-core/contrib

Bash completion has been installed to:
  /usr/local/etc/bash_completion.d

zsh completion has been installed to:
  /usr/local/share/zsh/site-functions
Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied - /usr/local/lib/perl5/site_perl/5.18.2
Error: Permission denied - /usr/local/lib/perl5/site_perl/5.18.2
</code>```

How can I solve this?

答:
From High Sierra, chown of /usr/local is not allowed. However you can still change permission the sub directories in /usr/local.

In my case, I had to create Frameworks in /usr/local and sudo chown -R $(whom) Frameworks. After that follow what brew doctor says.

The better way is to create subdirectory whatever you need and run

sudo chown -R $(whoami) $(brew --prefix)/*

Body:
Hi I just tried installing git via homebrew on my mac - something is wrong. I had the github for mac app installed, but I tried removing that. The current git version in my system is:

Nielsk@~: $ git --version
git version 1.9.3 (Apple Git-50)

This is what happens if I try to install git via homebrew:

Nielsk@~: $ brew install git
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/git-2.1.3.y
######################################################################## 100,0%
==> Pouring git-2.1.3.yosemite.bottle.tar.gz
==> Caveats
The OS X keychain credential helper has been installed to:
  /usr/local/bin/git-credential-osxkeychain

The 'contrib' directory has been installed to:
  /usr/local/share/git-core/contrib

Bash completion has been installed to:
  /usr/local/etc/bash_completion.d

zsh completion has been installed to:
  /usr/local/share/zsh/site-functions
Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied - /usr/local/lib/perl5/site_perl/5.18.2
Error: Permission denied - /usr/local/lib/perl5/site_perl/5.18.2

How can I solve this?


问:
What is the difference between an expression and a statement?
I know that this might be a duplicate, but I have not found sufficient answers to my examples. In general, what is the difference between statements and expressions? This is a distinction which I have not fully distinguished yet. I know that typically an expressions is supposedly anything that returns a value, such as a literal, or a function. Statements are usually said to be commands to the interpreter, such as "print such and such" or "do . . . while". However, I don't get it.

Wouldn't it make sense to say that print is an expression, since it is a function printing an input (input to output)? Also, people usually say that x = 1 is a statement, but couldn't this be considered an expression where the assignment operator is a function acting on two inputs and the output is that x refers to 1? Finally, couldn't a flow control structure such as if . . . else be considered a three-argument function in which one of the other arguments are returned based upon the truth value of the first input, making it an expression?

I am probably confused because I have a background in LISP, where everything is an expression. It seems that I can't shy away from the thought that most programming constructs are expressions at their core. Thus, could someone explain what really is the difference between a so-called statement and an expression?

答:
The answer is more philosophical than practical. Statements typically have side effects, whereas expressions are generally more algebraic in nature.

In purely functional languages, there are no statements. That is to say that even those things which execute side effects (to a file, for instance) are expressed in terms of values which represent (ideally) all mutations - including failures.

Imperative languages utilize statements to execute arbitrary code, such as assigning a value to a variable, or printing to the console, and potentially communicate failures though exception propagation.

Purely functional expressions merely reduce the cognitive overhead of dealing with mutations by exposing those mutations as values in-and-of-themselves. Mix this with pattern matching, and you are forced to explicitly handle all success and failure scenarios and consequently turn them in to values, explicitly mapping or filtering any failures.

Imperative statements are not required to expose failures as values, and therefore there is always the possibility of arbitrary code existing in an unsuspecting method in such a way that it is easily overlooked. Statements, such as method invocations or variable assignments (x = y = z()), can generally fit the mold of an expression while still executing arbitrary code and failing to communicate failures as values.

In the end, you cannot avoid mutation. You can, however, make it more explicit. This means statements and expressions differ mainly in a philosophical manner, both existing to answer the same question - how should we expose mutations within the context of code execution?


问:
ffmpeg: does 2 step encoding solves issues during video conversion?
I'm encoding several videos to x265 format to save disk storage, and on some of them some errors happen. Like these ones below:

```<code>[h264 @ 0x285f800] error while decoding MB 15 15, bytestream -29ate=3310.7kbits/s
[h264 @ 0x285f800] concealing 2434 DC, 2434 AC, 2434 MV errors in P frame
[matroska,webm @ 0x22205e0] Read error at pos. 1932044330 (0x7328a82a)
[h264 @ 0x27890c0] illegal short term buffer state detected
[h264 @ 0x27890c0] Missing reference picture, default is 65694
[h264 @ 0x27d0880] mmco: unref short failure
[h264 @ 0x27d0880] error while decoding MB 63 29, bytestream -8rate=3230.1kbits/s dup=0 drop=1
[h264 @ 0x27d0880] concealing 1266 DC, 1266 AC, 1266 MV errors in P frame
[matroska,webm @ 0x22205e0] Read error at pos. 2048927876 (0x7a202884)
[h264 @ 0x27304e0] mmco: unref short failureime=00:48:51.54 bitrate=3229.2kbits/s dup=0 drop=1
[h264 @ 0x27890c0] error while decoding MB 28 35, bytestream -16ate=3177.0kbits/s dup=0 drop=1
[h264 @ 0x27890c0] concealing 821 DC, 821 AC, 821 MV errors in P frame
[matroska,webm @ 0x22205e0] Read error at pos. 2112109973 (0x7de43d95)
[h264 @ 0x285f800] mmco: unref short failureime=00:50:36.21 bitrate=3175.5kbits/s dup=0 drop=1
[h264 @ 0x27d0880] error while decoding MB 51 21, bytestream -28ate=3199.4kbits/s dup=0 drop=1
[h264 @ 0x27d0880] concealing 1918 DC, 1918 AC, 1918 MV errors in P frame
[matroska,webm @ 0x22205e0] Read error at pos. 2202555497 (0x83485469)
[matroska,webm @ 0x22205e0] Read error at pos. 2409903171 (0x8fa43443)306.9kbits/s dup=0 drop=1
[h264 @ 0x27d0880] error while decoding MB 3 30, bytestream -7
[h264 @ 0x27d0880] concealing 1246 DC, 1246 AC, 1246 MV errors in P frame
[h264 @ 0x27890c0] error while decoding MB 7 5, bytestream -7bitrate=3396.2kbits/s dup=0 drop=1
[h264 @ 0x27890c0] concealing 3242 DC, 3242 AC, 3242 MV errors in B frame
[matroska,webm @ 0x22205e0] Read error at pos. 2628527465 (0x9cac2569)
[h264 @ 0x285f800] mmco: unref short failuretime=01:02:15.08 bitrate=3396.3kbits/s dup=0 drop=1
[h264 @ 0x2818040] error while decoding MB 36 30, bytestream -12rate=3473.5kbits/s dup=0 drop=1
[h264 @ 0x2818040] concealing 1213 DC, 1213 AC, 1213 MV errors in P frame
[matroska,webm @ 0x22205e0] Read error at pos. 2874947326 (0xab5c36fe)
[h264 @ 0x27890c0] error while decoding MB 46 8, bytestream -6itrate=3590.8kbits/s dup=0 drop=1
[h264 @ 0x27890c0] concealing 2963 DC, 2963 AC, 2963 MV errors in B frame
[matroska,webm @ 0x22205e0] Read error at pos. 3162785874 (0xbc844852)
</code>```

If I add 2-step encoding, that can fix these errors? What exactly does 2-step encoding does? The command I'm using is pretty much the one on this answer https://askubuntu.com/a/718300/396175 so how (which parameter) should I use to apply 2-step encoding?

Thanks!

答:
I'm encoding several videos to x265 format to save disk storage, and on some of them some errors happen.

Looks like decoding errors. The input has something wrong with it so the errors show up when the file is being read. If the input plays fine, or if the output looks ok, then ignore them.

If I add 2-step encoding, that can fix these errors?

No. It's a decoding issue. However, your ffmpeg is old so consider downloading a new one and seeing if it is more robust in its decoding (probably not but you never know).

What exactly does 2-step encoding does?

I see no mention of 2-pass encoding in the link you provided. I assume by "2-step" you are referring to "2-pass", but correct me if I am mistaken. 2-pass encoding generally is used to target a specific output file size. Otherwise, just use a single pass with encoders that offer a constant rate factor such as x264 and x265. See FFmpeg Wiki: H.264 & H.265 for more info on that.

(which parameter) should I use to apply 2-step encoding?

2-pass is initiated by using the -pass option. See the wiki links above for examples. However, you don't need to perform 2-pass encoding. Just use -crf as shown in the link you provided.

Body:
I'm encoding several videos to x265 format to save disk storage, and on some of them some errors happen. Like these ones below:

[h264 @ 0x285f800] error while decoding MB 15 15, bytestream -29ate=3310.7kbits/s
[h264 @ 0x285f800] concealing 2434 DC, 2434 AC, 2434 MV errors in P frame
[matroska,webm @ 0x22205e0] Read error at pos. 1932044330 (0x7328a82a)
[h264 @ 0x27890c0] illegal short term buffer state detected
[h264 @ 0x27890c0] Missing reference picture, default is 65694
[h264 @ 0x27d0880] mmco: unref short failure
[h264 @ 0x27d0880] error while decoding MB 63 29, bytestream -8rate=3230.1kbits/s dup=0 drop=1
[h264 @ 0x27d0880] concealing 1266 DC, 1266 AC, 1266 MV errors in P frame
[matroska,webm @ 0x22205e0] Read error at pos. 2048927876 (0x7a202884)
[h264 @ 0x27304e0] mmco: unref short failureime=00:48:51.54 bitrate=3229.2kbits/s dup=0 drop=1
[h264 @ 0x27890c0] error while decoding MB 28 35, bytestream -16ate=3177.0kbits/s dup=0 drop=1
[h264 @ 0x27890c0] concealing 821 DC, 821 AC, 821 MV errors in P frame
[matroska,webm @ 0x22205e0] Read error at pos. 2112109973 (0x7de43d95)
[h264 @ 0x285f800] mmco: unref short failureime=00:50:36.21 bitrate=3175.5kbits/s dup=0 drop=1
[h264 @ 0x27d0880] error while decoding MB 51 21, bytestream -28ate=3199.4kbits/s dup=0 drop=1
[h264 @ 0x27d0880] concealing 1918 DC, 1918 AC, 1918 MV errors in P frame
[matroska,webm @ 0x22205e0] Read error at pos. 2202555497 (0x83485469)
[matroska,webm @ 0x22205e0] Read error at pos. 2409903171 (0x8fa43443)306.9kbits/s dup=0 drop=1
[h264 @ 0x27d0880] error while decoding MB 3 30, bytestream -7
[h264 @ 0x27d0880] concealing 1246 DC, 1246 AC, 1246 MV errors in P frame
[h264 @ 0x27890c0] error while decoding MB 7 5, bytestream -7bitrate=3396.2kbits/s dup=0 drop=1
[h264 @ 0x27890c0] concealing 3242 DC, 3242 AC, 3242 MV errors in B frame
[matroska,webm @ 0x22205e0] Read error at pos. 2628527465 (0x9cac2569)
[h264 @ 0x285f800] mmco: unref short failuretime=01:02:15.08 bitrate=3396.3kbits/s dup=0 drop=1
[h264 @ 0x2818040] error while decoding MB 36 30, bytestream -12rate=3473.5kbits/s dup=0 drop=1
[h264 @ 0x2818040] concealing 1213 DC, 1213 AC, 1213 MV errors in P frame
[matroska,webm @ 0x22205e0] Read error at pos. 2874947326 (0xab5c36fe)
[h264 @ 0x27890c0] error while decoding MB 46 8, bytestream -6itrate=3590.8kbits/s dup=0 drop=1
[h264 @ 0x27890c0] concealing 2963 DC, 2963 AC, 2963 MV errors in B frame
[matroska,webm @ 0x22205e0] Read error at pos. 3162785874 (0xbc844852)

If I add 2-step encoding, that can fix these errors? What exactly does 2-step encoding does? The command I'm using is pretty much the one on this answer https://askubuntu.com/a/718300/396175 so how (which parameter) should I use to apply 2-step encoding?

Thanks!


问:
What is the Overriding Principle on Naming Conventions in PEP 8?
In the PEP 8 Style Guide for Python Code, the first rule listed under Naming Conventions is the Overriding Principle.

Overriding Principle

Names that are visible to the user as public parts of the API should follow conventions that reflect usage rather than implementation.

The PEP guidelines don't give any additional details or examples, which has left me unsure of what this rule actually means.

What is the Overriding Principle in PEP 8? When would this rule apply?

答: The overriding principle of Python is that you should be able to look at code and know what it does without having to read any other bit of code. Python encourages "Explicit rather than implicit" so well written python code should be obvious. There should not be any implied functionality, and everything should be named in a way that you're not surprised by what it does.</p>


问:
how to handle Edit Post on multiple images Asp.Net MVC
hi every one first time to ask here. So here is my Create post method on multiple images plus other data entries and it works with out any problem and it uploads all images and the content. My question is how to handle edit Post controller on multiple images.

here is the Create controller

```<code>      public ActionResult SaveDataAdded([Bind(Include = "SId,Category,SName,LocalName,CommonName,Description,PicTakenBy,ContentBy,EditedBy")]SpeciesDataTable ARow, HttpPostedFileBase file,HttpPostedFileBase file2, HttpPostedFileBase file3, HttpPostedFileBase file4)
    {if (ModelState.IsValid)

        {

            if (file != null && file.ContentLength > 0)
            {
              using (var Bnryreader = new System.IO.BinaryReader(file.InputStream))
                {
                    ARow.MainPic = Bnryreader.ReadBytes(file.ContentLength);
                }

            }

            if (file2 != null && file2.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file2.InputStream))
                {
                    ARow.SecPic = reader.ReadBytes(file2.ContentLength);
                }

            }
            if (file3 != null && file3.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file3.InputStream))
                {
                    ARow.ThirdPic = reader.ReadBytes(file3.ContentLength);
                }

            }
            if (file4 != null && file4.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file4.InputStream))
                {
                    ARow.FourthPic = reader.ReadBytes(file4.ContentLength);
                }

            }

            db.SpeciesDataTables.Add(ARow);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(ARow);

    }
</code>```

and here is the code block for edit. Probably my approach was not correct. But i need help on this.

```<code>    public ActionResult EditSpeciesPost([Bind(Include = "SId,Category,SName,LocalName,CommonName,Description,PicTakenBy,ContentBy,EditedBy")]SpeciesDataTable Editor, HttpPostedFileBase file, HttpPostedFileBase file2, HttpPostedFileBase file3, HttpPostedFileBase file4)
    {

            if (file != null && file.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file.InputStream))
                {
                    Editor.MainPic = reader.ReadBytes(file.ContentLength);
                }

            }

            if (file2 != null && file2.ContentLength > 0)
            {

                using (var reader = new System.IO.BinaryReader(file2.InputStream))
                {
                    Editor.SecPic = reader.ReadBytes(file2.ContentLength);
                }

            }

            if (file3 != null && file3.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file3.InputStream))
                {
                    Editor.ThirdPic = reader.ReadBytes(file3.ContentLength);
                }

            }
            if (file4 != null && file4.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file4.InputStream))
                {
                    Editor.FourthPic = reader.ReadBytes(file4.ContentLength);
                }

            }

        db.Entry(Editor).State = EntityState.Modified;
        db.SaveChanges();

          //return RedirectToAction("Index");

           return View(Editor);

    }
</code>```

here is the view for edit

@using(Html.BeginForm("EditSpecies", "Species", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
@Html.AntiForgeryToken()

            @if (Model.MainPic != null) // to view first image
            {
                var base64 = Convert.ToBase64String(Model.MainPic);
                var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);

            }

            <input type="file" name="file" />  // input for first image

            @if (Model.SecPic != null)// to view second image
            {
                var base64 = Convert.ToBase64String(Model.SecPic);
                var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);

            }

            <input type="file" name="file2" /> input for third image

// and it continues to third and fourth picture
}```

答:
What you should be doing is, sending only null for the images user has not updated in the UI and post the data to the httppost action method where you read the existing entity and update only those properties needed to update.

I would create a view model for my view with properties needed for the view.

```<code>public class SpeciesVm
{
    public int Id { set; get; }
    public string Name { set; get; }
    public string LocalName { set; get; }

    public HttpPostedFileBase MainImg { set; get; }
    public HttpPostedFileBase SecondImg { set; get; }
    public string MainPicImgSrc { set; get; }
    public string SecondPicImgSrc { set; get; }
}
</code>```

Now in your GET action, you create an object of this, load the property values.

```<code>public ActionResult Edit(int id)
{
   var e=db.SpeciesDataTables.Find(id);
   var vm = new SpeciesVm() { Id=id , Name =e.SName };
   vm.LocalName= e.LocalName;

   if(e.MainPic!=null)
   {
     vm.MainPicImgSrc = $"data:image/jpg;base64,{Convert.ToBase64String(e.MainPic)}";
   }
   if(e.SecPic!=null)
   {
     vm.SecondPicImgSrc = $"data:image/jpg;base64,{Convert.ToBase64String(e.SecPic)}";
   }
   return View(vm);
}
</code>```

Now in your view, you will use the properties of type HttpPostedFileBase for the file input

```<code>@model SpeciesVm
@using (Html.BeginForm("Edit","Species", FormMethod.Post,
                                         new { enctype = "multipart/form-data" }))
{
  @Html.HiddenFor(a=>a.Id)
  @Html.HiddenFor(a=>a.Name)
  @Html.HiddenFor(a=>a.LocalName)

  <div class="col-md-10">
    @if (!string.IsNullOrEmpty(Model.MainPicImgSrc))
    {
      <img src='@Model.MainPicImgSrc'  />
    }
    <input type="file" name="MainImg" />
  </div>
  <div class="col-md-10">
    @if (!string.IsNullOrEmpty(Model.SecondPicImgSrc))
    {
      <img src='@Model.SecondPicImgSrc'  />
    }
    <input type="file" name="SecondImg" />
  </div>
  <button type="submit">Save</button>
}
</code>```

Now in your HttpPost action method, you will use the same view model as the parameter, read the Id property value, using which read existing entity and update the properties as needed.

```<code>[HttpPost]
public ActionResult Edit(SpeciesVm model)
{
   var e=db.SpeciesDataTables.Find(id);
   e.SName = model.Name;
   //Update the image properties only if it was send from the form
   if(model.MainImg!=null)
   {
      e.MainPic = GetByteArrayFromImage(model.MainImg);
   }
   if(model.MainImg!=null)
   {
      e.SecPic = GetByteArrayFromImage(model.SecondImg);
   }
   db.SaveChanges();
   return RedirectToAction("Index");
}
private byte[] GetByteArrayFromImage(HttpPostedFileBase file)
{
    if (file == null)
        return null;
    var target = new MemoryStream();
    file.InputStream.CopyTo(target);
    return  target.ToArray();
}
</code>```

Body:
hi every one first time to ask here. So here is my Create post method on multiple images plus other data entries and it works with out any problem and it uploads all images and the content. My question is how to handle edit Post controller on multiple images.

here is the Create controller

      public ActionResult SaveDataAdded([Bind(Include = "SId,Category,SName,LocalName,CommonName,Description,PicTakenBy,ContentBy,EditedBy")]SpeciesDataTable ARow, HttpPostedFileBase file,HttpPostedFileBase file2, HttpPostedFileBase file3, HttpPostedFileBase file4)
    {if (ModelState.IsValid)

        {

            if (file != null && file.ContentLength > 0)
            {
              using (var Bnryreader = new System.IO.BinaryReader(file.InputStream))
                {
                    ARow.MainPic = Bnryreader.ReadBytes(file.ContentLength);
                }

            }

            if (file2 != null && file2.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file2.InputStream))
                {
                    ARow.SecPic = reader.ReadBytes(file2.ContentLength);
                }

            }
            if (file3 != null && file3.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file3.InputStream))
                {
                    ARow.ThirdPic = reader.ReadBytes(file3.ContentLength);
                }

            }
            if (file4 != null && file4.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file4.InputStream))
                {
                    ARow.FourthPic = reader.ReadBytes(file4.ContentLength);
                }

            }

            db.SpeciesDataTables.Add(ARow);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(ARow);

    }

and here is the code block for edit. Probably my approach was not correct. But i need help on this.

    public ActionResult EditSpeciesPost([Bind(Include = "SId,Category,SName,LocalName,CommonName,Description,PicTakenBy,ContentBy,EditedBy")]SpeciesDataTable Editor, HttpPostedFileBase file, HttpPostedFileBase file2, HttpPostedFileBase file3, HttpPostedFileBase file4)
    {

            if (file != null && file.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file.InputStream))
                {
                    Editor.MainPic = reader.ReadBytes(file.ContentLength);
                }

            }

            if (file2 != null && file2.ContentLength > 0)
            {

                using (var reader = new System.IO.BinaryReader(file2.InputStream))
                {
                    Editor.SecPic = reader.ReadBytes(file2.ContentLength);
                }

            }

            if (file3 != null && file3.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file3.InputStream))
                {
                    Editor.ThirdPic = reader.ReadBytes(file3.ContentLength);
                }

            }
            if (file4 != null && file4.ContentLength > 0)
            {
                using (var reader = new System.IO.BinaryReader(file4.InputStream))
                {
                    Editor.FourthPic = reader.ReadBytes(file4.ContentLength);
                }

            }

        db.Entry(Editor).State = EntityState.Modified;
        db.SaveChanges();

          //return RedirectToAction("Index");

           return View(Editor);

    }

here is the view for edit

@using(Html.BeginForm("EditSpecies", "Species", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
@Html.AntiForgeryToken()

            @if (Model.MainPic != null) // to view first image
            {
                var base64 = Convert.ToBase64String(Model.MainPic);
                var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);

            }

            <input type="file" name="file" />  // input for first image

            @if (Model.SecPic != null)// to view second image
            {
                var base64 = Convert.ToBase64String(Model.SecPic);
                var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);

            }

            <input type="file" name="file2" /> input for third image

// and it continues to third and fourth picture
}

Body:
What you should be doing is, sending only null for the images user has not updated in the UI and post the data to the httppost action method where you read the existing entity and update only those properties needed to update.

I would create a view model for my view with properties needed for the view.

public class SpeciesVm
{
    public int Id { set; get; }
    public string Name { set; get; }
    public string LocalName { set; get; }

    public HttpPostedFileBase MainImg { set; get; }
    public HttpPostedFileBase SecondImg { set; get; }
    public string MainPicImgSrc { set; get; }
    public string SecondPicImgSrc { set; get; }
}

Now in your GET action, you create an object of this, load the property values.

public ActionResult Edit(int id)
{
   var e=db.SpeciesDataTables.Find(id);
   var vm = new SpeciesVm() { Id=id , Name =e.SName };
   vm.LocalName= e.LocalName;

   if(e.MainPic!=null)
   {
     vm.MainPicImgSrc = $"data:image/jpg;base64,{Convert.ToBase64String(e.MainPic)}";
   }
   if(e.SecPic!=null)
   {
     vm.SecondPicImgSrc = $"data:image/jpg;base64,{Convert.ToBase64String(e.SecPic)}";
   }
   return View(vm);
}

Now in your view, you will use the properties of type HttpPostedFileBase for the file input

@model SpeciesVm
@using (Html.BeginForm("Edit","Species", FormMethod.Post,
                                         new { enctype = "multipart/form-data" }))
{
  @Html.HiddenFor(a=>a.Id)
  @Html.HiddenFor(a=>a.Name)
  @Html.HiddenFor(a=>a.LocalName)

  <div class="col-md-10">
    @if (!string.IsNullOrEmpty(Model.MainPicImgSrc))
    {
      <img src='@Model.MainPicImgSrc'  />
    }
    <input type="file" name="MainImg" />
  </div>
  <div class="col-md-10">
    @if (!string.IsNullOrEmpty(Model.SecondPicImgSrc))
    {
      <img src='@Model.SecondPicImgSrc'  />
    }
    <input type="file" name="SecondImg" />
  </div>
  <button type="submit">Save</button>
}

Now in your HttpPost action method, you will use the same view model as the parameter, read the Id property value, using which read existing entity and update the properties as needed.

[HttpPost]
public ActionResult Edit(SpeciesVm model)
{
   var e=db.SpeciesDataTables.Find(id);
   e.SName = model.Name;
   //Update the image properties only if it was send from the form
   if(model.MainImg!=null)
   {
      e.MainPic = GetByteArrayFromImage(model.MainImg);
   }
   if(model.MainImg!=null)
   {
      e.SecPic = GetByteArrayFromImage(model.SecondImg);
   }
   db.SaveChanges();
   return RedirectToAction("Index");
}
private byte[] GetByteArrayFromImage(HttpPostedFileBase file)
{
    if (file == null)
        return null;
    var target = new MemoryStream();
    file.InputStream.CopyTo(target);
    return  target.ToArray();
}