问:
Drag borderless windows form by mouse

Possible Duplicate:

  C# - Make a borderless form movable?

I have made a form without border in C#, by setting

this.FormBorderStyle = FormBorderStyle.None;

Now, problem is how can I drag it by mouse?

答:
This should be what you are looking for "Enhanced: Drag and move WinForms"

```<code>public partial class MyDraggableForm : Form
{
    private const int WM_NCHITTEST = 0x84;
    private const int HTCLIENT = 0x1;
    private const int HTCAPTION = 0x2;

    ///
    /// Handling the window messages
    ///
    protected override void WndProc(ref Message message)
    {
        base.WndProc(ref message);

        if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT)
            message.Result = (IntPtr)HTCAPTION;
    }
    public MyDraggableForm()
    {
        InitializeComponent();
    }
}
</code>```

As the blog post states, this is a way to "fool" the system. This way you don't need to think about mouse up/down events.

Title: Drag borderless windows form by mouse

Body:
This should be what you are looking for "Enhanced: Drag and move WinForms"

public partial class MyDraggableForm : Form
{
    private const int WM_NCHITTEST = 0x84;
    private const int HTCLIENT = 0x1;
    private const int HTCAPTION = 0x2;

    ///
    /// Handling the window messages
    ///
    protected override void WndProc(ref Message message)
    {
        base.WndProc(ref message);

        if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT)
            message.Result = (IntPtr)HTCAPTION;
    }
    public MyDraggableForm()
    {
        InitializeComponent();
    }
}

As the blog post states, this is a way to "fool" the system. This way you don't need to think about mouse up/down events.


来源: stackexchange

问:
Laravel testing is it possible to have followingRedirects after the assertSessionHas
I am testing in laravel and saw yesterday that you can't have followingRedirects before assertSessionHas. So I wanted to know if it is possible to have it after the assertSessionHas without repeating the whole test code. I have now this a temporary solution:

```<code>$response = $this->post('/signup', [
        'username' => 'Testing',
        'email' => 'testing@test.com',
        'password' => 'secret',
        'password_confirmation' => 'secret',
    ]);

    $this->assertDatabaseHas('users', ['username' => 'Testing', 'email' => 'testing@test.com']);
    $response->assertSessionHas('success', 'Your account has been created!');
    $code = $this->followRedirects($response)->getStatusCode();
    $this->assertEquals(200, $code);
</code>```

But I want to know if you are able to change the response later on with the followingRedirects instead of using it this way.

答:
When sending a post request in Laravel using PHPUnit, you don't need to pass the csrf_token(), it is included automatically.

I would refactor your code like this:

```<code>$this->post('/signup', [
    'username' => 'Testing',
    'email' => 'testing@test.com',
    'password' => 'secret',
    'password_confirmation' => 'secret',
])->assertStatus(200)
->assertSessionHas('success', 'Your account has been created!');

$user = User::latest()->first();

$this->assertEquals('Testing', $user->name);
$this->assertEquals('testing@test.com', $user->email);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am testing in laravel and saw yesterday that you can't have followingRedirects before assertSessionHas. So I wanted to know if it is possible to have it after the assertSessionHas without repeating the whole test code. I have now this a temporary solution:

$response = $this->post('/signup', [
        'username' => 'Testing',
        'email' => 'testing@test.com',
        'password' => 'secret',
        'password_confirmation' => 'secret',
    ]);

    $this->assertDatabaseHas('users', ['username' => 'Testing', 'email' => 'testing@test.com']);
    $response->assertSessionHas('success', 'Your account has been created!');
    $code = $this->followRedirects($response)->getStatusCode();
    $this->assertEquals(200, $code);

But I want to know if you are able to change the response later on with the followingRedirects instead of using it this way.

Body:
When sending a post request in Laravel using PHPUnit, you don't need to pass the csrf_token(), it is included automatically.

I would refactor your code like this:

$this->post('/signup', [
    'username' => 'Testing',
    'email' => 'testing@test.com',
    'password' => 'secret',
    'password_confirmation' => 'secret',
])->assertStatus(200)
->assertSessionHas('success', 'Your account has been created!');

$user = User::latest()->first();

$this->assertEquals('Testing', $user->name);
$this->assertEquals('testing@test.com', $user->email);


问:
Spring boot deployment
I am developing a spring boot rest API for mobile application (without view or JSP pages) , I am deploying the API on a windows server (dedicated) , I installed the tomcat server and MySQL server on the server , when I am trying to access the application from the server localhost everything is ok , ex:  localhost:8080/api/users, but when I am trying to access it from another pc using my server IP  I get cannot reach ex:  162.144.188.112:8080/api/users
the same thing happens when I want to access MySQL server using server IP.

so I do not  know is there any issue in my server , or I just miss something in the  configuration for MySQL and tomcat server ?

答:
You don't need to install tomcat to use spring boot. There is a starter that allows you to embed the servlet container and package everything inside a jar at build time
Therefore, starting the application is done simply by running java -jar.
Check out the tutorial to know how to correctly deploy a spring boot application

Title: Spring boot deployment


问:
akka-http. Represent Option values
By default, akka-http deserialize empty string in json(i.e. {"some_key":""}) to Some("").

How to make akka-http deserialize empty strings in all Option[String] types in all models of the App to None?

答:
Akka-http uses spray-json by default, so all you need to do is override the default behaviour by providing a custom one. One easy way to get what you are looking for is here: (mixin this trait on all your models)

```<code>trait CustomJsonMarshalling {
  implicit object OptionFormat extends JsonFormat[Option[String]] {
    def write(str: Option[String]) = JsString(str.getOrElse(""))

    def read(str: JsValue) = {
      str match {
        case JsString(s) => if (s.isEmpty) None else Some(s)
        case _ => throw new DeserializationException("Expected non empty string")
      }
    }
  }
}
</code>```

Title: akka-http. Represent Option values

Body:
Akka-http uses spray-json by default, so all you need to do is override the default behaviour by providing a custom one. One easy way to get what you are looking for is here: (mixin this trait on all your models)

trait CustomJsonMarshalling {
  implicit object OptionFormat extends JsonFormat[Option[String]] {
    def write(str: Option[String]) = JsString(str.getOrElse(""))

    def read(str: JsValue) = {
      str match {
        case JsString(s) => if (s.isEmpty) None else Some(s)
        case _ => throw new DeserializationException("Expected non empty string")
      }
    }
  }
}


问:
Django suppress form errors
If I have a bound form in Django 1.11, can I suppress the errors?

forms.py

```<code>class FirstForm(forms.ModelForm):
  class Meta:
    model = Foo
    fields = "__all__"
    exclude = ['many_fields_on_second_form']

class SecondForm(forms.ModelForm):
  class Meta:
    model = Foo
    fields = "__all__"
    widgets = {
      'all_first_form_fields':forms.HiddenInput(),
    }
</code>```

views.py

```<code>def index(request):
  # they've submitted the first form at this point
  myform = FirstForm(request.POST)
  if myform.is_valid():
    secondform = SecondForm(request.POST)
    secondform.errors = None # <-- this doesn't work, "can't set attribute"
  else:
    messages.error('first form failed')
</code>```

I do not want to suppress the errors in the template, only in the view. Is this possible?

答:
From a separate question I found this gem; set initial values instead:

```<code>initial = dict(map(lambda x:(x[0], x[1][0]), dict(request.POST).items()))
secondform = SecondForm(initial=initial)
</code>```

In my view the hidden fields populate correctly and there are no errors.

Title: Django suppress form errors

Body:
If I have a bound form in Django 1.11, can I suppress the errors?

forms.py

class FirstForm(forms.ModelForm):
  class Meta:
    model = Foo
    fields = "__all__"
    exclude = ['many_fields_on_second_form']

class SecondForm(forms.ModelForm):
  class Meta:
    model = Foo
    fields = "__all__"
    widgets = {
      'all_first_form_fields':forms.HiddenInput(),
    }

views.py

def index(request):
  # they've submitted the first form at this point
  myform = FirstForm(request.POST)
  if myform.is_valid():
    secondform = SecondForm(request.POST)
    secondform.errors = None # <-- this doesn't work, "can't set attribute"
  else:
    messages.error('first form failed')

I do not want to suppress the errors in the template, only in the view. Is this possible?

Body:
From a separate question I found this gem; set initial values instead:

initial = dict(map(lambda x:(x[0], x[1][0]), dict(request.POST).items()))
secondform = SecondForm(initial=initial)

In my view the hidden fields populate correctly and there are no errors.


问:
Dated jboss console log entries
Currently my jboss's console log entries are not dated,
If the log is timely dated with time which will help me to debug some application performance issue.
Can any one give some tips on the same? </p>

答:
The log configuration in JBoss 3.2.7 exists in the log4j.xml file. You can find that file in the conf directory of given configuration.

You can find there such lines:

```<code>  <layout class="org.apache.log4j.PatternLayout">
     <!-- The default pattern: Date Priority [Category] Message\n -->
     <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>

     <!-- The full pattern: Date MS Priority [Category] (Thread:NDC) Message\n
     <param name="ConversionPattern" value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
      -->
  </layout>
</code>```

You can just simple comment first definition of ConversionPattern and uncomment the second one. Or just simple create your own conversion pattern, you can find more about it here: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

ContentLicense: CC BY-SA 2.5

Title: Dated jboss console log entries

Body:
The log configuration in JBoss 3.2.7 exists in the log4j.xml file. You can find that file in the conf directory of given configuration.

You can find there such lines:

  <layout class="org.apache.log4j.PatternLayout">
     <!-- The default pattern: Date Priority [Category] Message\n -->
     <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>

     <!-- The full pattern: Date MS Priority [Category] (Thread:NDC) Message\n
     <param name="ConversionPattern" value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
      -->
  </layout>

You can just simple comment first definition of ConversionPattern and uncomment the second one. Or just simple create your own conversion pattern, you can find more about it here: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html


问:
Count number of Special Character in Unix Shell
I have a delimited file that is separated by octal \036 or Hexadecimal value 1e.

I need to count the number of delimiters on each line using a bash shell script.

I was trying to use awk, not sure if this is the best way.

Sample Input (| is a representation of \036)

```<code>Example|Running|123|
</code>```

Expected output:

```<code>3
</code>```

答:
Simply try

```<code>awk -F"|" '{print substr($3,length($3))}' OFS="|"   Input_file
</code>```

Explanation: Making field separator -F as | and then printing the 3rd column by doing $3 only as per your need. Then setting OFS(output field separator) to |. Finally mentioning Input_file name here.

Body:
I have a delimited file that is separated by octal \036 or Hexadecimal value 1e.

I need to count the number of delimiters on each line using a bash shell script.

I was trying to use awk, not sure if this is the best way.

Sample Input (| is a representation of \036)

Example|Running|123|

Expected output:

3

Body:
Simply try

awk -F"|" '{print substr($3,length($3))}' OFS="|"   Input_file

Explanation: Making field separator -F as | and then printing the 3rd column by doing $3 only as per your need. Then setting OFS(output field separator) to |. Finally mentioning Input_file name here.


问:
How to document parameters of a closure that's a parameter
My attempt at documenting a closure parameter to a function:

```<code>/**
    sends the request out.

    - Parameter pzurl: request description including url, method, formdata.
 - Parameter responseProcessor: closure that's on success invokes
 - Parameter json: a json array or dictionary
 - Parameter timestamp: and the same `timestamp` that this function returns
 - parameter failure: closure is invoked when json could not be parsed or remote indicated failure
 - Returns: timestamp to identify responses
 */
internal static func processPZURL(pzurl: PZURL,
                                  responseProcessor:@escaping (_ json:JSON, _ timestamp: TimeInterval) -> (), failure:@escaping (PZError) -> ()) -> TimeInterval {
</code>```

yields "No description"

and I can find no description of how to change that

Apple markup documentation <s>of no help</s> is here

more documentation from NSHipster that does not address the closure woe

答:
Apparently this is broken ever since january 2017 (or never worked in any xcode) per this:

https://bugs.swift.org/browse/SR-3693
so my question seems to be an up to date version of
How do you document the parameters of a function's closure parameter in Swift 3?

except answer in that question does not work in xcode 9.2

filed 35881586 with apple

ContentLicense: CC BY-SA 4.0

Body:
My attempt at documenting a closure parameter to a function:

/**
    sends the request out.

    - Parameter pzurl: request description including url, method, formdata.
 - Parameter responseProcessor: closure that's on success invokes
 - Parameter json: a json array or dictionary
 - Parameter timestamp: and the same `timestamp` that this function returns
 - parameter failure: closure is invoked when json could not be parsed or remote indicated failure
 - Returns: timestamp to identify responses
 */
internal static func processPZURL(pzurl: PZURL,
                                  responseProcessor:@escaping (_ json:JSON, _ timestamp: TimeInterval) -> (), failure:@escaping (PZError) -> ()) -> TimeInterval {

yields "No description"

and I can find no description of how to change that

Apple markup documentation <s>of no help</s> is here

more documentation from NSHipster that does not address the closure woe


问:
Mask from max values in numpy array, specific axis
Input example:

I have a numpy array, e.g.

a=np.array([[0,1], [2, 1], [4, 8]])

Desired output:

I would like to produce a mask array with the max value along a given axis, in my case axis 1, being True and all others being False. e.g. in this case

mask = np.array([[False, True], [True, False], [False, True]])

Attempt:

I have tried approaches using np.amax but this returns the max values in a flattened list:

```<code>>>> np.amax(a, axis=1)
array([1, 2, 8])
</code>```

and np.argmax similarly returns the indices of the max values along that axis.

```<code>>>> np.argmax(a, axis=1)
array([1, 0, 1])
</code>```

I could iterate over this in some way but once these arrays become bigger I want the solution to remain something native in numpy.

答:
in on line : np.equal(a.max(1)[:,None],a) or np.equal(a.max(1),a.T).T .

But this can lead to several ones in a row.

Body:
Input example:

I have a numpy array, e.g.

a=np.array([[0,1], [2, 1], [4, 8]])

Desired output:

I would like to produce a mask array with the max value along a given axis, in my case axis 1, being True and all others being False. e.g. in this case

mask = np.array([[False, True], [True, False], [False, True]])

Attempt:

I have tried approaches using np.amax but this returns the max values in a flattened list:

>>> np.amax(a, axis=1)
array([1, 2, 8])

and np.argmax similarly returns the indices of the max values along that axis.

>>> np.argmax(a, axis=1)
array([1, 0, 1])

I could iterate over this in some way but once these arrays become bigger I want the solution to remain something native in numpy.


问:
Python - List not printing to outfile
I'm trying to write a program for checking out/returning books at the library and I'm using temporary lists as storage for all the data in the patrons.txt and books.txt so I can edit it and then put it back in. The problem is that when I try to print the tempBookFile and tempPatronFile to outfile, the "file = outfile" part of following line

```<code>print(tempBookFile, file = outfile)
</code>```

is highlighted in yellow and when I hover over it it says Expected type 'Optional[IO[str]] got 'TextIOWrapper[str]' instead". As a result, everything in the book list and patron list gets deleted, except for the name of the book which is stored in the patron file while it is checked out.

```<code>class Book:
    def __init__(self, title, author, genre, isbn):
        self.title = title
        self.author = author
        self.genre = genre
        self.isbn = isbn

    def printAll(self,outfile):
        print(self.title, "|", self.author, "|", self.genre, "|", self.isbn, file = outfile)

class Patron:
    def __init__(self, name, phone, books):
        self.name = name
        self.phone = phone
        self.books = books

    def printAll(self, outfile):
        print(self.name, "|", self.phone, "|", self.books, file = outfile)

def main():
    print("Welcome to JCK library!")
    menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

    while(menu != 6):
        if(menu == 1):
            outfile = open("books.txt", "w")
            title = input("Enter title: ")
            while(title != "done" and title != "Done"):

                author = input("Enter author: ")
                genre = input("Enter genre: ")
                isbn = input("Enter isbn: ")
                book = Book(title,author,genre,isbn)
                book.printAll(outfile)

                print("Book added: ", title)
                print("Author: ", author)
                print("Isbn: ", isbn, "\n")

                title = input("Enter title: ")
            outfile.close()
            menu = eval(input( "Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 2):
            outfile = open("patrons.txt", "w")
            name = input("Enter patron name: ")
            phone = input("Enter phone number: ")
            books = []

            patron = Patron(name,phone,books)
            patron.printAll(outfile)
            outfile.close()
            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 3):
            title = ""
            author = ""
            genre = ""
            isbn = ""
            name = ""
            phone = ""
            books = []
            outfile = open("patrons.txt", "r")
            patronName = input("Enter Patron Name: ")

            if (patronName in outfile.read()):
                print("Patron found.")

                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                        name = patronInfo[0]
                        phone = patronInfo[1]
                        books = patronInfo[2]

                #Creates a temporary list containing all of the contents of the patrons.txt file so that
                #the list can be modified and then put back into the patrons.txt file
                tempPatronFile = outfile.readlines()

                #Removes the line from the temporary list that contains information about the patron who is checking out
                #a book so that it can be re-added to the list after it is updated
                for line in tempPatronFile:
                    if(patronName in line):
                        tempPatronFile.pop(line)

                outfile.close()
                outfile = open("books.txt", "r")
                bookName = input("Enter Book Name: ")

                if bookName in outfile.read():
                    books.append(bookName)

                    for line in outfile.readlines():
                        if(bookName in line):
                            bookInfo = line.split("|")
                            title = bookInfo[0]
                            author = bookInfo[1]
                            genre = bookInfo[2]
                            isbn = bookInfo[3]

                    book = Book(title,author,genre,isbn)

                    #Creates a temporary list containing all of the contents of the books.txt file so that
                    #the list can be modified and then put back into the books.txt file
                    tempBookFile = outfile.readlines()

                    #Removes the line from the temporary list that contains information about the book so that
                    #the book can be re-added later after it has been returned.
                    for line in tempBookFile:
                        if(bookName in line):
                            tempBookFile.pop(line)

                    outfile.close()

                    outfile = open("books.txt", "w")
                    print(tempBookFile, file = outfile)
                    outfile.close()

                    outfile = open("patrons.txt", "w")
                    print(tempPatronFile, file = outfile)
                    patron = Patron(name,phone,books)
                    patron.printAll(outfile)
                    book.printAll(outfile)
                    outfile.close()

                    print("Book due in 2 weeks.")

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 4):
            outfile = open("patrons.txt", "r")
            patronName = input("Enter patron name: ")

            if(patronName in outfile.read()):
                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                name = patronInfo[0]
                phone = patronInfo[1]
                books = patronInfo[2]

                bookName = input("Enter book name: ")

                if(bookName in outfile.read()):
                    for line in outfile.readlines():
                        if(bookName in line):
                            bookInfo = line.split("|")
                        title = bookInfo[0]
                        author = bookInfo[1]
                        genre = bookInfo[2]
                        isbn = bookInfo[3]

                    book = Book(title, author, genre, isbn)

                # Creates a temporary list containing all of the contents of the patrons.txt file so that
                # the list can be modified and then put back into the patrons.txt file
                tempPatronFile = outfile.readlines()

                # Removes the line from the temporary list that contains information about the patron who is checking out
                # a book so that it can be re-added to the list after it is updated
                for line in tempPatronFile:
                    if (patronName in line):
                        tempPatronFile.pop(line)

                #Removes the information about the book which was stored in the patron file while it was checked out.
                #Upon being returned, the book will go back into the books.txt file
                for line in tempPatronFile:
                    if(bookName in line):
                        tempPatronFile.pop(line)

                outfile.close()

                outfile = open("books.txt", "r")
                tempBookFile = outfile.readlines()
                tempBookFile.append(book)###################################
                outfile.close()

                outfile = open("books.txt", "w")
                print(tempBookFile, file = outfile)
                outfile.close()

                outfile = open("patrons.txt", "w")
                for line in books:
                    if(bookName in line):
                        books.pop(line)
                patron = Patron(name,phone,books)
                print(tempPatronFile, file = outfile)
                patron.printAll(outfile)
                outfile.close()
                print("Book returned.")

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 5):
            outfile = open("patrons.txt", "r")
            patronName = input("Input patron's name: ")

            if(patronName in outfile.read()):
                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                name = patronInfo[0]
                phone = patronInfo[1]
                books = patronInfo[2]

                print(patronName, "has the following book(s) checked out:\n", books)

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

    print("Have a nice day!")

main()
</code>```

答:
The issue has to do with your old school file opening. You should avoid using open and close to manage your files and instead use a with statement. Most of the time if you are using resources that need to be cleaned up/managed you should use

```<code>with open("my_file.txt", "w") as output_file:
    # File based operations here
</code>```

And then PyCharm will be happy. You can see a similar problem here: PyCharm - Expected type 'Optional[IO[str]]', got 'TextIOWrapper[str]' instead

Also as someone commented (it's now deleted) make sure you are opening the file in the correct mode. "w" will erase everything in the file and let you write to it. "r" will only let you read from it. "a" will let you append to the file and might be what you want. If you look up the inputs to open you can get the full details. https://docs.python.org/3/library/functions.html#open

Title: Python - List not printing to outfile

Body:
I'm trying to write a program for checking out/returning books at the library and I'm using temporary lists as storage for all the data in the patrons.txt and books.txt so I can edit it and then put it back in. The problem is that when I try to print the tempBookFile and tempPatronFile to outfile, the "file = outfile" part of following line

print(tempBookFile, file = outfile)

is highlighted in yellow and when I hover over it it says Expected type 'Optional[IO[str]] got 'TextIOWrapper[str]' instead". As a result, everything in the book list and patron list gets deleted, except for the name of the book which is stored in the patron file while it is checked out.

class Book:
    def __init__(self, title, author, genre, isbn):
        self.title = title
        self.author = author
        self.genre = genre
        self.isbn = isbn

    def printAll(self,outfile):
        print(self.title, "|", self.author, "|", self.genre, "|", self.isbn, file = outfile)

class Patron:
    def __init__(self, name, phone, books):
        self.name = name
        self.phone = phone
        self.books = books

    def printAll(self, outfile):
        print(self.name, "|", self.phone, "|", self.books, file = outfile)

def main():
    print("Welcome to JCK library!")
    menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

    while(menu != 6):
        if(menu == 1):
            outfile = open("books.txt", "w")
            title = input("Enter title: ")
            while(title != "done" and title != "Done"):

                author = input("Enter author: ")
                genre = input("Enter genre: ")
                isbn = input("Enter isbn: ")
                book = Book(title,author,genre,isbn)
                book.printAll(outfile)

                print("Book added: ", title)
                print("Author: ", author)
                print("Isbn: ", isbn, "\n")

                title = input("Enter title: ")
            outfile.close()
            menu = eval(input( "Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 2):
            outfile = open("patrons.txt", "w")
            name = input("Enter patron name: ")
            phone = input("Enter phone number: ")
            books = []

            patron = Patron(name,phone,books)
            patron.printAll(outfile)
            outfile.close()
            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 3):
            title = ""
            author = ""
            genre = ""
            isbn = ""
            name = ""
            phone = ""
            books = []
            outfile = open("patrons.txt", "r")
            patronName = input("Enter Patron Name: ")

            if (patronName in outfile.read()):
                print("Patron found.")

                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                        name = patronInfo[0]
                        phone = patronInfo[1]
                        books = patronInfo[2]

                #Creates a temporary list containing all of the contents of the patrons.txt file so that
                #the list can be modified and then put back into the patrons.txt file
                tempPatronFile = outfile.readlines()

                #Removes the line from the temporary list that contains information about the patron who is checking out
                #a book so that it can be re-added to the list after it is updated
                for line in tempPatronFile:
                    if(patronName in line):
                        tempPatronFile.pop(line)

                outfile.close()
                outfile = open("books.txt", "r")
                bookName = input("Enter Book Name: ")

                if bookName in outfile.read():
                    books.append(bookName)

                    for line in outfile.readlines():
                        if(bookName in line):
                            bookInfo = line.split("|")
                            title = bookInfo[0]
                            author = bookInfo[1]
                            genre = bookInfo[2]
                            isbn = bookInfo[3]

                    book = Book(title,author,genre,isbn)

                    #Creates a temporary list containing all of the contents of the books.txt file so that
                    #the list can be modified and then put back into the books.txt file
                    tempBookFile = outfile.readlines()

                    #Removes the line from the temporary list that contains information about the book so that
                    #the book can be re-added later after it has been returned.
                    for line in tempBookFile:
                        if(bookName in line):
                            tempBookFile.pop(line)

                    outfile.close()

                    outfile = open("books.txt", "w")
                    print(tempBookFile, file = outfile)
                    outfile.close()

                    outfile = open("patrons.txt", "w")
                    print(tempPatronFile, file = outfile)
                    patron = Patron(name,phone,books)
                    patron.printAll(outfile)
                    book.printAll(outfile)
                    outfile.close()

                    print("Book due in 2 weeks.")

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 4):
            outfile = open("patrons.txt", "r")
            patronName = input("Enter patron name: ")

            if(patronName in outfile.read()):
                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                name = patronInfo[0]
                phone = patronInfo[1]
                books = patronInfo[2]

                bookName = input("Enter book name: ")

                if(bookName in outfile.read()):
                    for line in outfile.readlines():
                        if(bookName in line):
                            bookInfo = line.split("|")
                        title = bookInfo[0]
                        author = bookInfo[1]
                        genre = bookInfo[2]
                        isbn = bookInfo[3]

                    book = Book(title, author, genre, isbn)

                # Creates a temporary list containing all of the contents of the patrons.txt file so that
                # the list can be modified and then put back into the patrons.txt file
                tempPatronFile = outfile.readlines()

                # Removes the line from the temporary list that contains information about the patron who is checking out
                # a book so that it can be re-added to the list after it is updated
                for line in tempPatronFile:
                    if (patronName in line):
                        tempPatronFile.pop(line)

                #Removes the information about the book which was stored in the patron file while it was checked out.
                #Upon being returned, the book will go back into the books.txt file
                for line in tempPatronFile:
                    if(bookName in line):
                        tempPatronFile.pop(line)

                outfile.close()

                outfile = open("books.txt", "r")
                tempBookFile = outfile.readlines()
                tempBookFile.append(book)###################################
                outfile.close()

                outfile = open("books.txt", "w")
                print(tempBookFile, file = outfile)
                outfile.close()

                outfile = open("patrons.txt", "w")
                for line in books:
                    if(bookName in line):
                        books.pop(line)
                patron = Patron(name,phone,books)
                print(tempPatronFile, file = outfile)
                patron.printAll(outfile)
                outfile.close()
                print("Book returned.")

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 5):
            outfile = open("patrons.txt", "r")
            patronName = input("Input patron's name: ")

            if(patronName in outfile.read()):
                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                name = patronInfo[0]
                phone = patronInfo[1]
                books = patronInfo[2]

                print(patronName, "has the following book(s) checked out:\n", books)

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

    print("Have a nice day!")

main()

Body:
The issue has to do with your old school file opening. You should avoid using open and close to manage your files and instead use a with statement. Most of the time if you are using resources that need to be cleaned up/managed you should use

with open("my_file.txt", "w") as output_file:
    # File based operations here

And then PyCharm will be happy. You can see a similar problem here: PyCharm - Expected type 'Optional[IO[str]]', got 'TextIOWrapper[str]' instead

Also as someone commented (it's now deleted) make sure you are opening the file in the correct mode. "w" will erase everything in the file and let you write to it. "r" will only let you read from it. "a" will let you append to the file and might be what you want. If you look up the inputs to open you can get the full details. https://docs.python.org/3/library/functions.html#open


问:
Cross-Platform iOS/Mac OS X Objective-C development?
I'll be starting  medium-sized iOS project soon, a document-centric app.

Later, the software might get ported to Mac OS X. Of course, the whole UI will need to change; that's not what I'm asking.

Is it possible to write the core logic in such a way that it's cross-platform (Mac/iOS only), or more easily ported? Has anybody done this before, or is the usual way to just write different code for both platforms?

I'm thankful for any tips regarding this, be they about Code, Frameworks, Version Control - anything. I'd hate to realize I've painted myself into a corner only after the fact, so I want to start as well as possible.

答:
The first step is to adhere to the MVC pattern. Views often need rewriting between iOS and OS X as you say, but the model layer and some part of controllers can be reused.

Foundation (NSArray etc) and Core Data are shared between iOS and OS X, so it should be no problem to write a common Objective-C code which manages the model layer, such as saving the data to the disk, retrieving them from the network, etc.

One important point is to resist the urge to write a long-ish code segment which mainly deals with the model layer directly in your view controller. That long-ish code segment can be abstracted into a method acting on the model layer by itself; then you can reuse that code in an OS X app later.

For example, suppose I create a view controller managing the document shown. Then in an action method defined in the view controller corresponding to an edit operation, I might write a code directly delving into the detail of the model layer and implement the edit operation. Then I would need to perform a rather big change to the source code when the view controller is ported to a window controller (or NSDocument subclass). Rather, I would implement a method for that particular edit operation inside the document object itself, so that I can call that method both from the view controller in an iOS app and from the window controller in an OS X app.


问:
Where do docker logs go when splunk server is not reachable

I am trying to get docker logs from a running docker container. I have configured splunk as logging driver in my docker compose and I understand that if splunk server is not reachable then container won't start.

```<code>  proxysecurity:
    image: test/image
    network_mode: host
    depends_on:
      - zookeeper
    ports:
      - '8083:8083'
    logging:
      driver: "splunk"
      options:
         splunk-url: "http://XX.X2.X3.X1:XXX7/"
         splunk-token: "XXXXX5-9CA1-44B8-B9E8-2XXX25"
         splunk-format: json
         tag: "{{.ImageName}}/{{.Name}}/{{.ID}}"
    environment:
      XXXCONNECT: localhost:32181
      XXXXXRS: http://localhost:8083
</code>```

Now if splunk server is not reachable when container is up and running , is there any fall back mechanism wherein we can tell docker container to log locally ?
Or is there any way to log to splunk as well as locally inside container ?

答:
I am the author of the Splunk Logging Driver.

In case if Splunk is unavailable, driver holds small buffer in memory and keeps retrying. Configuration for the size of the buffer is documented no official docs for the driver https://docs.docker.com/engine/admin/logging/splunk/

SPLUNK_LOGGING_DRIVER_BUFFER_MAX
If driver cannot connect to remote server, what is the maximum amount of messages it can hold in buffer for retries.

Unfortunately this is not ideal, considering that this buffer can be filled pretty quickly and that increasing the buffer to higher number can affect your containers. But this is how most of the drivers written.

I have built another solution delivering logs and metrics to Splunk. This solution includes tiny image with collector and Splunk Certified Application. It is built on top of json-file driver, which means that when Splunk is unavailable it will just keep retrying from the position of the log files. The logs files can have their own settings for rotation, this can be configured with dockerd daemon configuration. You can read another benefits of our solution Comparing with Splunk Logging Driver. And how to get started with Monitoring Docker.

Body:
I am trying to get docker logs from a running docker container. I have configured splunk as logging driver in my docker compose and I understand that if splunk server is not reachable then container won't start.

  proxysecurity:
    image: test/image
    network_mode: host
    depends_on:
      - zookeeper
    ports:
      - '8083:8083'
    logging:
      driver: "splunk"
      options:
         splunk-url: "http://XX.X2.X3.X1:XXX7/"
         splunk-token: "XXXXX5-9CA1-44B8-B9E8-2XXX25"
         splunk-format: json
         tag: "{{.ImageName}}/{{.Name}}/{{.ID}}"
    environment:
      XXXCONNECT: localhost:32181
      XXXXXRS: http://localhost:8083

Now if splunk server is not reachable when container is up and running , is there any fall back mechanism wherein we can tell docker container to log locally ?
Or is there any way to log to splunk as well as locally inside container ?


问:
How to schedule and trigger a delay between publication pages in rails?
I currently work on a recipes web application, where each user have the possibility to like a recipe. A recipe is composed by severals steps.

When an user like a recipe, he is supposed to receive the first step of the recipe. He can see it appear on the steps/index.html.erb page. The next ones are not visible yet.
Then, when he opens it, (recipes/:recipe_id/steps/1/show.html.erb), it displays the first step and, in the same time, triggers a time interval (configurable), before the apparition of the second step, and so on until the last step of the recipe.

The wait and the apparition of a step just have to occur once. When a step is loaded, it always appears on the list without waiting.
To schedule this, someone explains me to use ajax requests. But I did not well describe my problem and working on it, I encounted difficulties… Now I doubt on the structure of all and feel a bit lost!

If you have any idea,
in advance thanks  a lot ;)

Here my code :

Models :

```<code>class Recipe < ApplicationRecord
belongs_to :user
has_many :steps
has_many :favorites
has_many :favorited_by_users, :through => :favorites, :source => 'user'

class Step < ApplicationRecord
belongs_to :recipe
end

class Favorite < ApplicationRecord
belongs_to :recipe
belongs_to :user
end

class User < ApplicationRecord
has_many :recipes
has_many :favorites
has_many :favorite_recipes, :through => :favorites, :source => 'recipe’

devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
end
</code>```

In my Step Controller i have :

```<code>  def index
  @recipe = Recipe.find(params[:recipe_id])
  @steps = @recipe.steps
  end
</code>```

Thanks!!

答:
You'll need a place to store data that will determine if a user has already read a step or not yet. So, we'll add a new "join-table" between User and Step model.

bash / terminal:

```<code>rails generate model steps_user step:belongs_to user:belongs_to is_read:boolean
</code>```

Recommended: change the migration file generated for above, to have default: false, null: false for is_read

app/config/routes.rb

```<code>resources :steps do
  resources :steps_users, only: [] do
    put :create_or_update, on: :collection, as: 'create_or_update_steps_user'
  end
end
</code>```

app/controllers/steps_users_controller.rb

```<code>class StepsUsersController < ApplicationController
  def create_or_update
    @step = Step.find(params[:step_id])
    @steps_user = @step.steps_users.find_or_initialize_by(user: current_user)

    # you can further refactor this to use `save()` and not `save!()`
    # but for simplicity, I'll just use this to raise exception when there is a validation error
    if @steps_user.save!(steps_user_params)
      render status: :ok
    end
  end

  private

  def steps_user_params
    params.require(:steps_user).permit(:is_read)
  end
end
</code>```

app/models/step.rb

```<code>class Step < ApplicationRecord
  has_many :steps_users

  def previous_step
    # you might want to update this as I do not know if you have your own Step attribute that determines the "order" of the Steps
    recipe.steps.order(id: :desc).where('id < ?', id).first
  end
  # ...
</code>```

app/controllers/steps_controller.rb:

```<code>class StepsController < ApplicationController
  def show
    @step = Step.find(params[:id])

    # add some authorization here to prevent anyone from reading this step unless they have already read the previous steps (example code is below)
    # if @step.previous_step && !@step.previous_step.is_read?
    #   render status: :forbidden
    # end
  end
  # ...
</code>```

app/views/steps/show.html.erb:

```<code><script type='text/javasript'>
  $(function() {
    var delay = 30000; // 30 seconds

    var updateStepsUserAsRead = function() {
      $.ajax({
        type: 'POST',
        url: '<%= j create_or_update_steps_user_path(step_id: @step.id) %>',
        contentType: 'application/json; charset=utf-8',
        headers: {
          'X-CSRF-Token': Rails.csrfToken()
        },
        data: {
          _method: 'put',
          steps_user: {
            is_read: true
          }
        }
      })
    }

    setTimeout(updateStepsUserAsRead, delay);
  })
</script>

...
</code>```

Above JS script will mark is_read to be true for the current_user's steps_user record

app/views/steps/index.html.erb

```<code><% @steps.each do |step| %>
  <% if !step.previous_step || (step.previous_step && step.previous_step.is_read?) %>
    <%= link_to 'Step #', step # <<<<< update this %>
  <% end %>
<% end %>
</code>```

Body:
I currently work on a recipes web application, where each user have the possibility to like a recipe. A recipe is composed by severals steps.

When an user like a recipe, he is supposed to receive the first step of the recipe. He can see it appear on the steps/index.html.erb page. The next ones are not visible yet.
Then, when he opens it, (recipes/:recipe_id/steps/1/show.html.erb), it displays the first step and, in the same time, triggers a time interval (configurable), before the apparition of the second step, and so on until the last step of the recipe.

The wait and the apparition of a step just have to occur once. When a step is loaded, it always appears on the list without waiting.
To schedule this, someone explains me to use ajax requests. But I did not well describe my problem and working on it, I encounted difficulties… Now I doubt on the structure of all and feel a bit lost!

If you have any idea,
in advance thanks  a lot ;)

Here my code :

Models :

class Recipe < ApplicationRecord
belongs_to :user
has_many :steps
has_many :favorites
has_many :favorited_by_users, :through => :favorites, :source => 'user'

class Step < ApplicationRecord
belongs_to :recipe
end

class Favorite < ApplicationRecord
belongs_to :recipe
belongs_to :user
end

class User < ApplicationRecord
has_many :recipes
has_many :favorites
has_many :favorite_recipes, :through => :favorites, :source => 'recipe’

devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
end

In my Step Controller i have :

  def index
  @recipe = Recipe.find(params[:recipe_id])
  @steps = @recipe.steps
  end

Thanks!!

Body:
You'll need a place to store data that will determine if a user has already read a step or not yet. So, we'll add a new "join-table" between User and Step model.

bash / terminal:

rails generate model steps_user step:belongs_to user:belongs_to is_read:boolean

Recommended: change the migration file generated for above, to have default: false, null: false for is_read

app/config/routes.rb

resources :steps do
  resources :steps_users, only: [] do
    put :create_or_update, on: :collection, as: 'create_or_update_steps_user'
  end
end

app/controllers/steps_users_controller.rb

class StepsUsersController < ApplicationController
  def create_or_update
    @step = Step.find(params[:step_id])
    @steps_user = @step.steps_users.find_or_initialize_by(user: current_user)

    # you can further refactor this to use `save()` and not `save!()`
    # but for simplicity, I'll just use this to raise exception when there is a validation error
    if @steps_user.save!(steps_user_params)
      render status: :ok
    end
  end

  private

  def steps_user_params
    params.require(:steps_user).permit(:is_read)
  end
end

app/models/step.rb

class Step < ApplicationRecord
  has_many :steps_users

  def previous_step
    # you might want to update this as I do not know if you have your own Step attribute that determines the "order" of the Steps
    recipe.steps.order(id: :desc).where('id < ?', id).first
  end
  # ...

app/controllers/steps_controller.rb:

class StepsController < ApplicationController
  def show
    @step = Step.find(params[:id])

    # add some authorization here to prevent anyone from reading this step unless they have already read the previous steps (example code is below)
    # if @step.previous_step && !@step.previous_step.is_read?
    #   render status: :forbidden
    # end
  end
  # ...

app/views/steps/show.html.erb:

<script type='text/javasript'>
  $(function() {
    var delay = 30000; // 30 seconds

    var updateStepsUserAsRead = function() {
      $.ajax({
        type: 'POST',
        url: '<%= j create_or_update_steps_user_path(step_id: @step.id) %>',
        contentType: 'application/json; charset=utf-8',
        headers: {
          'X-CSRF-Token': Rails.csrfToken()
        },
        data: {
          _method: 'put',
          steps_user: {
            is_read: true
          }
        }
      })
    }

    setTimeout(updateStepsUserAsRead, delay);
  })
</script>

...

Above JS script will mark is_read to be true for the current_user's steps_user record

app/views/steps/index.html.erb

<% @steps.each do |step| %>
  <% if !step.previous_step || (step.previous_step && step.previous_step.is_read?) %>
    <%= link_to 'Step #', step # <<<<< update this %>
  <% end %>
<% end %>


问:
Error with reformatting the way data has been passed into a function
I have the following code :

```<code>var games = ["game_1", "game_2","game_3"]

var players= [{name:"steve"},{name:"sparrow"},{name:"captain"}]

var incomingData= [{game_1:"basketball"},{game_2:"badminton"},{game_3:"pingpong"}]

//change format as shown below:

reformat=[ {name:"steve",game:"basketball"},{name:"steve",game:"badminton"},{name:"steve",game:"pingpong"}]

 incomingData.map(incomingData=>{

       games.map((game,i)=>{
               players[i].game= incomingData.game

     })
    })

console.log(players) //[ { name: 'steve', game: undefined },  { name: sparrow', game: undefined },  { name: 'captain', game: undefined } ]
</code>```

I am trying to learn about how to handle objects. I am getting undefined for the list of game inside the object. I understand this approach is wrong and would like to get some suggestions regarding how to go about changing the format to the required format.

答:
```<code>incomingData.map((data, i) => {
    players[i].game = data[ games[i] ];
});
</code>```

You just need one loop.

Body:
I have the following code :

var games = ["game_1", "game_2","game_3"]

var players= [{name:"steve"},{name:"sparrow"},{name:"captain"}]

var incomingData= [{game_1:"basketball"},{game_2:"badminton"},{game_3:"pingpong"}]

//change format as shown below:

reformat=[ {name:"steve",game:"basketball"},{name:"steve",game:"badminton"},{name:"steve",game:"pingpong"}]

 incomingData.map(incomingData=>{

       games.map((game,i)=>{
               players[i].game= incomingData.game

     })
    })

console.log(players) //[ { name: 'steve', game: undefined },  { name: sparrow', game: undefined },  { name: 'captain', game: undefined } ]

I am trying to learn about how to handle objects. I am getting undefined for the list of game inside the object. I understand this approach is wrong and would like to get some suggestions regarding how to go about changing the format to the required format.

Body:
incomingData.map((data, i) => {
    players[i].game = data[ games[i] ];
});

You just need one loop.


问:
How can I reduce or otherwise influence the number of radial ticks in a polar plot?
I want a polar plot, but with a reduced number of radial (r dimension) ticks.  I already tried the suggested solutions from other questions, such as

```<code>pyplot.locator_params(axis='y', nticks=6)
</code>```

but it did not seem to change anything.

I tried using pyplot.gca().set_rticks([...]) but that requires to know the ticks in advance, while I am interested in just setting the maximum number of them.

What else could I try in order to reduce the number of ticks (or circles)?

答:
You may indeed use ax.set_rticks() to specify the specific ticklabels you want, e.g.

```<code>ax.set_rticks([0.5, 1, 1.5, 2])
</code>```

as shown in his example on the matplotlib page.

In some cases this may be undesired and the usual locator parameters would be preferable. You can get the locator via ax.yaxis.get_major_locator().base and set the parameters via .set_params(). Here you want to change the nbins parameter,

```<code>ax.yaxis.get_major_locator().base.set_params(nbins=3)
</code>```

Complete example:

```<code>import numpy as np
import matplotlib.pyplot as plt

r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r

ax = plt.subplot(111, projection='polar')
ax.plot(theta, r)
ax.set_rmax(2)

ax.yaxis.get_major_locator().base.set_params(nbins=3)

ax.set_title("A line plot on a polar axis", va='bottom')
plt.show()
</code>```

Body:
I want a polar plot, but with a reduced number of radial (r dimension) ticks.  I already tried the suggested solutions from other questions, such as

pyplot.locator_params(axis='y', nticks=6)

but it did not seem to change anything.

I tried using pyplot.gca().set_rticks([...]) but that requires to know the ticks in advance, while I am interested in just setting the maximum number of them.

What else could I try in order to reduce the number of ticks (or circles)?

Body:
You may indeed use ax.set_rticks() to specify the specific ticklabels you want, e.g.

ax.set_rticks([0.5, 1, 1.5, 2])

as shown in his example on the matplotlib page.

In some cases this may be undesired and the usual locator parameters would be preferable. You can get the locator via ax.yaxis.get_major_locator().base and set the parameters via .set_params(). Here you want to change the nbins parameter,

ax.yaxis.get_major_locator().base.set_params(nbins=3)

Complete example:

import numpy as np
import matplotlib.pyplot as plt

r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r

ax = plt.subplot(111, projection='polar')
ax.plot(theta, r)
ax.set_rmax(2)

ax.yaxis.get_major_locator().base.set_params(nbins=3)

ax.set_title("A line plot on a polar axis", va='bottom')
plt.show()


问:
python script throwing an error that i can deal with
I have created the above script to remove unwanted genes from a database. It does work quite well if you only use it once but I re-run it, it giving me an error message such as:
shutil.Error: Destination path 'path/rejected_database_genes/gene_A.fa' already exists
And obviously it stops. I think that the problem arises when there are two or more genes in the file that needs to be removed.
Kind regards, and thanks for your help.

```<code>import glob, sys, os, shutil
from Bio import SeqIO, SearchIO
from Bio.SeqRecord import SeqRecord
import argparse

def help_function():
    print 'Hi'
parser = argparse.ArgumentParser()
parser.add_argument('-input_file', '-i',type=str,help='path_to_data')
opts = parser.parse_args()

def check_file_exists(filepath, file_description):
    if not os.path.exists(filepath):
        print("The " + file_description + " (" + filepath + ") does not exist")
        sys.exit(1)
    else:
        print file_description + " detected"

def remove_empty_files(alleles_files,destination):
    input_handle=open(alleles_files, 'r')
    gene_records=list(SeqIO.parse(input_handle, 'fasta'))

    for gene_record in gene_records:
        #filename=gene_record.id[0]
        #count=0
        if len(gene_record.seq)<5 or 'N'in gene_record.seq:
            print gene_record.id
        elif '-' in gene_record.seq:
            print gene_record.id
            #count+=1
            shutil.move(alleles_files, destination)

def main():
    destination=opts.input_file + '/rejected_database_genes'
    if os.path.exists(destination):
        print 'Folder already exits'
    else:
        os.makedirs(destination)
        print 'Folder has been created'
    files=glob.glob(opts.input_file+'/*.fa')
    #print files
    #sys.exit()
    for f in files:
        #print f
        #sys.exit()
        alleles_files=glob.glob(f)[0]
        #print alleles_files
        #sys.exit()
        remove_empty_files(alleles_files,destination)
    print 'Files have been removed'
main()
</code>```

答:
What I wanted was that the moment the script found to remove that file, and storage somewhere else so I can check it later. The problem I was having was that if in the same file there were two unwanted seq, it would through me and error telling me that the file already existed on destination, and stopped. So I managed to solve this problem by added an if statement. The corrected script is the one below:

```<code>import glob, sys, os, shutil
from Bio import SeqIO, SearchIO
from Bio.SeqRecord import SeqRecord
import argparse

def help_function():
    print 'Hi'
parser = argparse.ArgumentParser()
parser.add_argument('-input_file', '-i',type=str,help='path_to_data')
opts = parser.parse_args()

def check_file_exists(filepath, file_description):
    if not os.path.exists(filepath):
        print("The " + file_description + " (" + filepath + ") does not exist")
        sys.exit(1)
    else:
        print file_description + " detected"

def remove_empty_files(alleles_files,destination):
    input_handle=open(alleles_files, 'r')
    gene_records=list(SeqIO.parse(input_handle, 'fasta'))
    geneID_list=[]
    for gene_record in gene_records:
        filename=gene_record.id.split('_')
        geneID=filename[0]+'_'+filename[1]
        if len(gene_record.seq)<5 or 'N'in gene_record.seq:
            geneID_list.append(geneID)
            shutil.move(alleles_files, destination)
            print geneID_list
        #break
        if '-' in gene_record.seq:
            geneID_list.append(geneID)
            shutil.move(alleles_files, destination)
            print geneID_list
        #break
        if len(geneID_list) >0:
            break

def main():
    if len(sys.argv) <=1:
        parser.print_help()
        sys.exit()
    else:
        check_file_exists(opts.input_file, 'input_file')

    destination=opts.input_file + '/rejected_database_genes'
    if os.path.exists(destination):
        print 'Folder already exits'
    else:
        os.makedirs(destination)
        print 'Folder has been created'
    files=glob.glob(opts.input_file+'/*.fa')
    #print files
    #sys.exit()
    for f in files:
        #print f
        #sys.exit()
        alleles_files=glob.glob(f)[0]
        #print alleles_files
        #sys.exit()

        remove_empty_files(alleles_files,destination)
    print 'Files have been removed'
main()
</code>```

By adding the third "if" statement, the file is removed as soon as it finds an unwanted sequence, remove the file to destination, and move to check the next file.

Body:
I have created the above script to remove unwanted genes from a database. It does work quite well if you only use it once but I re-run it, it giving me an error message such as:
shutil.Error: Destination path 'path/rejected_database_genes/gene_A.fa' already exists
And obviously it stops. I think that the problem arises when there are two or more genes in the file that needs to be removed.
Kind regards, and thanks for your help.

import glob, sys, os, shutil
from Bio import SeqIO, SearchIO
from Bio.SeqRecord import SeqRecord
import argparse

def help_function():
    print 'Hi'
parser = argparse.ArgumentParser()
parser.add_argument('-input_file', '-i',type=str,help='path_to_data')
opts = parser.parse_args()

def check_file_exists(filepath, file_description):
    if not os.path.exists(filepath):
        print("The " + file_description + " (" + filepath + ") does not exist")
        sys.exit(1)
    else:
        print file_description + " detected"

def remove_empty_files(alleles_files,destination):
    input_handle=open(alleles_files, 'r')
    gene_records=list(SeqIO.parse(input_handle, 'fasta'))

    for gene_record in gene_records:
        #filename=gene_record.id[0]
        #count=0
        if len(gene_record.seq)<5 or 'N'in gene_record.seq:
            print gene_record.id
        elif '-' in gene_record.seq:
            print gene_record.id
            #count+=1
            shutil.move(alleles_files, destination)

def main():
    destination=opts.input_file + '/rejected_database_genes'
    if os.path.exists(destination):
        print 'Folder already exits'
    else:
        os.makedirs(destination)
        print 'Folder has been created'
    files=glob.glob(opts.input_file+'/*.fa')
    #print files
    #sys.exit()
    for f in files:
        #print f
        #sys.exit()
        alleles_files=glob.glob(f)[0]
        #print alleles_files
        #sys.exit()
        remove_empty_files(alleles_files,destination)
    print 'Files have been removed'
main()

Body:
What I wanted was that the moment the script found to remove that file, and storage somewhere else so I can check it later. The problem I was having was that if in the same file there were two unwanted seq, it would through me and error telling me that the file already existed on destination, and stopped. So I managed to solve this problem by added an if statement. The corrected script is the one below:

import glob, sys, os, shutil
from Bio import SeqIO, SearchIO
from Bio.SeqRecord import SeqRecord
import argparse

def help_function():
    print 'Hi'
parser = argparse.ArgumentParser()
parser.add_argument('-input_file', '-i',type=str,help='path_to_data')
opts = parser.parse_args()

def check_file_exists(filepath, file_description):
    if not os.path.exists(filepath):
        print("The " + file_description + " (" + filepath + ") does not exist")
        sys.exit(1)
    else:
        print file_description + " detected"

def remove_empty_files(alleles_files,destination):
    input_handle=open(alleles_files, 'r')
    gene_records=list(SeqIO.parse(input_handle, 'fasta'))
    geneID_list=[]
    for gene_record in gene_records:
        filename=gene_record.id.split('_')
        geneID=filename[0]+'_'+filename[1]
        if len(gene_record.seq)<5 or 'N'in gene_record.seq:
            geneID_list.append(geneID)
            shutil.move(alleles_files, destination)
            print geneID_list
        #break
        if '-' in gene_record.seq:
            geneID_list.append(geneID)
            shutil.move(alleles_files, destination)
            print geneID_list
        #break
        if len(geneID_list) >0:
            break

def main():
    if len(sys.argv) <=1:
        parser.print_help()
        sys.exit()
    else:
        check_file_exists(opts.input_file, 'input_file')

    destination=opts.input_file + '/rejected_database_genes'
    if os.path.exists(destination):
        print 'Folder already exits'
    else:
        os.makedirs(destination)
        print 'Folder has been created'
    files=glob.glob(opts.input_file+'/*.fa')
    #print files
    #sys.exit()
    for f in files:
        #print f
        #sys.exit()
        alleles_files=glob.glob(f)[0]
        #print alleles_files
        #sys.exit()

        remove_empty_files(alleles_files,destination)
    print 'Files have been removed'
main()

By adding the third "if" statement, the file is removed as soon as it finds an unwanted sequence, remove the file to destination, and move to check the next file.


问:
React native redux map state to props not working
I am new to react-native and I am trying to implement a simple sign  up functionality using react-redux. For some reasons , mapping the state to props in connect is not working.

Below is my code :

SignUp.js ( Component )

```<code>import React from 'react';
import { View, Text , TouchableOpacity , TextInput } from 'react-native';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as signUpActions from "../actions/SignUpActions";

class SignUp extends React.Component {

  constructor(){
    super();
    this.state = {
      name : '',
      password : '',
    };
  }

  saveUser(){
      let user = {};
      user.name = this.state.name;
      user.password = this.state.password;
      this.props.registerUser(user);
  }

  static navigationOptions = {
    title : 'Sign Up',
  };

  render(){
    return (
      <View>
        <TextInput
          placeholder="Username"
          onChangeText={(text) => this.setState({name : text})}
          />
         <TextInput
            placeholder="Password"
            onChangeText={(text) => this.setState({password : text})}
         />
         <TouchableOpacity onPress = {() => this.saveUser()} >
           <Text>DONE</Text>
         </TouchableOpacity>
      </View>
    );
  }
}

export default connect(
  state => ({
      user : state.user
  }),
  dispatch => bindActionCreators(signUpActions, dispatch)
)(SignUp);
</code>```

SignUpAction.js

```<code>function storeUser(user) {
    return {
        type : 'REGISTER_USER',
        payload : user,
    };
};

export function registerUser(user) {
    return function (dispatch, getState) {
        fetch(<the-url>)
            .then((response) => {return response.json()})
            .then((responseData) => dispatch(storeUser(responseData)))
            .catch((err) => console.log(err));
    };
};
</code>```

SignUpReducer.js

```<code>const initialState = {
    data : {},
};

export default function signUpReducer(state = initialState, action) {

    console.log(action.payload)
    //This gives {id:26 , name : "xyz" ,password:"pass"}

    switch (action.type) {
        case 'REGISTER_USER' :
            return {
                ...state ,
                user : action.payload
            }
        default :
            return state;
    }
}
</code>```

This my root reducer

```<code>export default function getRootReducer(navReducer) {
    return combineReducers({
        nav: navReducer,
        signUpReducer : signUpReducer,
    });
}
</code>```

The register user function is being called. And the fetch request is also successfully executed over a network. It returns the same user object back after storing it in a database. It dispatches to the storeUser function as well. The reducer is getting called as well.

But , for some reasons , the state is not mapped to the props inside the connect. this.props.user returns undefined.

I must be doing something wrong in this but I am not able to figure it out. Based on what I have seen till now when we dispatch any action using bindActionCreators the result from reducer needs to be mapped to component's props using connect. Please correct me if wrong.

Please help me with this issue.

答:
From your store defination,

```<code>return combineReducers({
        nav: navReducer,
        signUpReducer : signUpReducer,
    });
</code>```

You defined the key signUpReducer for  your SignUp component state.
In order to access the state of this component,you should use this key followed by the state name.

The correct way to access user is :

```<code> export default connect(
      state => ({
          user : state.signUpReducer.user
      })
</code>```

//use signUpReducer key

Body:
I am new to react-native and I am trying to implement a simple sign  up functionality using react-redux. For some reasons , mapping the state to props in connect is not working.

Below is my code :

SignUp.js ( Component )

import React from 'react';
import { View, Text , TouchableOpacity , TextInput } from 'react-native';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as signUpActions from "../actions/SignUpActions";

class SignUp extends React.Component {

  constructor(){
    super();
    this.state = {
      name : '',
      password : '',
    };
  }

  saveUser(){
      let user = {};
      user.name = this.state.name;
      user.password = this.state.password;
      this.props.registerUser(user);
  }

  static navigationOptions = {
    title : 'Sign Up',
  };

  render(){
    return (
      <View>
        <TextInput
          placeholder="Username"
          onChangeText={(text) => this.setState({name : text})}
          />
         <TextInput
            placeholder="Password"
            onChangeText={(text) => this.setState({password : text})}
         />
         <TouchableOpacity onPress = {() => this.saveUser()} >
           <Text>DONE</Text>
         </TouchableOpacity>
      </View>
    );
  }
}

export default connect(
  state => ({
      user : state.user
  }),
  dispatch => bindActionCreators(signUpActions, dispatch)
)(SignUp);

SignUpAction.js

function storeUser(user) {
    return {
        type : 'REGISTER_USER',
        payload : user,
    };
};

export function registerUser(user) {
    return function (dispatch, getState) {
        fetch(<the-url>)
            .then((response) => {return response.json()})
            .then((responseData) => dispatch(storeUser(responseData)))
            .catch((err) => console.log(err));
    };
};

SignUpReducer.js

const initialState = {
    data : {},
};

export default function signUpReducer(state = initialState, action) {

    console.log(action.payload)
    //This gives {id:26 , name : "xyz" ,password:"pass"}

    switch (action.type) {
        case 'REGISTER_USER' :
            return {
                ...state ,
                user : action.payload
            }
        default :
            return state;
    }
}

This my root reducer

export default function getRootReducer(navReducer) {
    return combineReducers({
        nav: navReducer,
        signUpReducer : signUpReducer,
    });
}

The register user function is being called. And the fetch request is also successfully executed over a network. It returns the same user object back after storing it in a database. It dispatches to the storeUser function as well. The reducer is getting called as well.

But , for some reasons , the state is not mapped to the props inside the connect. this.props.user returns undefined.

I must be doing something wrong in this but I am not able to figure it out. Based on what I have seen till now when we dispatch any action using bindActionCreators the result from reducer needs to be mapped to component's props using connect. Please correct me if wrong.

Please help me with this issue.

Body:
From your store defination,

return combineReducers({
        nav: navReducer,
        signUpReducer : signUpReducer,
    });

You defined the key signUpReducer for  your SignUp component state.
In order to access the state of this component,you should use this key followed by the state name.

The correct way to access user is :

 export default connect(
      state => ({
          user : state.signUpReducer.user
      })

//use signUpReducer key


答:
try this </p>

```<code>var games = ["game_1", "game_2","game_3"]

var players= [{name:"steve"},{name:"sparrow"},{name:"captain"}]

var incomingData= [{game_1:"basketball"},{game_2:"badminton"},{game_3:"pingpong"}]

//change format as shown below:

var reformat=[ {name:"steve",game:"basketball"},{name:"steve",game:"badminton"},{name:"steve",game:"pingpong"}]

 games.map((game,i)=>{
               players[i].game= incomingData[i][game];
    })

console.log(players)
}
</code>```

Title: Error with reformatting the way data has been passed into a function

Body:
try this

var games = ["game_1", "game_2","game_3"]

var players= [{name:"steve"},{name:"sparrow"},{name:"captain"}]

var incomingData= [{game_1:"basketball"},{game_2:"badminton"},{game_3:"pingpong"}]

//change format as shown below:

var reformat=[ {name:"steve",game:"basketball"},{name:"steve",game:"badminton"},{name:"steve",game:"pingpong"}]

 games.map((game,i)=>{
               players[i].game= incomingData[i][game];
    })

console.log(players)
}


问:
Create BE Initiative, BE Feature and CPM Feature using Rally Rest Client in Java
We are trying to automate the project migration from one Rally workspace to other. Everything seems to work fine like we are able to migrate project and related releases/iterations/userstories/tasks from one workspace to another workspace.
But while trying to migrate BE Initiative/BE Feature/CPM Feature we are getting some exception related to Null Pointer exception but the error we are getting in Response doesn't seem to give much info.

A sample of code is -

```<code>    String oldProjectObjectId = "12345";
    String  newProjectObjectId = "67890";

    String oldRallyWorkspaceObjectId = "32145";
    String newRallyWorkspaceObjectId = "67894";
    QueryResponse beInitiativeResponse = queryRally("portfolioitem/beinitiative", "/project/"+this.oldProjectObjectId, "/workspace/"+this.oldRallyWorkspaceObjectId);

    int beInitiativeCount = beInitiativeResponse.getTotalResultCount();

    if(beInitiativeCount >0){

        JsonArray initiativeArray = beInitiativeResponse.getResults();

        for(int i=0; i< initiativeArray.size();i++){

            JsonObject beInitiativeObject = initiativeArray.get(i).getAsJsonObject();

            String oldBeInitiativeObjectId = beInitiativeObject.get("ObjectID").getAsString();
            String oldBeInitiativeName = beInitiativeObject.get("_refObjectName").getAsString();

            String owner = getObjectId(beInitiativeObject, "Owner");

            JsonObject BeInitiativeCreateObject = getJsonObject(oldBeInitiativeName, "/project/"+this.newProjectObjectId, "/workspace/"+this.newRallyWorkspaceObjectId, owner);
            CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/beinitiative", BeInitiativeCreateObject);

            if(beInitiativeCreateResponse.wasSuccessful()){
                String newBeInitiativeObjectId = beInitiativeCreateResponse.getObject().get("ObjectID").getAsString();

                String mapKey = oldBeInitiativeObjectId;
                String mapValue= newBeInitiativeObjectId;
                this.beInitiativesHashMap.put(mapKey, mapValue);
            }
            else{
                String[] errorList;
                errorList = beInitiativeCreateResponse.getErrors();
                for (int j = 0; j < errorList.length; j++) {
                    System.out.println(errorList[j]);
                }
            }

        }
    }
</code>```

queryRally and createInRally functions use Rally rest client to fetch and create the required projects and associated attributes like releases, iterations etc.

After executing CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/beinitiative", BeInitiativeCreateObject); when it's trying to execute if(beInitiativeCreateResponse.wasSuccessful()) it is instead going to else block and thus printing the below mentioned error.

An unexpected error has occurred.

We have recorded this error and will begin to investigate it.  In the meantime, if you would like to speak with our Support Team, please reference the information below:

java.lang.NullPointerException

2017-12-05 11:01 AM PST America/Los_Angeles

But the important point that is when trying to migrate projects and it's related attributes like release/iterations etc. withing same Rally workspace the above piece of code works just fine.

Update1:

While analysing the issue I made the following observations -

The workspace in which I am trying to create the BeInitiative doesn't have BEinitiative, Be Feature, CPM Feature options in Portfolio items dropdown. Rather it has Theme, Initiative and Feature options in it.
Therefore, I think I was getting the previouly mentioned error. Now I made the following changes to the code.

```<code>CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/theme", themeCreateObject);
</code>```

So now instead of creating the BEInitiative I am trying to create the theme only in new workspace but getting the following error -

Requested type name \"/portfolioitem/theme\" is unknown.

The object that i am passing to CreateResponse function is -

```<code>{"Name":"xyz","Project":"/project/1804","Workspace":"/workspace/139"}
</code>```

Also code for createInRally function is as mentioned below -

```<code>public CreateResponse createInRally( String query, JsonObject object) throws IOException{

    CreateRequest createRequest = new CreateRequest(query, object);

    CreateResponse createResponse = restApi.create(createRequest);

    return createResponse;
}
</code>```

答: So this is definitely an error in the web services api.  You should never get 500 responses with an unhandled nullpointer.  My initial guess is that when you're creating your new object some field on it is still referencing an object in the old workspace, and when we try to correctly hook up all the associations it fails to read one of those objects in the new workspace.  Can you provide some more information about what your actual object you're sending to create looks like?  Specifically what object relationships are you including (that may not be valid in the new workspace)?</p>

Body:
We are trying to automate the project migration from one Rally workspace to other. Everything seems to work fine like we are able to migrate project and related releases/iterations/userstories/tasks from one workspace to another workspace.
But while trying to migrate BE Initiative/BE Feature/CPM Feature we are getting some exception related to Null Pointer exception but the error we are getting in Response doesn't seem to give much info.

A sample of code is -

    String oldProjectObjectId = "12345";
    String  newProjectObjectId = "67890";

    String oldRallyWorkspaceObjectId = "32145";
    String newRallyWorkspaceObjectId = "67894";
    QueryResponse beInitiativeResponse = queryRally("portfolioitem/beinitiative", "/project/"+this.oldProjectObjectId, "/workspace/"+this.oldRallyWorkspaceObjectId);

    int beInitiativeCount = beInitiativeResponse.getTotalResultCount();

    if(beInitiativeCount >0){

        JsonArray initiativeArray = beInitiativeResponse.getResults();

        for(int i=0; i< initiativeArray.size();i++){

            JsonObject beInitiativeObject = initiativeArray.get(i).getAsJsonObject();

            String oldBeInitiativeObjectId = beInitiativeObject.get("ObjectID").getAsString();
            String oldBeInitiativeName = beInitiativeObject.get("_refObjectName").getAsString();

            String owner = getObjectId(beInitiativeObject, "Owner");

            JsonObject BeInitiativeCreateObject = getJsonObject(oldBeInitiativeName, "/project/"+this.newProjectObjectId, "/workspace/"+this.newRallyWorkspaceObjectId, owner);
            CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/beinitiative", BeInitiativeCreateObject);

            if(beInitiativeCreateResponse.wasSuccessful()){
                String newBeInitiativeObjectId = beInitiativeCreateResponse.getObject().get("ObjectID").getAsString();

                String mapKey = oldBeInitiativeObjectId;
                String mapValue= newBeInitiativeObjectId;
                this.beInitiativesHashMap.put(mapKey, mapValue);
            }
            else{
                String[] errorList;
                errorList = beInitiativeCreateResponse.getErrors();
                for (int j = 0; j < errorList.length; j++) {
                    System.out.println(errorList[j]);
                }
            }

        }
    }

queryRally and createInRally functions use Rally rest client to fetch and create the required projects and associated attributes like releases, iterations etc.

After executing CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/beinitiative", BeInitiativeCreateObject); when it's trying to execute if(beInitiativeCreateResponse.wasSuccessful()) it is instead going to else block and thus printing the below mentioned error.

An unexpected error has occurred.

We have recorded this error and will begin to investigate it.  In the meantime, if you would like to speak with our Support Team, please reference the information below:

java.lang.NullPointerException

2017-12-05 11:01 AM PST America/Los_Angeles

But the important point that is when trying to migrate projects and it's related attributes like release/iterations etc. withing same Rally workspace the above piece of code works just fine.

Update1:

While analysing the issue I made the following observations -

The workspace in which I am trying to create the BeInitiative doesn't have BEinitiative, Be Feature, CPM Feature options in Portfolio items dropdown. Rather it has Theme, Initiative and Feature options in it.
Therefore, I think I was getting the previouly mentioned error. Now I made the following changes to the code.

CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/theme", themeCreateObject);

So now instead of creating the BEInitiative I am trying to create the theme only in new workspace but getting the following error -

Requested type name \"/portfolioitem/theme\" is unknown.

The object that i am passing to CreateResponse function is -

{"Name":"xyz","Project":"/project/1804","Workspace":"/workspace/139"}

Also code for createInRally function is as mentioned below -

public CreateResponse createInRally( String query, JsonObject object) throws IOException{

    CreateRequest createRequest = new CreateRequest(query, object);

    CreateResponse createResponse = restApi.create(createRequest);

    return createResponse;
}


问:
Git merge giving unexpected results

We're trying to merge two Git branches.

This is the merge commit.

This is the file link of the source commit.
This is the file link of the target commit.

Based on the commit graph: link

the closes common ancestor is commit 01886ab, right? Well it one has the following version of the file.

My understanding of git merge is that merging "A" into "B" with base "A" should output "B". Based on that, I have problems with the comments: "The following two/three mappings are symmetrical..." (lines 30/31/32).

In the base file, there is "three". The source file has "two" and the target "three". According to my understanding, it should merge to "two".

It merged to "three" (merge file).

Thank you!!

答: When I ran this merge locally I got a merge conflict.  The conflict was because in commit 6d8450ab64821a280aa0e2d20c42e4929d028812, which is an ancestor of db30386422f648a3e3382f5648e987bfc178d93d, you added whitespace above the line The following...; and in commit 333d343af1ac436eff598231957e9705e4121dab, an ancestor of 2c0135217daa3fefbbc7e73a6ee94682c33a9b81, you changed three to two.  Furthermore, if you checkout the merge commit 7f46cd43102b1f63bf0a5416a376b7c880313b1d and run git blame contracts/DutchExchange.sol, you'll see on line 32 that the merge commit introduced a newline.  So to answer your question, it looks like it merged to three because that's how you resolved the merge conflict.

Title: Git merge giving unexpected results


问:
sql test condition if failed move to next person
I am trying to get the urns that don't have a status_mvf  = 88

```<code>status_mvf    urn        desc        date
88            104        no show     2017-03-06
9             104        late        2017-03-07
2             104        on time     2017-03-08
2             210        on time     2017-03-06
2             210        on time     2017-03-07
9             320        late        2017-03-06

SELECT
    a.Status_Mvf,
    p.URN,
    v.ADMIT_DATE

FROM APPOINTMENT
WHERE  Status_Mvf <> '88'

--group by p.urn,

ORDER BY URN, STATUS_MVF
</code>```

Desired result - no urn 104 because it had an 88

```<code>status_mvf   urn       desc      date
2            210       on time   2017-03-06
2            210       on time   2017-03-07
9            320       late      2017-03-06
</code>```

答:
You can use not exists:

```<code>select a.*
from appointment a
where not exists (select 1 from appointment a2 where a2.urn = a.urn and a2.status_mvf = '88');
</code>```

Body:
I am trying to get the urns that don't have a status_mvf  = 88

status_mvf    urn        desc        date
88            104        no show     2017-03-06
9             104        late        2017-03-07
2             104        on time     2017-03-08
2             210        on time     2017-03-06
2             210        on time     2017-03-07
9             320        late        2017-03-06

SELECT
    a.Status_Mvf,
    p.URN,
    v.ADMIT_DATE

FROM APPOINTMENT
WHERE  Status_Mvf <> '88'

--group by p.urn,

ORDER BY URN, STATUS_MVF

Desired result - no urn 104 because it had an 88

status_mvf   urn       desc      date
2            210       on time   2017-03-06
2            210       on time   2017-03-07
9            320       late      2017-03-06

Body:
You can use not exists:

select a.*
from appointment a
where not exists (select 1 from appointment a2 where a2.urn = a.urn and a2.status_mvf = '88');


问:
How to see a result of git fetch?
I fetch a branch from a remote repository. How can I see that it has worked successfully? I expect that after this fetch I should have a (copy of) remote branch locally but I cannot find it (neither with git branch nor git branch -r nor git status). To me it looks like nothing has happened.

答:
After you fetched, to see what remote "master" has compared to your local "master", you ask Git to show you exactly this:

```<code>git log origin/master ^master
</code>```

which means «all commits reachable from "origin/master" which do not include commits reachable from "master"» or, alternatively

```<code>git log master..origin/master
</code>```

also, git diff master origin/master
 seems to address the question very simply I think.

Title: How to see a result of git fetch?

Body:
After you fetched, to see what remote "master" has compared to your local "master", you ask Git to show you exactly this:

git log origin/master ^master

which means «all commits reachable from "origin/master" which do not include commits reachable from "master"» or, alternatively

git log master..origin/master

also, git diff master origin/master
 seems to address the question very simply I think.


问:
search by name in sql table - clustered indexing
I have table (Products) with column (barcode PK, name) I want efficient way to search by name, I read the clustered indexing speed the search? But how can I use it, can anyone explain clustered indexing?

答:
A clustered index directs SQL to physically store the data in the ordinal position of the index value. So if you have 5 rows with the same clustered value, they are all store sequentially (a heap table) next to one another. SQL does not need to scan an entire table to find matching values. You may lose minor INSERT performance, but certain SELECT queries that use the clustered index field will be dramatically faster.

If you ran this query

```<code>SELECT * FROM MyTable WHERE ClusteredIndexField = 'A'
</code>```

SQL knows that all rows with an "A" value in the clustered field are all together. Once it finds the first matching row, it iterates the next rows. SQL can reliably know not to search any longer as it knows no more rows can possibly match the condition.

http://www.sqlpassion.at/archive/2016/03/29/clustered-indexes-advantages-disadvantages/

Body:
A clustered index directs SQL to physically store the data in the ordinal position of the index value. So if you have 5 rows with the same clustered value, they are all store sequentially (a heap table) next to one another. SQL does not need to scan an entire table to find matching values. You may lose minor INSERT performance, but certain SELECT queries that use the clustered index field will be dramatically faster.

If you ran this query

SELECT * FROM MyTable WHERE ClusteredIndexField = 'A'

SQL knows that all rows with an "A" value in the clustered field are all together. Once it finds the first matching row, it iterates the next rows. SQL can reliably know not to search any longer as it knows no more rows can possibly match the condition.

http://www.sqlpassion.at/archive/2016/03/29/clustered-indexes-advantages-disadvantages/


问:
Why this HashMap not formatted correctly in Jersey/Tomcat?
I'm testing Jersey, I wanted to mack a mock endpoint that produces this JSON object

```<code>{
   "Flight1" : 757,
   "Flight2" : 107,
   "Flight3" : 637,
}
</code>```

so I've written written this resource:

```<code>@GET
@Path("myjson")
@Produces(MediaType.APPLICATION_JSON)
public String getMyJson(@QueryParam ("test1") String lat, @QueryParam("test2") String lng) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("Flight 1", 765);
    map.put("Flight 2", 657);
    map.put("Flight 3", 908);
    return map.toString();
}
</code>```

But then I get this response when I call /myjson

{
       Flight 1=765,
       Flight 2=657,
       Flight 3=908
  }

Jersey already knows which element is a String and which element is an Integer, yet it format then as if they're all numbers.
Also the Json as it stands can not be formatted by the "pretty" formatter, and I believe this makes parsing it difficult by http clients.

So my question are:

Why is this happening?

How to avoid it and write simple mock JSON object for testing that is correctly formatted

答:
Why is this happening?

Because you are only making a toString of your HashMap.
Ex.

```<code>    HashMap<String,String> stringStringHashMap = new HashMap<String, String>();
    stringStringHashMap.put("a","b");
    stringStringHashMap.put("b","b");
    stringStringHashMap.put("c","b");
</code>```

Will print  {b=b, c=b, a=b}

How to avoid it and write simple mock JSON object for testing that is
  correctly formatted

You can do this by using a lot of libraries(Gson, Jackson, JsonSimple,etc).
As this already answered what you want to make HashMap to Json

Body:
I'm testing Jersey, I wanted to mack a mock endpoint that produces this JSON object

{
   "Flight1" : 757,
   "Flight2" : 107,
   "Flight3" : 637,
}

so I've written written this resource:

@GET
@Path("myjson")
@Produces(MediaType.APPLICATION_JSON)
public String getMyJson(@QueryParam ("test1") String lat, @QueryParam("test2") String lng) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("Flight 1", 765);
    map.put("Flight 2", 657);
    map.put("Flight 3", 908);
    return map.toString();
}

But then I get this response when I call /myjson

{
       Flight 1=765,
       Flight 2=657,
       Flight 3=908
  }

Jersey already knows which element is a String and which element is an Integer, yet it format then as if they're all numbers.
Also the Json as it stands can not be formatted by the "pretty" formatter, and I believe this makes parsing it difficult by http clients.

So my question are:

Why is this happening?

How to avoid it and write simple mock JSON object for testing that is correctly formatted

Body:
Why is this happening?

Because you are only making a toString of your HashMap.
Ex.

    HashMap<String,String> stringStringHashMap = new HashMap<String, String>();
    stringStringHashMap.put("a","b");
    stringStringHashMap.put("b","b");
    stringStringHashMap.put("c","b");

Will print  {b=b, c=b, a=b}

How to avoid it and write simple mock JSON object for testing that is
  correctly formatted

You can do this by using a lot of libraries(Gson, Jackson, JsonSimple,etc).
As this already answered what you want to make HashMap to Json


问:
Crashlytics NDK symbols and Gradle tasks
I have a question that mostly relates to gradle.

I'm using Crashlytics to report NDK crashes in my Android app.
I have a task in build.gradle that calls ndk-build and compiles the cpp files into an .so file.
At the end of this task I want to call a task that uploads generated symbols mapping to Crashlytics.

After installing the Fabric plugin in Android Studio, I saw there are some new tasks that were added to the Gradle tab. One of them is
crashlyticsUploadSymbols[buildType][flavour] where buildType and flavour indicate which buildtype and flavour is currently selected.

This task does seem to upload a symbols file.

My question is,
Is it possible to call this task from within build.gradle?
Currently I use a manual call in Android Studio's terminal tab in the form of:

./gradlew crashlyticsUploadSymbols[buildType][flavour]

Is it possible to call this task somehow from within build.gradle?

To call this task I use finalizedBy at the end of the buildNdk task, so once buildNdk has finished, the upload task will execute.

Also very important, how can I get the current buildType and flavour so I am able to add it to the crashlyticsUploadSymbols call?

Thank you!

答:
The following did the job for me:</p>

```<code>android {
...
    afterEvaluate {
        assembleDebug.finalizedBy(crashlyticsUploadSymbolsDebug)
        assembleRelease.finalizedBy(crashlyticsUploadSymbolsRelease)
    }
}
</code>```

Body:
The following did the job for me:

android {
...
    afterEvaluate {
        assembleDebug.finalizedBy(crashlyticsUploadSymbolsDebug)
        assembleRelease.finalizedBy(crashlyticsUploadSymbolsRelease)
    }
}


问:
how to create a selenium/standalone-chrome image with changeable port (the 4444)
I'm was wondering how can I pass a different port number as argument when I'm running the selenium container instead of the default port(4444)

Usually I'm using:

```<code>docker run --shm-size=2G -d --net=host -e TZ=UTC -e SCREEN_WIDTH=1920 -e SCREEN_HEIGHT=1080  selenium/standalone-chrome:3.7.0
</code>```

Is it possible to do so with the current selenium image or do I need to build a selenium image of my own and if so how to create that kind of image?

答:
You can bind port with -p

```<code>docker run -d -p 4444:4444 --name selenium-hub selenium/hub:3.8.1-aluminum
</code>```

But if you want change the port inside container I think you must modify sources of image.

Body:
I'm was wondering how can I pass a different port number as argument when I'm running the selenium container instead of the default port(4444)

Usually I'm using:

docker run --shm-size=2G -d --net=host -e TZ=UTC -e SCREEN_WIDTH=1920 -e SCREEN_HEIGHT=1080  selenium/standalone-chrome:3.7.0

Is it possible to do so with the current selenium image or do I need to build a selenium image of my own and if so how to create that kind of image?

Body:
You can bind port with -p

docker run -d -p 4444:4444 --name selenium-hub selenium/hub:3.8.1-aluminum

But if you want change the port inside container I think you must modify sources of image.