问:
Using Asp.Net Core dependency injection to inject classes to other projects
I have an ASP.Net Core project responsible for handling all web requests, and I have another project responsible for reading/writing from and into the database (Entity framework Core project).
and of course another projects for different things but let's now imagine just we have only the previous two projects for the simplicity.

Is it possible some how to use ASP.Net Core dependency injection to inject classes into another projects (other projects which are library classes and not ASP.Net Core projects)? for example injecting DbContext to my Entity framework project?

答:
It may be that what you are thinking of doing is futile? If you are running inside an Asp.Net application, then all your code is probably called from a Controller, and the Controller can get all the dependencies you need, and pass them through:

```<code>public class MyController : Controller
{
    readonly MyComponent myComponent;

    public MyController(MyDbContext dbctx)
    {
        myComponent= new MyComponent(dbctx);
    }
    // ...etc...
}
</code>```

But is one of your other projects a ConsoleApp or Service that runs outside the Asp.Net application? Then the question is, can I reference Asp.Net.Core to use DI outside of Asp.Net?

I suspect the answer is 'probably-yes', and your starting point would be to copy MS's builder code on github.

But that would beg the question, of why choose the Asp.Net DI over all the existing DI containers out there? Castle.Windsor, AutoFac, StructureMap, Ninject have all done the job well for years.

Body:
It may be that what you are thinking of doing is futile? If you are running inside an Asp.Net application, then all your code is probably called from a Controller, and the Controller can get all the dependencies you need, and pass them through:

public class MyController : Controller
{
    readonly MyComponent myComponent;

    public MyController(MyDbContext dbctx)
    {
        myComponent= new MyComponent(dbctx);
    }
    // ...etc...
}

But is one of your other projects a ConsoleApp or Service that runs outside the Asp.Net application? Then the question is, can I reference Asp.Net.Core to use DI outside of Asp.Net?

I suspect the answer is 'probably-yes', and your starting point would be to copy MS's builder code on github.

But that would beg the question, of why choose the Asp.Net DI over all the existing DI containers out there? Castle.Windsor, AutoFac, StructureMap, Ninject have all done the job well for years.


来源: stackexchange

问:
should I do with docker-compose? when I have 2 project
I'm having 2 project

A {mysql, redis, rails}
B {mysql, redis, rails}

should I do

create a docker-compose.yml file with a MySql, a redis, rails1, rails2
or

create 2 docker-compose.yml file with each is a Mysql, a Redis, rails

help me!

答:
You could create a docker-compose.yml file with your common services. And then create two project specific composer files which inherits the root composer file.

docker-compose.project.template.yml

```<code>services:
  mysql:
    ....
</code>```

docker.compose.project.a.yml

```<code>services:
  mysql:
    extends:
      file: docker-compose.project.template.yml
      service: mysql
    ...
</code>```

Another option is to create a general project docker-compose.yml file and use environment variables to customize the behaviour.

ContentLicense: CC BY-SA 3.0

Body:
You could create a docker-compose.yml file with your common services. And then create two project specific composer files which inherits the root composer file.

docker-compose.project.template.yml

services:
  mysql:
    ....

docker.compose.project.a.yml

services:
  mysql:
    extends:
      file: docker-compose.project.template.yml
      service: mysql
    ...

Another option is to create a general project docker-compose.yml file and use environment variables to customize the behaviour.


问:
Dynamics Ax: Alert when any record changes
I want to send an alert in Ax, when any field in the vendor table changes (and on create/delete of a record).

In the alert, I would like to include the previous and current value.

But, it appears that you can't set alerts for when any field in a table changes, but need to set one up for EVERY FIELD?!  I hope I am mistaken.

And how can I send this notification to a group of people

答:
As you have observed the alert system is not designed for "any" field changes, only specific field changes.

This is a bogus request anyway as it would generate many alarts. The right thing to do is to enable database logging of the VendTable table, then send a daily report (in batch) to those interested.

This is done in Administration\Setup\Database logging. There is a report in Administration\Reports. You will need to know the table number to select the table.
This solution requires a "Database logging" license key.

ContentLicense: CC BY-SA 2.5


问:
laravel 5.4 upload image
My controller code for upload file in laravel 5.4:

```<code>if ($request->hasFile('input_img')) {
    if($request->file('input_img')->isValid()) {
        try {
            $file = $request->file('input_img');
            $name = rand(11111, 99999) . '.' . $file->getClientOriginalExtension();
            $request->file('input_img')->move("fotoupload", $name);
        } catch (Illuminate\Filesystem\FileNotFoundException $e) {

        }
    }
}
</code>```

Image was successfully uploaded but the code threw an exception :

FileNotFoundException in MimeTypeGuesser.php line 123

The file is there any fault in my code or is it a bug  in laravel 5.4, can anyone help me solve the problem ?

My view code:

```<code><form enctype="multipart/form-data" method="post" action="{{url('admin/post/insert')}}">
    {{ csrf_field() }}
    <div class="form-group">
        <label for="imageInput">File input</label>
        <input data-preview="#preview" name="input_img" type="file" id="imageInput">
        <img class="col-sm-6" id="preview"  src="">
        <p class="help-block">Example block-level help text here.</p>
    </div>
    <div class="form-group">
        <label for="">submit</label>
        <input class="form-control" type="submit">
    </div>
</form>
</code>```

答: In Laravel 5.4, you can use guessClientExtension

ContentLicense: CC BY-SA 4.0

Title: laravel 5.4 upload image

Body:
My controller code for upload file in laravel 5.4:

if ($request->hasFile('input_img')) {
    if($request->file('input_img')->isValid()) {
        try {
            $file = $request->file('input_img');
            $name = rand(11111, 99999) . '.' . $file->getClientOriginalExtension();
            $request->file('input_img')->move("fotoupload", $name);
        } catch (Illuminate\Filesystem\FileNotFoundException $e) {

        }
    }
}

Image was successfully uploaded but the code threw an exception :

FileNotFoundException in MimeTypeGuesser.php line 123

The file is there any fault in my code or is it a bug  in laravel 5.4, can anyone help me solve the problem ?

My view code:

<form enctype="multipart/form-data" method="post" action="{{url('admin/post/insert')}}">
    {{ csrf_field() }}

        File input
        <input data-preview="#preview" name="input_img" type="file" id="imageInput">

Example block-level help text here.

        submit
        <input class="form-control" type="submit">

</form>


问:
Problems with PHP contact form
I have a problem with my contact form that I have created. When the user clicks on the send email button, I receive the email with a header, but I can't see the user's input.

So basically I am able to see the header($subject) and the pre written text("This is an automated message"), but I am not able to see the contents of $email and $message. What could be wrong?

```<code><?php

$email = $_POST['email'];
$message = $_POST['message'];

$to = "test@testemail.com";
$subject = "New Message!"; $body = "This is an automated message. Please do not reply to this email. \n\n $email \n\n $message";

mail($to, $subject, $body); echo "Message Sent.";
?>

<form id="contact-me-form" action="contact.php" name="contact_form "method="post">
    <input type="text" name="email" placeholder="Email Address">
    <textarea name="message" placeholder="Type Your Message Here"></textarea>
    <input id="sendEmail" type="submit" name="submit" value="Send">
</form>
</code>```

答:
you need to check whether you have post parameters then send the email

change your code to

```<code>     <?php
    if(isset($_POST['email']) && isset($_POST['message'])){
        $email = $_POST['email'];
        $message = $_POST['message'];

        $to = "test@testemail.com";
        $subject = "New Message!"; $body = "This is an automated message. Please do not reply to this email. \n\n $email \n\n $message";

        mail($to, $subject, $body); echo "Message Sent.";
    }
    ?>

    <form id="contact-me-form" action="contact.php" name="contact_form "method="post">
        <input type="text" name="email" placeholder="Email Address">
        <textarea name="message" placeholder="Type Your Message Here"></textarea>
        <input id="sendEmail" type="submit" name="submit" value="Send">
    </form>
</code>```

Title: Problems with PHP contact form

Body:
I have a problem with my contact form that I have created. When the user clicks on the send email button, I receive the email with a header, but I can't see the user's input.

So basically I am able to see the header($subject) and the pre written text("This is an automated message"), but I am not able to see the contents of $email and $message. What could be wrong?

<?php

$email = $_POST['email'];
$message = $_POST['message'];

$to = "test@testemail.com";
$subject = "New Message!"; $body = "This is an automated message. Please do not reply to this email. \n\n $email \n\n $message";

mail($to, $subject, $body); echo "Message Sent.";
?>

<form id="contact-me-form" action="contact.php" name="contact_form "method="post">
    <input type="text" name="email" placeholder="Email Address">
    <textarea name="message" placeholder="Type Your Message Here"></textarea>
    <input id="sendEmail" type="submit" name="submit" value="Send">
</form>

Body:
you need to check whether you have post parameters then send the email

change your code to

     <?php
    if(isset($_POST['email']) && isset($_POST['message'])){
        $email = $_POST['email'];
        $message = $_POST['message'];

        $to = "test@testemail.com";
        $subject = "New Message!"; $body = "This is an automated message. Please do not reply to this email. \n\n $email \n\n $message";

        mail($to, $subject, $body); echo "Message Sent.";
    }
    ?>

    <form id="contact-me-form" action="contact.php" name="contact_form "method="post">
        <input type="text" name="email" placeholder="Email Address">
        <textarea name="message" placeholder="Type Your Message Here"></textarea>
        <input id="sendEmail" type="submit" name="submit" value="Send">
    </form>


问:
SQL Server where clause order count > 0
I have a query that works but returns all students, whether they place orders or not.  I just want those with orders.  The query works fine until I add the where clause.  How can I properly write this?</p>

```<code>SELECT top 100 percent s.id, s.fname as [First Name], s.lname as [Last Name],
(select count(student_id) from orderX x where x.student_id=s.id) as [Order Count],
(select sum(no_attendees) from orderX x where x.student_id=s.id) as [Attendees / Participants],
(select sum(eventHours) from orderX x where x.student_id=s.id) as [Event Hours],
oc1.text as [Occupation 1], oc2.text as [Occupation 2],
oc3.text as [Occupation 3], s.OccupationOther, s.dateGraduated, s.organization, s.city, s.zip, s.st, s.county,
aud.text as [Preferred Audience], pts.text as [Plans to Share], mr.text as [Main Reason]
FROM  student s
left join occupation1 oc1 on s.Occupation1 = oc1.id
left  join occupation2 oc2 on s.Occupation2 = oc2.id
left  join occupation3 oc3 on s.Occupation3 = oc3.id
left  join audience aud on s.audience = aud.id
left  join PlanToShare pts on s.PlanToShare = pts.id
left  join mainReason mr on s.mainReason = mr.id

where [Order Count] > 0
</code>```

答:
You cannot use a column alias ([Order count]) in the WHERE clause. Either repeat the

```<code>(select count(student_id) from orderX x where x.student_id=s.id)
</code>```

in the WHERE clause as

```<code>WHERE (select count(student_id) from orderX x where x.student_id=s.id) > 0
</code>```

or use a cte.

Title: SQL Server where clause order count > 0

Body:
I have a query that works but returns all students, whether they place orders or not.  I just want those with orders.  The query works fine until I add the where clause.  How can I properly write this?

SELECT top 100 percent s.id, s.fname as [First Name], s.lname as [Last Name],
(select count(student_id) from orderX x where x.student_id=s.id) as [Order Count],
(select sum(no_attendees) from orderX x where x.student_id=s.id) as [Attendees / Participants],
(select sum(eventHours) from orderX x where x.student_id=s.id) as [Event Hours],
oc1.text as [Occupation 1], oc2.text as [Occupation 2],
oc3.text as [Occupation 3], s.OccupationOther, s.dateGraduated, s.organization, s.city, s.zip, s.st, s.county,
aud.text as [Preferred Audience], pts.text as [Plans to Share], mr.text as [Main Reason]
FROM  student s
left join occupation1 oc1 on s.Occupation1 = oc1.id
left  join occupation2 oc2 on s.Occupation2 = oc2.id
left  join occupation3 oc3 on s.Occupation3 = oc3.id
left  join audience aud on s.audience = aud.id
left  join PlanToShare pts on s.PlanToShare = pts.id
left  join mainReason mr on s.mainReason = mr.id

where [Order Count] > 0

Body:
You cannot use a column alias ([Order count]) in the WHERE clause. Either repeat the

(select count(student_id) from orderX x where x.student_id=s.id)

in the WHERE clause as

WHERE (select count(student_id) from orderX x where x.student_id=s.id) > 0

or use a cte.


答:
I think no correlation needed here. Find all the aggregates in subquery and "inner" join it (inner because you are anyways going to filter out zero count rows)</p>

```<code>select top 100 percent s.id,
    s.fname as [First Name],
    s.lname as [Last Name],
    x.order_count as [Order Count],
    x.attendess_participants as [Attendees / Participants],
    x.eventHours as [Event Hours],
    oc1.text as [Occupation 1],
    oc2.text as [Occupation 2],
    oc3.text as [Occupation 3],
    s.OccupationOther,
    s.dateGraduated,
    s.organization,
    s.city,
    s.zip,
    s.st,
    s.county,
    aud.text as [Preferred Audience],
    pts.text as [Plans to Share],
    mr.text as [Main Reason]
from student s
left join occupation1 oc1 on s.Occupation1 = oc1.id
left join occupation1 oc2 on s.Occupation2 = oc2.id
left join occupation1 oc3 on s.Occupation3 = oc3.id
left join audience aud on s.audience = aud.id
left join PlanToShare pts on s.PlanToShare = pts.id
left join mainReason mr on s.mainReason = mr.id
inner join (
    select student_id,
        count(*) as order_count,
        sum(no_attendees) as attendess_participants,
        sum(eventHours) as event_hours
    from orderX x
    group by student_id
    ) x on x.student_id = s.id;
</code>```

Title: SQL Server where clause order count > 0

Body:
I think no correlation needed here. Find all the aggregates in subquery and "inner" join it (inner because you are anyways going to filter out zero count rows)

select top 100 percent s.id,
    s.fname as [First Name],
    s.lname as [Last Name],
    x.order_count as [Order Count],
    x.attendess_participants as [Attendees / Participants],
    x.eventHours as [Event Hours],
    oc1.text as [Occupation 1],
    oc2.text as [Occupation 2],
    oc3.text as [Occupation 3],
    s.OccupationOther,
    s.dateGraduated,
    s.organization,
    s.city,
    s.zip,
    s.st,
    s.county,
    aud.text as [Preferred Audience],
    pts.text as [Plans to Share],
    mr.text as [Main Reason]
from student s
left join occupation1 oc1 on s.Occupation1 = oc1.id
left join occupation1 oc2 on s.Occupation2 = oc2.id
left join occupation1 oc3 on s.Occupation3 = oc3.id
left join audience aud on s.audience = aud.id
left join PlanToShare pts on s.PlanToShare = pts.id
left join mainReason mr on s.mainReason = mr.id
inner join (
    select student_id,
        count(*) as order_count,
        sum(no_attendees) as attendess_participants,
        sum(eventHours) as event_hours
    from orderX x
    group by student_id
    ) x on x.student_id = s.id;


问:
Nacha Addenda Record
I am writing some software for generating Nacha files. It's mostly done and working fine. However, one of our clients asked us for an Addenda record (CCD Addenda Record). I am happy to add this, it should be easy but the spec doesn't appear to indicate how the Detail Record (type 6) and the Addenda Record (type 7) are linked. I can't believe its just positional.
I see a "Entry detail Sequence Number" field on the Addenda record but I don't see a matching number in the Detail Record. There isn't even anything with the same field length. Do any of you know the answer to this?
TIA</p>

答:
your belief is wrong. it is positional.
Addenda records supply description to their preceding entry.</p>

Title: Nacha Addenda Record


问:
How to extract images from pdf using Java (not using pdfbox)
I've being researching on how to extract images from a big (> 300MB) PDF file. I'm using pdfbox but for some particular reason that I can't figure out, some pages are not correctly extracted.

I'm using the PDFToImage class of pdfbox as base for my code.

So, do you know another library that may help me to do this? I know that iText may be used, but I read that it can't be used for commercial products.

I've installed the packages xpdf and xpdf-utils, and the utility called pdfimages is working perfect. But I need to solve this problem from Java and it should be portable.

答:
I think you're talking about two different things here: extracting images from a PDF, and converting PDF pages to images.  PDFToImage will output an image for every page, while pdfimages extracts all embedded images (e.g. a text document has 0 images).

Take a look at org.apache.pdfbox.tools.ExtractImages (source code) to see if it does what you want.


问:
Config variable not being fetched as expected from application.yml
I have config variable(in application.yml) as:

```<code>xyz:
exception.emails: ['abc@gmail.com']
</code>```

While fetching this in local works fine but after deploying war I am getting config variable as:

```<code>xyz: [
    exception: [
        emails[
            0
        ]: abc@gmail.com
    ]
]
</code>```

I am pulling this as:

```<code>def email = Holders.config.grails.xyz.exception.emails
</code>```

答:
I'm actually surprised this work at all, because I don't think that is proper yml syntax looking at the default application.yml they specify a list of userAgents like this:

```<code>grails:
    mime:
        disable:
            accept:
                header:
                    userAgents:
                        - Gecko
                        - WebKit
                        - Presto
                        - Trident
</code>```

Personally I like to use an application.groovy and use groovy syntax like this:

```<code>grails {
    mime {
        disable {
            accept {
                header {
                    userAgents:
                    ['Gecko', 'WebKit', 'Presto', 'Trident']
                }
            }
        }
</code>```

It maybe a little out of date but here is an example of a application.yml converted to application.groovy:
https://github.com/virtualdogbert/Grails3Tutorial/blob/step_01_settings_yml_to_groovy/grails-app/conf/application.groovy

Also note in the past you could run code from application.groovy, however if you have any imports they won't work,because application.yml/groovy, is meant for the cli(pre runtime), so as a workaround you can also specify a runtime.groovy, where you can have imports. If you ever go the extra mile and write a plugin, you can specify a plugin.groovy, to set defaults.

Body:
I have config variable(in application.yml) as:

xyz:
exception.emails: ['abc@gmail.com']

While fetching this in local works fine but after deploying war I am getting config variable as:

xyz: [
    exception: [
        emails[
            0
        ]: abc@gmail.com
    ]
]

I am pulling this as:

def email = Holders.config.grails.xyz.exception.emails

Body:
I'm actually surprised this work at all, because I don't think that is proper yml syntax looking at the default application.yml they specify a list of userAgents like this:

grails:
    mime:
        disable:
            accept:
                header:
                    userAgents:
                        - Gecko
                        - WebKit
                        - Presto
                        - Trident

Personally I like to use an application.groovy and use groovy syntax like this:

grails {
    mime {
        disable {
            accept {
                header {
                    userAgents:
                    ['Gecko', 'WebKit', 'Presto', 'Trident']
                }
            }
        }

It maybe a little out of date but here is an example of a application.yml converted to application.groovy:
https://github.com/virtualdogbert/Grails3Tutorial/blob/step_01_settings_yml_to_groovy/grails-app/conf/application.groovy

Also note in the past you could run code from application.groovy, however if you have any imports they won't work,because application.yml/groovy, is meant for the cli(pre runtime), so as a workaround you can also specify a runtime.groovy, where you can have imports. If you ever go the extra mile and write a plugin, you can specify a plugin.groovy, to set defaults.


问:
JavaScript: Check whether variable exists with name given by other variable
I know how to check whether a variable in Javascript exists or not. I can simply use

if (variable == null) { // do something }

to check that it does not exist. Or similarly

if (typeof variable == 'undefined') {
      // do something }

But I'm in a slightly different situation: I have a variable named 'myVariable' which takes a string as value.

Question: How can I check whether a variable exists with a name equal to the value of myVariable?

Example: If we have

var myVariable = 'car';

how can I check whether a variable exists / is defined with the name 'car'? (Of course in practice we don't know the value of myVariable). I need something like

if (typeof value of myVariable == 'undefined') { // do something}

Thank you very much in advance for any help!

答:
You can check for null, NaN etc like:

```<code>if(myVariable) {
    doSomething()
} else {
    doSomething()
}
</code>```

it means, will be false if value is null, undefined, NaN, empty string(""), 0, false

You can save 90% time

Body:
You can check for null, NaN etc like:

if(myVariable) {
    doSomething()
} else {
    doSomething()
}

it means, will be false if value is null, undefined, NaN, empty string(""), 0, false

You can save 90% time


问:
How to read and parse a line from file?
There is a file consisted of lines in the following format:

```<code>John, D E       100
Bob, F I        200
Oli, G H       1500
...
</code>```

in general:

string, char char integer

The file needs to be read and stored in two arrays of which the first should store the string and characters1 and the second should store the integer.

How could this be done?

An initial attempt is made here.

1. Concatenated into single string as they are with the comma and the white spaces.

答:
If the items in the input file are delimited by whitespaces or commas, we can read them using list-directed input (fmt=*), as suggested in the comments in the linked question, such that

```<code>read (funit, [fmt =] *, iostat = ios) surname, first_name, second_name, consumption
</code>```

where the part "fmt =" is optional. The following is a slightly modified version of the original code in the linked page (please see comments in the code for more details):

```<code>module MyModule
    implicit none  !<-- this propagates to all routines in this module
contains

subroutine ReadFileIntoArrays (filename, name_arr, kWh_arr, ndata)

    character(*), intent(in) :: filename     !<-- an assumed-length string
    character(*), intent(out) :: name_arr(:) !<-- an array of assumed-length strings
    integer, intent(out) :: kWh_arr(:), ndata

    character :: first_name, second_name  !<-- a single char
    character(50) :: surname              !<-- a string of 50 chars
    integer :: consumption, funit, ios, idx

    funit = 10  ! use >= 10 (or open( newunit=funit, ... ) for recent compilers)
    open (funit, file = filename, status = 'old')

    idx = 0
    do
        read (funit, fmt = *, iostat = ios) &   !<-- "&" means line continuation
                surname, first_name, second_name, consumption

        ! "fmt = *" (list-directed input) tells the compiler
        ! to use whitespaces/commas as delimiters.

        if (ios > 0) then
            print *, "Wrong input format!" ; exit
        else if (ios < 0) then
            print *, "finished reading data." ; exit
        else
            idx = idx + 1
            if (idx > size( name_arr )) stop "size of name_arr(:) too small"

            ! trim() chops trailing spaces in a string
            name_arr( idx ) = trim(surname)//','//first_name//'.'//second_name//'.'
            kWh_arr( idx ) = consumption
        end if
    end do
    ndata = idx

    close (funit)
end subroutine

end module

program MyMain
    use MyModule
    implicit none
    integer :: consumption( 10 ), ndata, idx
    character(50) :: names( 10 )  !<-- an array of size 10 (each element = 50-char string)
    character(200) :: filename    !<-- a string of 200 chars

    filename = "clients.txt"
    names = ""
    consumption = 0

    call ReadFileIntoArrays (filename, names, consumption, ndata)

    print "(2a20)", "name", "consumption"
    do idx = 1, ndata
        print "(a20,i20)", trim( names( idx ) ), consumption( idx )
    enddo
end program
</code>```

Then, with the input in the question, the output becomes

```<code> finished reading data.
                name         consumption
           John,D.E.                 100
            Bob,F.I.                 200
            Oli,G.H.                1500
</code>```

Title: How to read and parse a line from file?

Body:
There is a file consisted of lines in the following format:

John, D E       100
Bob, F I        200
Oli, G H       1500
...

in general:

string, char char integer

The file needs to be read and stored in two arrays of which the first should store the string and characters1 and the second should store the integer.

How could this be done?

An initial attempt is made here.

1. Concatenated into single string as they are with the comma and the white spaces.

Body:
If the items in the input file are delimited by whitespaces or commas, we can read them using list-directed input (fmt=*), as suggested in the comments in the linked question, such that

read (funit, [fmt =] *, iostat = ios) surname, first_name, second_name, consumption

where the part "fmt =" is optional. The following is a slightly modified version of the original code in the linked page (please see comments in the code for more details):

module MyModule
    implicit none  !<-- this propagates to all routines in this module
contains

subroutine ReadFileIntoArrays (filename, name_arr, kWh_arr, ndata)

    character(*), intent(in) :: filename     !<-- an assumed-length string
    character(*), intent(out) :: name_arr(:) !<-- an array of assumed-length strings
    integer, intent(out) :: kWh_arr(:), ndata

    character :: first_name, second_name  !<-- a single char
    character(50) :: surname              !<-- a string of 50 chars
    integer :: consumption, funit, ios, idx

    funit = 10  ! use >= 10 (or open( newunit=funit, ... ) for recent compilers)
    open (funit, file = filename, status = 'old')

    idx = 0
    do
        read (funit, fmt = *, iostat = ios) &   !<-- "&" means line continuation
                surname, first_name, second_name, consumption

        ! "fmt = *" (list-directed input) tells the compiler
        ! to use whitespaces/commas as delimiters.

        if (ios > 0) then
            print *, "Wrong input format!" ; exit
        else if (ios < 0) then
            print *, "finished reading data." ; exit
        else
            idx = idx + 1
            if (idx > size( name_arr )) stop "size of name_arr(:) too small"

            ! trim() chops trailing spaces in a string
            name_arr( idx ) = trim(surname)//','//first_name//'.'//second_name//'.'
            kWh_arr( idx ) = consumption
        end if
    end do
    ndata = idx

    close (funit)
end subroutine

end module

program MyMain
    use MyModule
    implicit none
    integer :: consumption( 10 ), ndata, idx
    character(50) :: names( 10 )  !<-- an array of size 10 (each element = 50-char string)
    character(200) :: filename    !<-- a string of 200 chars

    filename = "clients.txt"
    names = ""
    consumption = 0

    call ReadFileIntoArrays (filename, names, consumption, ndata)

    print "(2a20)", "name", "consumption"
    do idx = 1, ndata
        print "(a20,i20)", trim( names( idx ) ), consumption( idx )
    enddo
end program

Then, with the input in the question, the output becomes

 finished reading data.
                name         consumption
           John,D.E.                 100
            Bob,F.I.                 200
            Oli,G.H.                1500


答:
Try like this

```<code><?php

$email = $_POST['email'];
$message = $_POST['message'];

$to = "test@testemail.com";
$subject = "New Message!"; $body = "This is an automated message. Please do not reply to this email. \n\n $email \n\n $message";
$body= $_POST["message"]
if ($_SERVER["REQUEST_METHOD"] == "POST") {
mail($to, $subject, $body); echo "Message Sent.";

}
?>

<form id="contact-me-form" action="contact.php" name="contact_form "method="post">
    <input type="text" name="email" placeholder="Email Address">
    <textarea name="message" placeholder="Type Your Message Here"></textarea>
    <input id="sendEmail" type="submit" name="submit" value="Send">
</form>
</code>```

This will send an email to test@testemail.com when the user submit a message in the form

Title: Problems with PHP contact form

Body:
Try like this

<?php

$email = $_POST['email'];
$message = $_POST['message'];

$to = "test@testemail.com";
$subject = "New Message!"; $body = "This is an automated message. Please do not reply to this email. \n\n $email \n\n $message";
$body= $_POST["message"]
if ($_SERVER["REQUEST_METHOD"] == "POST") {
mail($to, $subject, $body); echo "Message Sent.";

}
?>

<form id="contact-me-form" action="contact.php" name="contact_form "method="post">
    <input type="text" name="email" placeholder="Email Address">
    <textarea name="message" placeholder="Type Your Message Here"></textarea>
    <input id="sendEmail" type="submit" name="submit" value="Send">
</form>

This will send an email to test@testemail.com when the user submit a message in the form


问:
Counting nuumber of emoticons in tweets extracted in a file
i have extraxted a number of tweets ( utf-8) in a csv file. I am trying to run a python code to count number of emoticons in each tweet.The emoticons appear in the file as follows:-
 ðŸ’©ðŸ’©ðŸ’©ðŸ’©ðŸ’©

Now i dont know how to identify these.
I tried to covert the whole tring to unicode and then counting them by following code:
  s=str(strs, "unicode")
    print(s)
    print(strs)
    emoti = re.finditer(r'[\U0001f600-\U0001f650]', s)
    count = sum(1 for _ in emoti)

but it gives an error as-decoding str is not supported
I cant collect all the tweets again, i need to count no. of emoticons on the same set of tweets. can any body tell how to go about it?
Thanks in Advance

答:
If this string is what you have:

```<code>'ðŸ’©ðŸ’©ðŸ’©ðŸ’©ðŸ’©'
</code>```

It has been decoded with the wrong codec.  It looks like cp1252 (the Windows ANSI default).  Re-encode it with the incorrect coded used, then decode it with utf8.  Better yet, fix the source of the incorrect decoding.

```<code>>>> 'ðŸ’©ðŸ’©ðŸ’©ðŸ’©ðŸ’©'.encode('cp1252')
b'\xf0\x9f\x92\xa9\xf0\x9f\x92\xa9\xf0\x9f\x92\xa9\xf0\x9f\x92\xa9\xf0\x9f\x92\xa9'
>>> 'ðŸ’©ðŸ’©ðŸ’©ðŸ’©ðŸ’©'.encode('cp1252').decode('utf8')
''
</code>```

Unfortunately there is not a single range of Unicode characters for emoji.  See emoji-test.txt from the unicode.org website.  That particular character is U+1F4A9, and is outside the Unicode range you have specified in your sample code.

Body:
If this string is what you have:

'ðŸ’©ðŸ’©ðŸ’©ðŸ’©ðŸ’©'

It has been decoded with the wrong codec.  It looks like cp1252 (the Windows ANSI default).  Re-encode it with the incorrect coded used, then decode it with utf8.  Better yet, fix the source of the incorrect decoding.

>>> 'ðŸ’©ðŸ’©ðŸ’©ðŸ’©ðŸ’©'.encode('cp1252')
b'\xf0\x9f\x92\xa9\xf0\x9f\x92\xa9\xf0\x9f\x92\xa9\xf0\x9f\x92\xa9\xf0\x9f\x92\xa9'
>>> 'ðŸ’©ðŸ’©ðŸ’©ðŸ’©ðŸ’©'.encode('cp1252').decode('utf8')
''

Unfortunately there is not a single range of Unicode characters for emoji.  See emoji-test.txt from the unicode.org website.  That particular character is U+1F4A9, and is outside the Unicode range you have specified in your sample code.


问:
Is there a global database of all products with EAN 13 barcodes which i can integrate with my wordpress site?
EAN 13 is an international system. Is there an API or database that contains all items that have these barcodes? Like all food, goods you can buy in a regular convenience store. Is there a global open database for this that i could integrate with my Database and then use it by adding the just the barcode and the all info related to that product will be autopopulated?</p>

答:
Look here: https://www.outpan.com

It is an crowd sourcing project and there is also an API, where you can query an EAN code and it outputs detailed information.


问:
Java Stream Api strings manipulation
I have some list of words List<String> strings I have to make a word out of most frequent letters on each position.

For example for strings = {"qwerty", "qwer" , "ab", "bab"} the result would be "qwer"

Letters that appear once do not count

I came up to idea of creating a list

```<code>List<Map<String, Integer>> list;
</code>```

Its size is equal to the string in strings of maximal size and the map would count number of characters on the position

```<code>IntStream.range(0, strings.stream().max(String::compareTo).get().length())
    .forEachOrdered(i -> {
        strings.stream().forEach(s -> {
            if (s.length()>i){
                Map<String,Integer> temp = list.get(i);
                String character = s.charAt(i) + "";
                Integer value = temp.get(character) == null ? 0 : temp.get(character) + 1;
                temp.put(character, value);
                list.add(i, temp);
            }
        });
    });
</code>```

Have no idea why id doesn't work

答:
Here's my take. For maximum length string, I used the formula given here.
I am assuming your string has only alphabetical characters in it. Therefore there is no need for a hashmap. An array of size 26 will do. Then I just loop over each position and find the most frequent character.

```<code>public class WordsWithMostFrequentChars {
public static void main(String[] args) {
    String[] st = new String[] { "qwerty", "qwer" , "ab", "bab"};
    List<String> strings = Arrays.asList(st);
    List<Character> result = new ArrayList<Character>();
    int maxLength = strings.stream().max(Comparator.comparingInt(String::length)).get().length();

    IntStream.range(0,maxLength).forEach(i -> {
        int[] freq = new int[26];
        strings.stream().forEach(s -> {
            Character c;
            if(s.length()>i) {
                c=s.charAt(i);
                freq[c - 'a'] = freq[c - 'a'] + 1;
            }
        });
        // max finder
        int max = 0;
        for (int k = 1; k < 26; k++)
            if (freq[k] > freq[max])
                max = k;

        if(freq[max]>1) result.add((char) ('a' + max));

        });

        System.out.println(result);

    }
}
</code>```

Run:

```<code>[q, w, e, r]
</code>```

Title: Java Stream Api strings manipulation

Body:
I have some list of words List<String> strings I have to make a word out of most frequent letters on each position.

For example for strings = {"qwerty", "qwer" , "ab", "bab"} the result would be "qwer"

Letters that appear once do not count

I came up to idea of creating a list

List<Map<String, Integer>> list;

Its size is equal to the string in strings of maximal size and the map would count number of characters on the position

IntStream.range(0, strings.stream().max(String::compareTo).get().length())
    .forEachOrdered(i -> {
        strings.stream().forEach(s -> {
            if (s.length()>i){
                Map<String,Integer> temp = list.get(i);
                String character = s.charAt(i) + "";
                Integer value = temp.get(character) == null ? 0 : temp.get(character) + 1;
                temp.put(character, value);
                list.add(i, temp);
            }
        });
    });

Have no idea why id doesn't work

Body:
Here's my take. For maximum length string, I used the formula given here.
I am assuming your string has only alphabetical characters in it. Therefore there is no need for a hashmap. An array of size 26 will do. Then I just loop over each position and find the most frequent character.

public class WordsWithMostFrequentChars {
public static void main(String[] args) {
    String[] st = new String[] { "qwerty", "qwer" , "ab", "bab"};
    List<String> strings = Arrays.asList(st);
    List<Character> result = new ArrayList<Character>();
    int maxLength = strings.stream().max(Comparator.comparingInt(String::length)).get().length();

    IntStream.range(0,maxLength).forEach(i -> {
        int[] freq = new int[26];
        strings.stream().forEach(s -> {
            Character c;
            if(s.length()>i) {
                c=s.charAt(i);
                freq[c - 'a'] = freq[c - 'a'] + 1;
            }
        });
        // max finder
        int max = 0;
        for (int k = 1; k < 26; k++)
            if (freq[k] > freq[max])
                max = k;

        if(freq[max]>1) result.add((char) ('a' + max));

        });

        System.out.println(result);

    }
}

Run:

[q, w, e, r]


问:
CURL HTTP CODE 403
I am getting curl http code as 403:

The user myuser was denied access to perform the operation on the object defect due to the following reasons: The permission setting for operation Create doesn't allow user to perform the required operation on the secured object.

Same code was working fine with 'HTTP', now it is 'HTTPS', so I updated code like added curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); and curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); these lines and it is giving 403 as HTTP CODE. Can someone help me where I am wrong.

```<code>$ch = curl_init(MY_BASE_URL);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13');
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_COOKIEFILE, MY_COOKIES);
curl_setopt($ch, CURLOPT_COOKIEJAR, MY_COOKIES);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8","Accept:application/json, text/javascript, */*; q=0.01"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($myfields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response=curl_exec($ch);
$code=curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code!=201)
{throw new Exception("Error creating defect: ".$response);}
else{echo 'Success';}
</code>```

答:
try this user agent(if not works then try with random user agents)</p>

```<code>$useragent= "curl/7.39.0";
curl_setopt($ch,CURLOPT_USERAGENT, $useragent);
</code>```

Title: CURL HTTP CODE 403

Body:
I am getting curl http code as 403:

The user myuser was denied access to perform the operation on the object defect due to the following reasons: The permission setting for operation Create doesn't allow user to perform the required operation on the secured object.

Same code was working fine with 'HTTP', now it is 'HTTPS', so I updated code like added curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); and curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); these lines and it is giving 403 as HTTP CODE. Can someone help me where I am wrong.

$ch = curl_init(MY_BASE_URL);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13');
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_COOKIEFILE, MY_COOKIES);
curl_setopt($ch, CURLOPT_COOKIEJAR, MY_COOKIES);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8","Accept:application/json, text/javascript, */*; q=0.01"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($myfields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response=curl_exec($ch);
$code=curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code!=201)
{throw new Exception("Error creating defect: ".$response);}
else{echo 'Success';}

Body:
try this user agent(if not works then try with random user agents)

$useragent= "curl/7.39.0";
curl_setopt($ch,CURLOPT_USERAGENT, $useragent);


问:
Confusion about the text file encoding and how to transform between different encoding method?
I had a text file f.txt which encoded as UTF-8 as shown below:

```<code>chengs-MBP:test cheng$ cat f.txt
Wіnd
like
chengs-MBP:test cheng$ FILE -I f.txt
f.txt: text/plain; charset=utf-8
</code>```

However, this two words in this file Wind and like are diiferent, as the like can be find by grep command while Wind cannot, it confused me:

```<code>chengs-MBP:test cheng$ cat f.txt | grep like
like
chengs-MBP:test cheng$ cat f.txt | grep Wind
chengs-MBP:test cheng$
</code>```

And I want to transform this file to us-ascii by iconv command, but I failed:

```<code>chengs-MBP:test cheng$ iconv -f UTF-8 -t US-ASCII f.txt > new.txt
conv: f.txt:1:0: cannot convert
</code>```

My goal is to transform this file to a format which all of the words inside this file could be find by grep or sed... that's all.

答:
UTF-8 is an encoding for the Unicode character set. Some Unicode characters are in look-alike subsets, sometimes collectively called "confusables". So,

```<code>f.txt | grep "Wind"
</code>```

will look for LATIN SMALL LETTER I, while

```<code>f.txt | grep "Wіnd"
</code>```

will look for CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I. You could write it as

```<code>f.txt | grep "W\xD1\x96nd"
</code>```

Since і is not a member of the ASCII character set, it can't be encoded in ASCII.

If you want to take this further, I suggest that you don't abandon UTF-8 as your text file encoding but you might want to transliterate confusable letters to Basic Latin or use a search library that deals with transliteration as a feature. grep just gives you exactly what you ask for.

Body:
I had a text file f.txt which encoded as UTF-8 as shown below:

chengs-MBP:test cheng$ cat f.txt
Wіnd
like
chengs-MBP:test cheng$ FILE -I f.txt
f.txt: text/plain; charset=utf-8

However, this two words in this file Wind and like are diiferent, as the like can be find by grep command while Wind cannot, it confused me:

chengs-MBP:test cheng$ cat f.txt | grep like
like
chengs-MBP:test cheng$ cat f.txt | grep Wind
chengs-MBP:test cheng$

And I want to transform this file to us-ascii by iconv command, but I failed:

chengs-MBP:test cheng$ iconv -f UTF-8 -t US-ASCII f.txt > new.txt
conv: f.txt:1:0: cannot convert

My goal is to transform this file to a format which all of the words inside this file could be find by grep or sed... that's all.

Body:
UTF-8 is an encoding for the Unicode character set. Some Unicode characters are in look-alike subsets, sometimes collectively called "confusables". So,

f.txt | grep "Wind"

will look for LATIN SMALL LETTER I, while

f.txt | grep "Wіnd"

will look for CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I. You could write it as

f.txt | grep "W\xD1\x96nd"

Since і is not a member of the ASCII character set, it can't be encoded in ASCII.

If you want to take this further, I suggest that you don't abandon UTF-8 as your text file encoding but you might want to transliterate confusable letters to Basic Latin or use a search library that deals with transliteration as a feature. grep just gives you exactly what you ask for.


问:
C, Open gl, drawing until another line
Trying to figure out how to draw that white lines until these red lines:

I can draw to until green point height's but not red lines.

答:
Here's a little unoptimized example using the fixed function opengl pipeline:

```<code>#define FREEGLUT_LIB_PRAGMAS 1
#define NDEBUG 1

#include <GL/glut.h>
#include <cmath>

using namespace std;

#define MAX_POINTS 8
#define PROJ_VALUE 40

float points[MAX_POINTS][2];

void init() {
    points[0][0] = 0;
    points[0][1] = 10;
    points[1][0] = 1;
    points[1][1] = 8;
    points[2][0] = 2;
    points[2][1] = 4;
    points[3][0] = 3;
    points[3][1] = 7;
    points[4][0] = 4;
    points[4][1] = 3;
    points[5][0] = 5;
    points[5][1] = 4;
    points[6][0] = 6;
    points[6][1] = 5;
    points[7][0] = 7;
    points[7][1] = 0;
}

float lerp(float x, float a, float b) {
    return x * b + (1 - x) * a;
}

void plot_function(int step_x, int step_y) {
    for (int i = 0; i < MAX_POINTS; i++) {
        float x0 = (float)points[i][0] * step_x + step_x;
        float y0 = (float)points[i][1] * step_y;
        float x1 = (float)points[i + 1][0] * step_x + step_x;
        float y1 = (float)points[i + 1][1] * step_y;

        for (int j = 0; j < step_x; j++) {
            float k = (float)j / step_x;

            glColor3f(1.0, 1.0, 1.0);
            glBegin(GL_LINES);
            glVertex2f(x0 + j, 0);
            glVertex2f(x0 + j, lerp(k, y0, y1));
            glEnd();
        }

        glColor3f(0.0, 1.0, 0.0);
        glPointSize(8);
        glBegin(GL_POINTS);
        glVertex2f(x0, y0);
        glEnd();

        glColor3f(1.0, 0.0, 0.0);
        glBegin(GL_LINES);
        glVertex2f(x0, y0);
        glVertex2f(x1, y1);
        glEnd();
    }
}

void display() {
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, PROJ_VALUE, 0, PROJ_VALUE, -1, 1);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    plot_function(5, 2);
    glutSwapBuffers();
}

int main(int argc, char **argv) {
    init();

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutInitWindowSize(640, 480);
    glutCreateWindow("StackOverflow gl plotting");
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}
</code>```

Here's the result:

I'll leave to you the exercise to make it beautier (round points, antialiasing, clipping, smooth rendering) and refactor properly the code to be faster&cleaner. Hope it helps.

EDIT:

Brief explanation of the above code:

At the very beginning you'll have some control points (green points). Usually you store these points into an array of floating point values, in the above code they're just stored in a global variable called points. To draw these points you'd just need to loop through the array and using the opengl function to draw points, they represent x&y coordinates. You could also draw the white lines from [x,y] to [x,0] easily as well.

Now, the tricky part, how do we draw the intermediate points? What are they actually? First of all, you need to understand what a linear interpolation is, read here, but basically is a formula like x*b+(1-x)*a, if you consider x=0 the result will be a, if x=1 the result will be b and if the value is between [0,1] you'll get a value in between a&b. So, in order to calculate the intermediate points you just apply the linear interpolation between the previous&next points, you can see that in the line glVertex2f(x0 + j, lerp(k, y0, y1)).

About step_x & step_y arguments, if it's easier for you to understand, replace them with 0 and get rid of them, so you'll understand easily the code.

Title: C, Open gl, drawing until another line

Body:
Here's a little unoptimized example using the fixed function opengl pipeline:

#define FREEGLUT_LIB_PRAGMAS 1
#define NDEBUG 1

#include <GL/glut.h>
#include <cmath>

using namespace std;

#define MAX_POINTS 8
#define PROJ_VALUE 40

float points[MAX_POINTS][2];

void init() {
    points[0][0] = 0;
    points[0][1] = 10;
    points[1][0] = 1;
    points[1][1] = 8;
    points[2][0] = 2;
    points[2][1] = 4;
    points[3][0] = 3;
    points[3][1] = 7;
    points[4][0] = 4;
    points[4][1] = 3;
    points[5][0] = 5;
    points[5][1] = 4;
    points[6][0] = 6;
    points[6][1] = 5;
    points[7][0] = 7;
    points[7][1] = 0;
}

float lerp(float x, float a, float b) {
    return x * b + (1 - x) * a;
}

void plot_function(int step_x, int step_y) {
    for (int i = 0; i < MAX_POINTS; i++) {
        float x0 = (float)points[i][0] * step_x + step_x;
        float y0 = (float)points[i][1] * step_y;
        float x1 = (float)points[i + 1][0] * step_x + step_x;
        float y1 = (float)points[i + 1][1] * step_y;

        for (int j = 0; j < step_x; j++) {
            float k = (float)j / step_x;

            glColor3f(1.0, 1.0, 1.0);
            glBegin(GL_LINES);
            glVertex2f(x0 + j, 0);
            glVertex2f(x0 + j, lerp(k, y0, y1));
            glEnd();
        }

        glColor3f(0.0, 1.0, 0.0);
        glPointSize(8);
        glBegin(GL_POINTS);
        glVertex2f(x0, y0);
        glEnd();

        glColor3f(1.0, 0.0, 0.0);
        glBegin(GL_LINES);
        glVertex2f(x0, y0);
        glVertex2f(x1, y1);
        glEnd();
    }
}

void display() {
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, PROJ_VALUE, 0, PROJ_VALUE, -1, 1);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    plot_function(5, 2);
    glutSwapBuffers();
}

int main(int argc, char **argv) {
    init();

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutInitWindowSize(640, 480);
    glutCreateWindow("StackOverflow gl plotting");
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}

Here's the result:

I'll leave to you the exercise to make it beautier (round points, antialiasing, clipping, smooth rendering) and refactor properly the code to be faster&cleaner. Hope it helps.

EDIT:

Brief explanation of the above code:

At the very beginning you'll have some control points (green points). Usually you store these points into an array of floating point values, in the above code they're just stored in a global variable called points. To draw these points you'd just need to loop through the array and using the opengl function to draw points, they represent x&y coordinates. You could also draw the white lines from [x,y] to [x,0] easily as well.

Now, the tricky part, how do we draw the intermediate points? What are they actually? First of all, you need to understand what a linear interpolation is, read here, but basically is a formula like x*b+(1-x)*a, if you consider x=0 the result will be a, if x=1 the result will be b and if the value is between [0,1] you'll get a value in between a&b. So, in order to calculate the intermediate points you just apply the linear interpolation between the previous&next points, you can see that in the line glVertex2f(x0 + j, lerp(k, y0, y1)).

About step_x & step_y arguments, if it's easier for you to understand, replace them with 0 and get rid of them, so you'll understand easily the code.


问:
How do I open Python IDLE (Shell WIndow) in WIndows 10?
I am just starting to learn Python and I am using Windows 10. I downloaded and installed Python 3.4.3. But everytime I open Python from my Desktop or from C:\Python\python.exe it just opens a black command prompt without any Menu options like File menu, Edit Menu, Format Menu etc. I can't see any colors of the code, it's just black screen with white text. I searched about it on internet and came to know that what I am opening is the Editor winodws and I need to open Shell Window in order to have access to all of those options and features. I can't figure out where is the .exe of Shell Window and with what name is it? Please help me.

P.S. I also tried to open pythonw.exe that was present in the Python folder where it was installed, but nothing opened.

答:
In Windows you will need to right click a .py, and press Edit to edit the file using IDLE. Since the default action of double clicking a .py is executing the file with python on a shell prompt.

To open just IDLE:

Click on that. C:\Python36\Lib\idlelib\idle.bat


问:
delete_all does not work while each do delete does
Intended functionality - delete all linked asset_items when an asset_line_item is deleted. (without using destroy, destroy_all). I am using postgres

With the following model:

```<code>class AssetLineItem < PurchaseLineItem

  has_many :asset_items
  ...

  after_destroy :destroy_cleanup

  private

  def destroy_cleanup
    asset_items.delete_all
  end
end
</code>```

This results in the asset_items remaining, however all of their asset_line_item columns are set to null.

```<code>  def destroy_cleanup
    asset_items.each do |asset_item|
      asset_item.delete
    end
  end
</code>```

replacing delete_all with the loop above however has the intended result of delete all associated asset_items.

Although I have working code, I'm curious what could cause delete_all to act in this way?

答:
Calling just delete_all on association just nullifies the reference. It is the same as delete_all(:nullify):

```<code>pry(main)> Booking.last.passengers.delete_all
  Booking Load (0.6ms)  SELECT  `bookings`.* FROM `bookings`  ORDER BY `bookings`.`id` DESC LIMIT 1
  SQL (2.8ms)  UPDATE `passengers` SET `passengers`.`booking_id` = NULL WHERE `passengers`.`booking_id` = 157
=> nil
</code>```

You need to call delete_all(:delete_all) to actually delete associated records.

Here is docs.

Or to get desired effect you can add following line to your AssetLineItem model:

```<code>has_many :asset_items, dependent: :destroy
</code>```

as lakhvir kumar mentioned.

Also your destroy_cleanup callback could be refactored to:

```<code>  def destroy_cleanup
    asset_items.map(&:delete)
  end
</code>```

Here is some good links to the topic:

delete_all vs destroy_all?

Rails :dependent => :destroy VS :dependent => :delete_all

Body:
Intended functionality - delete all linked asset_items when an asset_line_item is deleted. (without using destroy, destroy_all). I am using postgres

With the following model:

class AssetLineItem < PurchaseLineItem

  has_many :asset_items
  ...

  after_destroy :destroy_cleanup

  private

  def destroy_cleanup
    asset_items.delete_all
  end
end

This results in the asset_items remaining, however all of their asset_line_item columns are set to null.

  def destroy_cleanup
    asset_items.each do |asset_item|
      asset_item.delete
    end
  end

replacing delete_all with the loop above however has the intended result of delete all associated asset_items.

Although I have working code, I'm curious what could cause delete_all to act in this way?

Body:
Calling just delete_all on association just nullifies the reference. It is the same as delete_all(:nullify):

pry(main)> Booking.last.passengers.delete_all
  Booking Load (0.6ms)  SELECT  `bookings`.* FROM `bookings`  ORDER BY `bookings`.`id` DESC LIMIT 1
  SQL (2.8ms)  UPDATE `passengers` SET `passengers`.`booking_id` = NULL WHERE `passengers`.`booking_id` = 157
=> nil

You need to call delete_all(:delete_all) to actually delete associated records.

Here is docs.

Or to get desired effect you can add following line to your AssetLineItem model:

has_many :asset_items, dependent: :destroy

as lakhvir kumar mentioned.

Also your destroy_cleanup callback could be refactored to:

  def destroy_cleanup
    asset_items.map(&:delete)
  end

Here is some good links to the topic:

delete_all vs destroy_all?

Rails :dependent => :destroy VS :dependent => :delete_all


问:
Cut corners in image PHP
Im working with Intervention Image to make a frame. Now im stuck on a part to cut off the edges. I need 4 of those images to make them fit as a frame. I know i can use the Intervention Image library to rotate the image, but i have no clue to cut those corners. Anyone has a idea how to achieve this?

Original:

Result:

答:
You need to create two polygons and fill them with transparent colors.

http://image.intervention.io/api/polygon

An example:

```<code>$img = Image::make('foo/bar/baz.jpg')->encode('png');
$w = $img->width();
$h = $img->height();
$points = [0,0,$width,0,$width,$width,0,0];
$img->polygon($points, function($d) {
    $d->background("transparent");
});
$points = [0,$height,$width,$height,$width,$height-$width,0,$height];
$img->polygon($points, function($d) {
    $d->background("transparent");
});
$img->save('foo/bar/baz_cut.png'); // jpg won't have transparency
</code>```

Title: Cut corners in image PHP

Body:
You need to create two polygons and fill them with transparent colors.

http://image.intervention.io/api/polygon

An example:

$img = Image::make('foo/bar/baz.jpg')->encode('png');
$w = $img->width();
$h = $img->height();
$points = [0,0,$width,0,$width,$width,0,0];
$img->polygon($points, function($d) {
    $d->background("transparent");
});
$points = [0,$height,$width,$height,$width,$height-$width,0,$height];
$img->polygon($points, function($d) {
    $d->background("transparent");
});
$img->save('foo/bar/baz_cut.png'); // jpg won't have transparency


问:
Does Vaadin 8 `Binder::bindInstanceFields` only work with String data types?
Using the Vaadin 8 @PropertyId annotation with the Binder::bindInstanceFields is certainly shorter and sweeter than writing a line of code for each field-property binding.

```<code>Person person;  // `name` is String, `yearOfBirth` is Integer.
…
@PropertyId ( "name" )
final TextField nameField = new TextField ( "Full name:" ); // Bean property.

@PropertyId ( "yearOfBirth" )
final TextField yearOfBirthField = new TextField ( "Year of Birth:" ); // Bean property.
…
// Binding
Binder < Person > binder = new Binder <> ( Person.class );
binder.bindInstanceFields ( this );
binder.setBean ( person );
</code>```

But we get an Exception thrown because the yearOfBirth property is an Integer, and this easy-does-it binding approach lacks an converter.

SEVERE:

java.lang.IllegalStateException: Property type 'java.lang.Integer' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.

Does that mean Binder::bindInstanceFields can be used only a beans made entirely of properties of String data type?

Is there a way to specify a Converter such as StringToIntegerConverter without having to itemize each and every binding in code?

答:
So far the best way to handle this for me, is to write a dedicated field for
the type of input (note that this "pattern" also works for writing composite
fields).

See the complete example here.  The IntegerField is the field to wrap the Integer
yet in another binder via a bean to hold the actual value.

```<code>// run with `spring run --watch <file>.groovy`
@Grab('com.vaadin:vaadin-spring-boot-starter:2.0.1')

import com.vaadin.ui.*
import com.vaadin.annotations.*
import com.vaadin.shared.*
import com.vaadin.data.*
import com.vaadin.data.converter.*

class IntegerField extends CustomField<Integer> {
    final Binder<Bean> binder
    final wrappedField = new TextField()
    IntegerField() {
        binder = new BeanValidationBinder<IntegerField.Bean>(IntegerField.Bean)
        binder.forField(wrappedField)
            .withNullRepresentation('')
            .withConverter(new StringToIntegerConverter("Only numbers"))
            .bind('value')
        doSetValue(null)
    }
    IntegerField(String caption) {
        this()
        setCaption(caption)
    }
    Class<Integer> getType() {
        Integer
    }
    com.vaadin.ui.Component initContent() {
        wrappedField
    }
    Registration addValueChangeListener(HasValue.ValueChangeListener<Integer> listener) {
        binder.addValueChangeListener(listener)
    }
    protected void doSetValue(Integer value) {
        binder.bean = new IntegerField.Bean(value)
    }
    Integer getValue() {
       binder.bean?.value
    }
    @groovy.transform.Canonical
    static class Bean {
        Integer value
    }
}

@groovy.transform.Canonical
class Person {
    @javax.validation.constraints.Min(value=18l)
    Integer age
}

class PersonForm extends FormLayout {
    @PropertyId('age')
    IntegerField ageField = new IntegerField("Age")
    PersonForm() {
        addComponents(ageField)
    }
}

@com.vaadin.spring.annotation.SpringUI
@com.vaadin.annotations.Theme("valo")
class MyUI extends UI {
    protected void init(com.vaadin.server.VaadinRequest request) {
        def form = new PersonForm()
        def binder = new BeanValidationBinder<Person>(Person)
        binder.bindInstanceFields(form)
        binder.bean = new Person()
        content = new VerticalLayout(
            form,
            new Button("Submit", {
                Notification.show(binder.bean.toString())
            } as Button.ClickListener)
        )
    }
}
</code>```

Body:
Using the Vaadin 8 @PropertyId annotation with the Binder::bindInstanceFields is certainly shorter and sweeter than writing a line of code for each field-property binding.

Person person;  // `name` is String, `yearOfBirth` is Integer.
…
@PropertyId ( "name" )
final TextField nameField = new TextField ( "Full name:" ); // Bean property.

@PropertyId ( "yearOfBirth" )
final TextField yearOfBirthField = new TextField ( "Year of Birth:" ); // Bean property.
…
// Binding
Binder < Person > binder = new Binder <> ( Person.class );
binder.bindInstanceFields ( this );
binder.setBean ( person );

But we get an Exception thrown because the yearOfBirth property is an Integer, and this easy-does-it binding approach lacks an converter.

SEVERE:

java.lang.IllegalStateException: Property type 'java.lang.Integer' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.

Does that mean Binder::bindInstanceFields can be used only a beans made entirely of properties of String data type?

Is there a way to specify a Converter such as StringToIntegerConverter without having to itemize each and every binding in code?

Body:
So far the best way to handle this for me, is to write a dedicated field for
the type of input (note that this "pattern" also works for writing composite
fields).

See the complete example here.  The IntegerField is the field to wrap the Integer
yet in another binder via a bean to hold the actual value.

// run with `spring run --watch <file>.groovy`
@Grab('com.vaadin:vaadin-spring-boot-starter:2.0.1')

import com.vaadin.ui.*
import com.vaadin.annotations.*
import com.vaadin.shared.*
import com.vaadin.data.*
import com.vaadin.data.converter.*

class IntegerField extends CustomField<Integer> {
    final Binder<Bean> binder
    final wrappedField = new TextField()
    IntegerField() {
        binder = new BeanValidationBinder<IntegerField.Bean>(IntegerField.Bean)
        binder.forField(wrappedField)
            .withNullRepresentation('')
            .withConverter(new StringToIntegerConverter("Only numbers"))
            .bind('value')
        doSetValue(null)
    }
    IntegerField(String caption) {
        this()
        setCaption(caption)
    }
    Class<Integer> getType() {
        Integer
    }
    com.vaadin.ui.Component initContent() {
        wrappedField
    }
    Registration addValueChangeListener(HasValue.ValueChangeListener<Integer> listener) {
        binder.addValueChangeListener(listener)
    }
    protected void doSetValue(Integer value) {
        binder.bean = new IntegerField.Bean(value)
    }
    Integer getValue() {
       binder.bean?.value
    }
    @groovy.transform.Canonical
    static class Bean {
        Integer value
    }
}

@groovy.transform.Canonical
class Person {
    @javax.validation.constraints.Min(value=18l)
    Integer age
}

class PersonForm extends FormLayout {
    @PropertyId('age')
    IntegerField ageField = new IntegerField("Age")
    PersonForm() {
        addComponents(ageField)
    }
}

@com.vaadin.spring.annotation.SpringUI
@com.vaadin.annotations.Theme("valo")
class MyUI extends UI {
    protected void init(com.vaadin.server.VaadinRequest request) {
        def form = new PersonForm()
        def binder = new BeanValidationBinder<Person>(Person)
        binder.bindInstanceFields(form)
        binder.bean = new Person()
        content = new VerticalLayout(
            form,
            new Button("Submit", {
                Notification.show(binder.bean.toString())
            } as Button.ClickListener)
        )
    }
}


问:
Python- Remaining values in list after value has occurred x times
So far I have:

```<code>list = [0,0,1,1,0,1,0,1,0]
score = 1
for i in list:
    while score < 4:
        if i == 0:
            list.pop(0)
            score = score +1
print(list)
</code>```

I want to print the remaining list after the 4th 0. The list is dynamic and is changed by the user.

答:
You can simply achieve that without any need of second loop, first write a function that finds the correct index and get the remaining part. </p>

```<code>def find_index(element, encounter, list):
   for i, v in enumerate(list):
     if v == element:
       encounter -= 1
       if encounter == 0:
         return i

list = [0,0,1,1,0,1,0,1,0]
list[find_index(0, 4, list):]
# >>> [0, 1, 0]
list[find_index(0, 4, list)+1:]
# >>> [1, 0]
</code>```

Body:
So far I have:

list = [0,0,1,1,0,1,0,1,0]
score = 1
for i in list:
    while score < 4:
        if i == 0:
            list.pop(0)
            score = score +1
print(list)

I want to print the remaining list after the 4th 0. The list is dynamic and is changed by the user.

Body:
You can simply achieve that without any need of second loop, first write a function that finds the correct index and get the remaining part.

def find_index(element, encounter, list):
   for i, v in enumerate(list):
     if v == element:
       encounter -= 1
       if encounter == 0:
         return i

list = [0,0,1,1,0,1,0,1,0]
list[find_index(0, 4, list):]
# >>> [0, 1, 0]
list[find_index(0, 4, list)+1:]
# >>> [1, 0]


问:
How to update (clear previous value) screen with PHP?
I echo a variable to the screen in a while loop. The variable increments by 1 up to 10.

So I show it on screen echo $a;

But I want to clear the screen from the previous value before it echoes the new one.

In Pascal for example it was ClrScr;.

I looked a bit for the code to clear screen but I don't think what I found is exactly what I wanted, nor did I understood it :P

答:
After </p>

```<code>echo $a;
</code>```

<p>You can add </p>

```<code>echo exec('clear');
</code>```

Body:
After

echo $a;

You can add

echo exec('clear');


问:
How the call the default implementation code in protocol in swift?
I have given the some default implementation code in protocol extension. But how to call this specified code in a class that confirms to the protocol. Here is an example:</p>

```<code>class BaseClass {}
protocol ImplementedProtocol {
    func printInfo()
}
extension ImplementedProtocol where Self: BaseClass {
    func printInfo() {
        print("Hello! This is ImplementedProtocol")
    }
}

class SuperClass: BaseClass, ImplementedProtocol {
    func printInfo() {
        // I should do sth here.
        print("Hello! This is SuperClass")
    }
}
class SubClass: SuperClass {
    override func printInfo() {
        super.printInfo()
        print("This is SubClass")
    }

}

let a = SubClass()
a.printInfo() // I get "Here is SuperClass. Here is SubClass."
// But I want "Here is ImplementedProtocol. Here is SuperClass. Here is SubClass."
</code>```

答:
A protocol is more like a compile-time guarantee that type has certain methods and properties. Default implementation adds another layer of complexity to this by injecting an implementation to the protocol's adopters. I don't have the skills to go through Swift's source code but I think when the adopter provide its own implementation, the default implementation is overshadowed and there's no way to get it back.

A workaround is to add a method with a different name to your protocol, which provides the default implementation and can be called by any adopter:

```<code>protocol ImplementedProtocol {
    func printInfo()

    func defaultPrintInfo()
}

extension ImplementedProtocol where Self: BaseClass {
    func printInfo() {
        defaultPrintInfo()
    }

    func defaultPrintInfo() {
        print("Hello! This is ImplementedProtocol")
    }
}

class SuperClass: BaseClass, ImplementedProtocol {
    func printInfo() {
        self.defaultPrintInfo()
        print("Hello! This is SuperClass")
    }
}
</code>```

Body:
I have given the some default implementation code in protocol extension. But how to call this specified code in a class that confirms to the protocol. Here is an example:

class BaseClass {}
protocol ImplementedProtocol {
    func printInfo()
}
extension ImplementedProtocol where Self: BaseClass {
    func printInfo() {
        print("Hello! This is ImplementedProtocol")
    }
}

class SuperClass: BaseClass, ImplementedProtocol {
    func printInfo() {
        // I should do sth here.
        print("Hello! This is SuperClass")
    }
}
class SubClass: SuperClass {
    override func printInfo() {
        super.printInfo()
        print("This is SubClass")
    }

}

let a = SubClass()
a.printInfo() // I get "Here is SuperClass. Here is SubClass."
// But I want "Here is ImplementedProtocol. Here is SuperClass. Here is SubClass."

Body:
A protocol is more like a compile-time guarantee that type has certain methods and properties. Default implementation adds another layer of complexity to this by injecting an implementation to the protocol's adopters. I don't have the skills to go through Swift's source code but I think when the adopter provide its own implementation, the default implementation is overshadowed and there's no way to get it back.

A workaround is to add a method with a different name to your protocol, which provides the default implementation and can be called by any adopter:

protocol ImplementedProtocol {
    func printInfo()

    func defaultPrintInfo()
}

extension ImplementedProtocol where Self: BaseClass {
    func printInfo() {
        defaultPrintInfo()
    }

    func defaultPrintInfo() {
        print("Hello! This is ImplementedProtocol")
    }
}

class SuperClass: BaseClass, ImplementedProtocol {
    func printInfo() {
        self.defaultPrintInfo()
        print("Hello! This is SuperClass")
    }
}


问:
Difference between @interface definition in .h and .m file
Normally we use

```<code>@interface interface_name : parent_class <delegates>
{
......
}
@end
</code>```

method in .h file and in .m file we synthesis the properties of variables declared in .h file.

But in some code, this @interface.....@end method is kept in the .m file also. What does it mean?  What is the difference between them?

Also give some words about getters and setters for the interface file that is defined in .m file...

答:
The concept is that you can make your project much cleaner if you
  limit the .h to the public interfaces of your class, and then put
  private implementation details in this class extension.

when you declare variable methods or properties in ABC.h file , It
  means these variables properties and methods can be access outside the
  class

```<code>@interface Jain:NSObject
{
    NSString *_name;
}

@property(readwrite, copy) NSString *name;
-(NSString*)makeSmallTalkWith:(Person*)jain;
@end
</code>```

@Interface allows you to declare private ivars, properties and
  methods. So anything you declare here cannot be accessed from outside
  this class. In general, you want to declare all ivars, properties and
  methods by default as private

Simply say when you declare variable methods or properties in ABC.m
  file , It means these variables properties and methods can not  be
  access outside the class

```<code>@interface Jain()
    {
        NSString *_name;
    }

    @property(readwrite, copy) NSString *name;
    -(NSString*)makeSmallTalkWith:(Person*)jain;
    @end
</code>```

OwnerDisplayName: Rajkanth

Body:
Normally we use

@interface interface_name : parent_class <delegates>
{
......
}
@end

method in .h file and in .m file we synthesis the properties of variables declared in .h file.

But in some code, this @interface.....@end method is kept in the .m file also. What does it mean?  What is the difference between them?

Also give some words about getters and setters for the interface file that is defined in .m file...

Body:
The concept is that you can make your project much cleaner if you
  limit the .h to the public interfaces of your class, and then put
  private implementation details in this class extension.

when you declare variable methods or properties in ABC.h file , It
  means these variables properties and methods can be access outside the
  class

@interface Jain:NSObject
{
    NSString *_name;
}

@property(readwrite, copy) NSString *name;
-(NSString*)makeSmallTalkWith:(Person*)jain;
@end

@Interface allows you to declare private ivars, properties and
  methods. So anything you declare here cannot be accessed from outside
  this class. In general, you want to declare all ivars, properties and
  methods by default as private

Simply say when you declare variable methods or properties in ABC.m
  file , It means these variables properties and methods can not  be
  access outside the class

@interface Jain()
    {
        NSString *_name;
    }

    @property(readwrite, copy) NSString *name;
    -(NSString*)makeSmallTalkWith:(Person*)jain;
    @end


问:
A better alternative to Vagrant
We use Vagrant for dev environment automation and provisioning. It works smoothly. But sometimes, if vagrant has some problem(we faced LOT of them starting from SSH to networking config), the new developers who join us and are supposed to just boot up the box and start working, have a really hard time coping up with that. So I was just wondering, ain't there some easier way(like having a GUI like VirtualBox to start and end an env) of managing these virtual environments?

maybe my question should be, What are the best practices on this area, other than Vagrant?

答: You could use Docker if you don't mind the configuration overhead https://www.docker.com/</p>

Title: A better alternative to Vagrant


问:
Github: Permission denied (publickey) but I got "You've successfully authenticated" message
Step I had done:
https://help.github.com/articles/generating-ssh-keys/ follow exactly.

```<code>$ eval "$(ssh-agent -s)"
Agent pid 31944
$ ssh-add
Enter passphrase for /home/centos7/.ssh/id_rsa:
Identity added: /home/centos7/.ssh/id_rsa (/home/centos7/.ssh/id_rsa)

$ ssh-add -l
4096 ab:4d:23:23:99:ce:bb:9d:9f:9e:f9:b2:c8:1a:cd:f7 /home/centos7/.ssh/id_rsa (RSA)
</code>```

However, when I run

```<code>$ git clone git@github.com:privateRepo/repo.git

Cloning into 'repo'...
The authenticity of host 'github.com (192.30.252.130)' can't be established.
RSA key fingerprint is 56:27:ac:a5:36:28:2d:36:23:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,192.30.252.130' (RSA) to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.
</code>```

Below is the output I run

```<code>$ ssh -Tv git@github.com

OpenSSH_6.6.1, OpenSSL 1.0.1e-fips 11 Feb 2013
debug1: Reading configuration data /home/centos7/.ssh/config
debug1: /home/centos/.ssh/config line 1: Applying options for *github.com
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 56: Applying options for *
debug1: Connecting to github.com [192.30.252.131] port 22.
debug1: Connection established.
debug1: identity file /home/centos7/.ssh/id_rsa type 1
debug1: identity file /home/centos7/.ssh/id_rsa-cert type -1
debug1: identity file /home/centos7/.ssh/id_dsa type -1
debug1: identity file /home/centos7/.ssh/id_dsa-cert type -1
debug1: identity file /home/centos7/.ssh/id_ecdsa type -1
debug1: identity file /home/centos7/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/centos7/.ssh/id_ed25519 type -1
debug1: identity file /home/centos7/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.6.1
debug1: Remote protocol version 2.0, remote software version libssh-0.7.0
debug1: no match: libssh-0.7.0
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-sha1 none
debug1: kex: client->server aes128-ctr hmac-sha1 none
debug1: kex: ecdh-sha2-nistp256 need=20 dh_need=20
debug1: kex: ecdh-sha2-nistp256 need=20 dh_need=20
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: RSA 56:27:ac:a5:36:28:2d:36:23:1b:56:4d:eb:df:a6:48
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /home/centos/.ssh/known_hosts:1
Warning: Permanently added the RSA host key for IP address '192.30.252.131' to the list of known hosts.
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/centos7/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 535
debug1: Authentication succeeded (publickey).
Authenticated to github.com ([192.30.252.131]:22).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8
debug1: Sending env LC_CTYPE = UTF-8
Hi tomkim! You've successfully authenticated, but GitHub does not provide shell access.
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: channel 0: free: client-session, nchannels 1
Transferred: sent 4128, received 2040 bytes, in 0.5 seconds
Bytes per second: sent 8000.8, received 3953.9
debug1: Exit status 1
</code>```

As the line above showed that Hi tomkim! You've successfully authenticated, but GitHub does not provide shell access. which means I already unthenticated, but why I can't clone my repo?

Update:
I can clone in my home directory, but when I try with sudo it did not work, it happen in my /var/www/html/ folder

$ sudo git clone git@github.privateRepo/repo.git
Cloning into 'repo'...
Warning: Permanently added the RSA host key for IP address '192.30.252.131' to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

$ git clone git@github.privateRepo/repo.git
Cloning into 'repo'...
remote: Counting objects: 4741, done.
remote: Total 4741 (delta 0), reused 0 (delta 0), pack-reused 4741
Receiving objects: 100% (4741/4741), 30.30 MiB | 5.83 MiB/s, done.
Resolving deltas: 100% (1451/1451), done.
[centos@ip-172-31-12-124 ~]$ ll
total 4
drwxrwxr-x. 12 centos centos 4096 Jun 15 04:16 repo

I know I can clone with HTTPS, but I would like to solve this issue, anyone can help?

答:
use this
https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/

then get your generated key ( start with ssh-rsa or other type )
go to your git user panel -> SSH & GPG Keys  --> New SSH key -> paste your key ( fill title with any ) then press Add SSH key

Will Fix.

good luck.

Body:
Step I had done:
https://help.github.com/articles/generating-ssh-keys/ follow exactly.

$ eval "$(ssh-agent -s)"
Agent pid 31944
$ ssh-add
Enter passphrase for /home/centos7/.ssh/id_rsa:
Identity added: /home/centos7/.ssh/id_rsa (/home/centos7/.ssh/id_rsa)

$ ssh-add -l
4096 ab:4d:23:23:99:ce:bb:9d:9f:9e:f9:b2:c8:1a:cd:f7 /home/centos7/.ssh/id_rsa (RSA)

However, when I run

$ git clone git@github.com:privateRepo/repo.git

Cloning into 'repo'...
The authenticity of host 'github.com (192.30.252.130)' can't be established.
RSA key fingerprint is 56:27:ac:a5:36:28:2d:36:23:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,192.30.252.130' (RSA) to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

Below is the output I run

$ ssh -Tv git@github.com

OpenSSH_6.6.1, OpenSSL 1.0.1e-fips 11 Feb 2013
debug1: Reading configuration data /home/centos7/.ssh/config
debug1: /home/centos/.ssh/config line 1: Applying options for *github.com
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 56: Applying options for *
debug1: Connecting to github.com [192.30.252.131] port 22.
debug1: Connection established.
debug1: identity file /home/centos7/.ssh/id_rsa type 1
debug1: identity file /home/centos7/.ssh/id_rsa-cert type -1
debug1: identity file /home/centos7/.ssh/id_dsa type -1
debug1: identity file /home/centos7/.ssh/id_dsa-cert type -1
debug1: identity file /home/centos7/.ssh/id_ecdsa type -1
debug1: identity file /home/centos7/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/centos7/.ssh/id_ed25519 type -1
debug1: identity file /home/centos7/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.6.1
debug1: Remote protocol version 2.0, remote software version libssh-0.7.0
debug1: no match: libssh-0.7.0
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-sha1 none
debug1: kex: client->server aes128-ctr hmac-sha1 none
debug1: kex: ecdh-sha2-nistp256 need=20 dh_need=20
debug1: kex: ecdh-sha2-nistp256 need=20 dh_need=20
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: RSA 56:27:ac:a5:36:28:2d:36:23:1b:56:4d:eb:df:a6:48
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /home/centos/.ssh/known_hosts:1
Warning: Permanently added the RSA host key for IP address '192.30.252.131' to the list of known hosts.
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/centos7/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 535
debug1: Authentication succeeded (publickey).
Authenticated to github.com ([192.30.252.131]:22).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8
debug1: Sending env LC_CTYPE = UTF-8
Hi tomkim! You've successfully authenticated, but GitHub does not provide shell access.
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: channel 0: free: client-session, nchannels 1
Transferred: sent 4128, received 2040 bytes, in 0.5 seconds
Bytes per second: sent 8000.8, received 3953.9
debug1: Exit status 1

As the line above showed that Hi tomkim! You've successfully authenticated, but GitHub does not provide shell access. which means I already unthenticated, but why I can't clone my repo?

Update:
I can clone in my home directory, but when I try with sudo it did not work, it happen in my /var/www/html/ folder

$ sudo git clone git@github.privateRepo/repo.git
Cloning into 'repo'...
Warning: Permanently added the RSA host key for IP address '192.30.252.131' to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

$ git clone git@github.privateRepo/repo.git
Cloning into 'repo'...
remote: Counting objects: 4741, done.
remote: Total 4741 (delta 0), reused 0 (delta 0), pack-reused 4741
Receiving objects: 100% (4741/4741), 30.30 MiB | 5.83 MiB/s, done.
Resolving deltas: 100% (1451/1451), done.
[centos@ip-172-31-12-124 ~]$ ll
total 4
drwxrwxr-x. 12 centos centos 4096 Jun 15 04:16 repo

I know I can clone with HTTPS, but I would like to solve this issue, anyone can help?