问:
SSRS Report Duplicates Flag
I'm presently making a report on ssrs from a Great Plains Dynamics DB.

It's a pretty simple report with a few columns. Everything works fine but in GP, when creating an Invoice or a Return bill, sometimes GP is gonna give the same Bill ID. It doesn't really shows as a duplicated because for GP, an Invoice and a Return can/could have the same ID because they are not the same type. Don't ask me why..

So for my report, when I start a research from a multiples values parameters with my SopNumber (Bill ID) it gives me the right information. But now I would like to have a flag on those information that equals the bill ID and has Invoice and Return at the same time.

Since it is normal for GP to have 2 different type of document for the same ID, I cannot ask my report to remove the return or the invoice cause in different case, an Invoice could be the important document and in an other case, the return.

In my tablix, I do not show the Bill ID, because I don't need the information except when there is this "duplication".

I would also like after the flag (line highlited), that on the top of my report, a sentence shows something like : "Those documents are in conflict : 000123123". So with this information showing my ID, I can now go in my multiple values parameter and remove this number.

I wanna achieve those 2 flags because I'm making a calcul from my documents amount and if those 2 would be there, it would make my calcul wrong.

I hope you guys can help me. If so, thank you very much in advance!

I worked on a couple of different expressions but never got the result I wanted. Use previous statement and equals but couldn't find how to make it look like is equals to Invoice and Return and SopNumber equals the same.

```<code>select CASE SOP10200.SOPTYPE
                WHEN 1 THEN 'QUOTE'
                WHEN 2 THEN 'ORDER'
                WHEN 3 THEN 'INVOICE'
                WHEN 4 THEN 'RETURN'
                WHEN 5 THEN 'BACK ORDER'
                WHEN 6 THEN 'FULLFILLMENT ORDER'
                END AS SOPTYPE,
                sop10200.SLPRSNID,
                sop10200.XTNDPRCE as ExtendedPrice,
                sop10200.SOPNUMBE,
                iv00101.ITMCLSCD as FAMILYCLASS,
                sop10100.DOCDATE

from sop10200
left join iv00101 on sop10200.ITEMNMBR = iv00101.ITEMNMBR
left join sop10100 on sop10200.SOPNUMBE = sop10100.SOPNUMBE

WHERE SOP10100.DOCDATE BETWEEN '2018-01-01 00:00:00.000' AND '2035-01-01 00:00:00.000'
union all

select  CASE SOP30300.SOPTYPE
                WHEN 1 THEN 'QUOTE'
                WHEN 2 THEN 'ORDER'
                WHEN 3 THEN 'INVOICE'
                WHEN 4 THEN 'RETURN'
                WHEN 5 THEN 'BACK ORDER'
                WHEN 5 THEN 'FULLFILLMENT ORDER'
                END AS SOPTYPE,
                sop30300.SLPRSNID,
                sop30300.XTNDPRCE as ExtendedPrice,
                sop30300.SOPNUMBE,
                iv00101.ITMCLSCD as FAMILYCLASS,
                sop30200.DOCDATE

from sop30300
left join iv00101 on sop30300.ITEMNMBR = iv00101.ITEMNMBR
left join sop30200 on sop30300.SOPNUMBE = sop30200.SOPNUMBE

WHERE SOP30200.DOCDATE BETWEEN '2018-01-01 00:00:00.000' AND '2035-01-01 00:00:00.000'

ORDER BY SOPNUMBE desc
</code>```

答:
Correct me if I'm wrong, but it sounds like you want a way to see if there is a duplicate record for the report and use that in a calculation?

You could do a subquery to retrieve a count, and if that is more than 1 than you have a duplicate record

EDIT:

```<code>SELECT *, (IF
    (SELECT Count(S1.SOPTYPE) FROM sop10200 S1 WHERE T1.BillID = S1.BillID ) > 1 THEN "Duplicate " ELSE "" END) AS DuplicateCheck
FROM sop10200 T1
</code>```

The above solution will give you a value you can use on each page to report whether or not that it has a duplicate BillID.

Title: SSRS Report Duplicates Flag

Body:
I'm presently making a report on ssrs from a Great Plains Dynamics DB.

It's a pretty simple report with a few columns. Everything works fine but in GP, when creating an Invoice or a Return bill, sometimes GP is gonna give the same Bill ID. It doesn't really shows as a duplicated because for GP, an Invoice and a Return can/could have the same ID because they are not the same type. Don't ask me why..

So for my report, when I start a research from a multiples values parameters with my SopNumber (Bill ID) it gives me the right information. But now I would like to have a flag on those information that equals the bill ID and has Invoice and Return at the same time.

Since it is normal for GP to have 2 different type of document for the same ID, I cannot ask my report to remove the return or the invoice cause in different case, an Invoice could be the important document and in an other case, the return.

In my tablix, I do not show the Bill ID, because I don't need the information except when there is this "duplication".

I would also like after the flag (line highlited), that on the top of my report, a sentence shows something like : "Those documents are in conflict : 000123123". So with this information showing my ID, I can now go in my multiple values parameter and remove this number.

I wanna achieve those 2 flags because I'm making a calcul from my documents amount and if those 2 would be there, it would make my calcul wrong.

I hope you guys can help me. If so, thank you very much in advance!

I worked on a couple of different expressions but never got the result I wanted. Use previous statement and equals but couldn't find how to make it look like is equals to Invoice and Return and SopNumber equals the same.

select CASE SOP10200.SOPTYPE
                WHEN 1 THEN 'QUOTE'
                WHEN 2 THEN 'ORDER'
                WHEN 3 THEN 'INVOICE'
                WHEN 4 THEN 'RETURN'
                WHEN 5 THEN 'BACK ORDER'
                WHEN 6 THEN 'FULLFILLMENT ORDER'
                END AS SOPTYPE,
                sop10200.SLPRSNID,
                sop10200.XTNDPRCE as ExtendedPrice,
                sop10200.SOPNUMBE,
                iv00101.ITMCLSCD as FAMILYCLASS,
                sop10100.DOCDATE

from sop10200
left join iv00101 on sop10200.ITEMNMBR = iv00101.ITEMNMBR
left join sop10100 on sop10200.SOPNUMBE = sop10100.SOPNUMBE

WHERE SOP10100.DOCDATE BETWEEN '2018-01-01 00:00:00.000' AND '2035-01-01 00:00:00.000'
union all

select  CASE SOP30300.SOPTYPE
                WHEN 1 THEN 'QUOTE'
                WHEN 2 THEN 'ORDER'
                WHEN 3 THEN 'INVOICE'
                WHEN 4 THEN 'RETURN'
                WHEN 5 THEN 'BACK ORDER'
                WHEN 5 THEN 'FULLFILLMENT ORDER'
                END AS SOPTYPE,
                sop30300.SLPRSNID,
                sop30300.XTNDPRCE as ExtendedPrice,
                sop30300.SOPNUMBE,
                iv00101.ITMCLSCD as FAMILYCLASS,
                sop30200.DOCDATE

from sop30300
left join iv00101 on sop30300.ITEMNMBR = iv00101.ITEMNMBR
left join sop30200 on sop30300.SOPNUMBE = sop30200.SOPNUMBE

WHERE SOP30200.DOCDATE BETWEEN '2018-01-01 00:00:00.000' AND '2035-01-01 00:00:00.000'

ORDER BY SOPNUMBE desc

Body:
Correct me if I'm wrong, but it sounds like you want a way to see if there is a duplicate record for the report and use that in a calculation?

You could do a subquery to retrieve a count, and if that is more than 1 than you have a duplicate record

EDIT:

SELECT *, (IF
    (SELECT Count(S1.SOPTYPE) FROM sop10200 S1 WHERE T1.BillID = S1.BillID ) > 1 THEN "Duplicate " ELSE "" END) AS DuplicateCheck
FROM sop10200 T1

The above solution will give you a value you can use on each page to report whether or not that it has a duplicate BillID.


来源: stackexchange

问:
What is the best way to format strings in Python?
I am currently reading books and taking online courses on Python. There are numerous ways we can format strings in python, but I was wondering what is the best way.

For example if we have this two ways of formating strings, which one would be better to use? Does it even make a difference?

```<code>    print("I am %d years old." % (age))
</code>```

or

```<code>    print("I am {} years old".format(age))
</code>```

or maybe even

```<code>    print("I am " + str(age) + " years old")
</code>```

Well anyway, it's more a theoretical question. I am new to coding, but I know some functions or methods are more memory consuming than others, so I am trying to figure out if maybe one of these is a better practice.

答:
I wouldn't presume that there is any best way to tackle string formatting, I'd say it depends on how much a developer wants his code to be readable.

The formatting with % is an old way, but backwards compatible.

Using the .format(_) function is the recommended way going forward.

Concatenation of strings together is usually very hard to read or to grasp as to what the final string is supposed to be.

I personally always use .format option, also because it allows to name the variables inside the curly brackets. For example

```<code>from datetime import datetime
now = datetime.now()
time_now = "Time: '{time}'".format(time=now)
</code>```

In this way it gives a more general variable name inside the string, so that everybody knows what the input variable is about.

ContentLicense: CC BY-SA 4.0

Body:
I am currently reading books and taking online courses on Python. There are numerous ways we can format strings in python, but I was wondering what is the best way.

For example if we have this two ways of formating strings, which one would be better to use? Does it even make a difference?

    print("I am %d years old." % (age))

or

    print("I am {} years old".format(age))

or maybe even

    print("I am " + str(age) + " years old")

Well anyway, it's more a theoretical question. I am new to coding, but I know some functions or methods are more memory consuming than others, so I am trying to figure out if maybe one of these is a better practice.

Body:
I wouldn't presume that there is any best way to tackle string formatting, I'd say it depends on how much a developer wants his code to be readable.

The formatting with % is an old way, but backwards compatible.

Using the .format(_) function is the recommended way going forward.

Concatenation of strings together is usually very hard to read or to grasp as to what the final string is supposed to be.

I personally always use .format option, also because it allows to name the variables inside the curly brackets. For example

from datetime import datetime
now = datetime.now()
time_now = "Time: '{time}'".format(time=now)

In this way it gives a more general variable name inside the string, so that everybody knows what the input variable is about.


问:
Custom Pipe Not Found
I am having issues with a custom pipe not being found when I call it.

I have imported the pipe in my app.module.ts file and declared it in the declarations. I followed a few tutorials on how to do it and also have looked at a few questions already asked on here and by what I am seeing it should work but it is still throwing the error: "The pipe 'getOrderType' could not be found"

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'getOrderType'})
export class GetOrderTypePipe implements PipeTransform {
    transform(orderType: String, delivered: Boolean, requestType: String): LoadTypeEnum {
        if (delivered&& requestType !== 'mobile') {
            return 'Mobile devlivery';
          } else if (requestType === 'web') {
            return 'Web';
          } else {
            return 'N/A';
          }
    }
}
</code>```

and here is how I am calling it in my html:

```<code>{{ this.orderType| getOrderType: this.order.requestType: this.delivered}}
</code>```

答:
Where did you import your pipe because it looks like its missing in your module.ts providers:</p>

```<code>providers: [
        GetOrderTypePipe
    ]
</code>```

Title: Custom Pipe Not Found

Body:
I am having issues with a custom pipe not being found when I call it.

I have imported the pipe in my app.module.ts file and declared it in the declarations. I followed a few tutorials on how to do it and also have looked at a few questions already asked on here and by what I am seeing it should work but it is still throwing the error: "The pipe 'getOrderType' could not be found"

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'getOrderType'})
export class GetOrderTypePipe implements PipeTransform {
    transform(orderType: String, delivered: Boolean, requestType: String): LoadTypeEnum {
        if (delivered&& requestType !== 'mobile') {
            return 'Mobile devlivery';
          } else if (requestType === 'web') {
            return 'Web';
          } else {
            return 'N/A';
          }
    }
}

and here is how I am calling it in my html:

{{ this.orderType| getOrderType: this.order.requestType: this.delivered}}

Body:
Where did you import your pipe because it looks like its missing in your module.ts providers:

providers: [
        GetOrderTypePipe
    ]


问:
Good Quality Free Gridview for .NET WinForms
Is there a good quality free Gridview for .NET WinForms?  The Xceed datagrid (express edition) is lovely, but is for WPF.  It's nice and simple, isn't overwhelming in the features department, and looks great at the click of a button.  I'm looking for something similar for WinForms.</p>

答: The DevAge SourceGrid appears to be decent.  Everything I've seen that is great or sleek is for sale only.</p>

OwnerDisplayName: Neil Barnwell

ContentLicense: CC BY-SA 2.5


问:
show page as a popup
is there any solution that when i acces a normal page it will be loaded in a popup if the user has javascript activated?
So,can i make a normal page a popup? Using a jquery plugin for example?

Thank you!

答:
Yes, for sure you can have pages as popup when js is active.

Check jQuery bPopUp plugin. It's simple to implement, and quite interesting in features.

Thanks.

ContentLicense: CC BY-SA 3.0

Title: show page as a popup


问:
TypeScript error: "Type 'number' is not assignable to type '0 | 1 | 2' ". Why am I getting this error?
I am getting a weird TypeScript error.

I have the following example:

```<code>interface Foo {
  prop: 0 | 1 | 2;
}

class Bar implements Foo {
  prop = 1;
}

</code>```

And I am getting the error:

```<code>src/example.ts:6:3 - error TS2416: Property 'prop' in type 'Bar' is not assignable to the same property in base type 'Foo'.
  Type 'number' is not assignable to type '0 | 1 | 2'.

6   prop = 1;
    ~~~~
</code>```

Why does this code give the error?

答:
You need to also define the element in Bar since Foo is an interface:

```<code>interface Foo {
  prop: 0 | 1 | 2;
}

class Bar implements Foo {
  prop: 0 | 1 | 2 = 1;
}
</code>```

An interface just describes how a class needs to look, so basically you then need to re-define everything within the class to match your interface.

If you don't want to re-define the definition of the element a class might be a better option:

```<code>class Foo {
  protected prop: 0 | 1 | 2;
}

class Bar extends Foo {
  public test() {
    this.prop = 1;
  }
}
</code>```

Body:
I am getting a weird TypeScript error.

I have the following example:

interface Foo {
  prop: 0 | 1 | 2;
}

class Bar implements Foo {
  prop = 1;
}

And I am getting the error:

src/example.ts:6:3 - error TS2416: Property 'prop' in type 'Bar' is not assignable to the same property in base type 'Foo'.
  Type 'number' is not assignable to type '0 | 1 | 2'.

6   prop = 1;
    ~~~~

Why does this code give the error?

Body:
You need to also define the element in Bar since Foo is an interface:

interface Foo {
  prop: 0 | 1 | 2;
}

class Bar implements Foo {
  prop: 0 | 1 | 2 = 1;
}

An interface just describes how a class needs to look, so basically you then need to re-define everything within the class to match your interface.

If you don't want to re-define the definition of the element a class might be a better option:

class Foo {
  protected prop: 0 | 1 | 2;
}

class Bar extends Foo {
  public test() {
    this.prop = 1;
  }
}


问:
sqlalchemy, select using reverse-inclusive (not in) list of child column values
I have a typical Post / Tags (many tags associated with one post) relationship in flask-sqlalchemy, and I want to select posts which aren't tagged with any tag in a list I provide. First, the models I set up:

```<code>class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    tags = db.relationship('Tag', lazy='dynamic')

class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text(50))
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
</code>```

Something like

db.session.query(Post).filter(Post.tags.name.notin_(['dont','want','these']))

fails with

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Post.tags has an attribute 'name'

which I assume is because tags is a relationship and not a column. I had this working on another project when I was writing the actual SQL manually. This was the SQL that worked:

SELECT * FROM $posts WHERE id NOT IN (SELECT post_id FROM $tags WHERE name IN ('dont','want','these'))

How would I achieve this using the sqlalchemy API?

答:
The notin_ works for me, adjusted example:

```<code>db.session.query(Post).filter(Post.tags.notin_(['dont','want','these']))
</code>```

Body:
I have a typical Post / Tags (many tags associated with one post) relationship in flask-sqlalchemy, and I want to select posts which aren't tagged with any tag in a list I provide. First, the models I set up:

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    tags = db.relationship('Tag', lazy='dynamic')

class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text(50))
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'))

Something like

db.session.query(Post).filter(Post.tags.name.notin_(['dont','want','these']))

fails with

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Post.tags has an attribute 'name'

which I assume is because tags is a relationship and not a column. I had this working on another project when I was writing the actual SQL manually. This was the SQL that worked:

SELECT * FROM $posts WHERE id NOT IN (SELECT post_id FROM $tags WHERE name IN ('dont','want','these'))

How would I achieve this using the sqlalchemy API?

Body:
The notin_ works for me, adjusted example:

db.session.query(Post).filter(Post.tags.notin_(['dont','want','these']))


问:
What purpose does this receive statement fullfil in this judge function?
I recently started learning Erlang from https://learnyousomeerlang.com
in this chapter errors and processes, I understood what the program does and how it executes but I'm unable to figure out what's the purpose of this receive the statement in judge function when and how will it be called?

From What I understand if tuple pattern matches with Pid and atom it returns an atom. How will i send message to receive inside judge?

```<code>  start_critic() ->
  spawn(?MODULE, critic, []).

judge(Pid, Band, Album) ->
  Pid ! {self(), {Band, Album}},
  receive
    {Pid, Criticism} -> Criticism
  after 2000 ->
    timeout
  end.

critic() ->
  receive
    {From, {"Rage Against the Turing Machine", "Unit Testify"}} ->
      From ! {self(), "They are great!"};
    {From, {"System of a Downtime", "Memoize"}} ->
      From ! {self(), "They're not Johnny Crash but they're good."};
    {From, {"Johnny Crash", "The Token Ring of Fire"}} ->
      From ! {self(), "Simply incredible."};
    {From, {_Band, _Album}} ->
      From ! {self(), "They are terrible!"}
  end,
  critic().
</code>```

Output

```<code>c(linkmon).
{ok,linkmon}

Critic = linkmon:start_critic().
<0.109.0>

linkmon:judge(Critic, "Genesis", "The Lambda Lies Down on Broadway").
"They are terrible!"

linkmon:judge(Critic, "Genesis", "A trick of the Tail Recursion").
"They are terrible!"

linkmon:judge(Critic, "Johnny Crash", "The Token Ring of Fire").
"Simply incredible."
</code>```

答: The line Pid ! ... sends a message to the critic. The critic will then send a response via one of the From ! ... lines. The receive in the judge function waits for said response and then simply returns the string contained in the response.

Body:
I recently started learning Erlang from https://learnyousomeerlang.com
in this chapter errors and processes, I understood what the program does and how it executes but I'm unable to figure out what's the purpose of this receive the statement in judge function when and how will it be called?

From What I understand if tuple pattern matches with Pid and atom it returns an atom. How will i send message to receive inside judge?

  start_critic() ->
  spawn(?MODULE, critic, []).

judge(Pid, Band, Album) ->
  Pid ! {self(), {Band, Album}},
  receive
    {Pid, Criticism} -> Criticism
  after 2000 ->
    timeout
  end.

critic() ->
  receive
    {From, {"Rage Against the Turing Machine", "Unit Testify"}} ->
      From ! {self(), "They are great!"};
    {From, {"System of a Downtime", "Memoize"}} ->
      From ! {self(), "They're not Johnny Crash but they're good."};
    {From, {"Johnny Crash", "The Token Ring of Fire"}} ->
      From ! {self(), "Simply incredible."};
    {From, {_Band, _Album}} ->
      From ! {self(), "They are terrible!"}
  end,
  critic().

Output

c(linkmon).
{ok,linkmon}

Critic = linkmon:start_critic().
<0.109.0>

linkmon:judge(Critic, "Genesis", "The Lambda Lies Down on Broadway").
"They are terrible!"

linkmon:judge(Critic, "Genesis", "A trick of the Tail Recursion").
"They are terrible!"

linkmon:judge(Critic, "Johnny Crash", "The Token Ring of Fire").
"Simply incredible."


问:
I want to save a file in VB.net from the amount of tries a user has
I'm a student trying to learn Console App .Net Framework and I want to code a random number between 0000 and 9999 (as a pin that you need to guess). Thus far I've had to set it as a random number from 1000 to 9999 as the system wont let me do 0000. Furthermore, I want to save the amount of tries the user has as a text file e.g. if the user tries 50 times, I'd like it to say

```<code>Username          Tries
</code>```

I've tried Randomise() Rnd(*9999) and X = EasyNum.Next(1000, 9999) but then I can't compare unless I convert that to an integer.

```<code>Module Module1
    Dim Tries As String = 0
    Dim EasyNum As New Random
    Dim HardNum As New Random
    Dim Attempt As String
    Sub Main()
        Dim Difficulty As String
        Console.WriteLine("Welcome to MasterMind")
        Console.WriteLine("Choose between Easy and Hard difficulty")

        Difficulty = Strings.LCase(Console.ReadLine)
        While Difficulty <> "easy" And Difficulty <> "hard"
            Console.WriteLine("That's not a correct mode")
            Difficulty = Strings.LCase(Console.ReadLine)
        End While
        If Difficulty = "easy" Then
            Easy()
        ElseIf Difficulty = "hard" Then
            Hard()
        End If

    End Sub

    Dim EasyGuess1 As Integer
    Dim EasyGuess2 As Integer
    Dim X As String
    Dim Y As Integer
    Sub Easy()

        Console.WriteLine("You have chosen the easy difficulty")
        Console.WriteLine("You have to guess a 4 Digit number between 1000 and 9999")
        Console.WriteLine("Enter your guess")

        X = EasyNum.Next(1000, 9999)
        Console.WriteLine(X)
        EasyGuess1 = Console.ReadLine
        Tries = +1
        If Mid(CStr(EasyGuess1), 1, 1) = Mid(CStr(X), 1, 1) Then
            Console.WriteLine("You have 1 number correct, try again?")
            Attempt = Strings.LCase(Console.ReadLine)
            While Attempt <> "yes" And Attempt <> "no"
                Console.WriteLine("Enter either yes or no")
                Attempt = Strings.LCase(Console.ReadLine)
            End While
        ElseIf Mid(CStr(EasyGuess1), 2, 1) = Mid(CStr(X), 2, 1) Then
            Console.WriteLine("You have 1 number correct, try again?")
            Attempt = Strings.LCase(Console.ReadLine)
            While Attempt <> "yes" And Attempt <> "no"
                Console.WriteLine("Enter either yes or no")
                Attempt = Strings.LCase(Console.ReadLine)
            End While
        End If
        If Attempt = "yes" Then
            EasyYes()
        ElseIf Attempt = "no" Then
            EasyNo()
        End If
        Console.WriteLine("incorrect")

        Console.ReadKey()
    End Sub
    Sub EasyYes()
        Console.WriteLine("Enter a new guess")
        EasyGuess1 = Console.ReadLine
    End Sub
    Sub EasyNo()
        Dim Save As String
        Dim File As System.IO.File
        Console.WriteLine("Do you want to save your tries? Enter Yes or no")
        Save = Strings.LCase(Console.ReadLine)
        If Save = "yes" Then
            System.IO.File.Create(Tries, "C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test")
        End If
    End Sub
    Sub Hard()

        Console.WriteLine("You have chosen the hard difficulty")

    End Sub
    Sub HardYes()

    End Sub
    Sub HardNo()

    End Sub

End Module
</code>```

When I try to save the tries, I get this:

System.InvalidCastException: 'Conversion from string "C:\X\Code\VB\Challenges\Cha" to type 'Integer' is not valid.'
  InnerException
  FormatException: Input string was not in a correct format.

Which I don't understand myself.

答:
Comments in line. Please read all comments. This program is still not working too well but I will leave it to you to tidy up.</p>

```<code>Module Module1
    Dim Tries As Integer = 0
    'Use only a single instance of Random
    Dim EasyNum As New Random
    'Dim HardNum As New Random
    Dim Attempt As String
    Sub Main()
        Dim Difficulty As String
        Console.WriteLine("Welcome to MasterMind")
        Console.WriteLine("Choose between Easy and Hard difficulty")

        Difficulty = Strings.LCase(Console.ReadLine)
        'AndAlso prevents the second condition from executing if the first condition is true
        While Difficulty <> "easy" AndAlso Difficulty <> "hard"
            Console.WriteLine("That's not a correct mode")
            Difficulty = Strings.LCase(Console.ReadLine)
        End While
        If Difficulty = "easy" Then
            Easy()
            'ElseIf Difficulty = "hard" Then
            '    Hard() 'Not implemented
        End If

    End Sub

    'Dim EasyGuess2 As Integer
    'Dim X As String
    'Dim Y As Integer
    Sub Easy()
        Dim EasyGuess1 As Integer
        Console.WriteLine("You have chosen the easy difficulty")
        Console.WriteLine("You have to guess a 4 Digit number between 1000 and 9999")
        Console.WriteLine("Enter your guess")
        'X = EasyNum.Next(1000, 9999)
        'The next method returns a non-negative integer not a string
        'To get 0 to 9999 with leading zeros do the following
        'Returns a non-negative random integer that is less than the specified maximum.
        Dim X = EasyNum.Next(10000).ToString("0000")
        Console.WriteLine(X)
        'Console.ReadLine returns a String. You should Not assign a String to an Integer
        'EasyGuess1 = Console.ReadLine
        'Never trust a user :-) Use .TryParse to set the variable
        Integer.TryParse(Console.ReadLine, EasyGuess1)
        'This just assigns the value of 1 to Tries
        'Tries = +1
        'If you want to increment Tries
        Tries += 1
        'Let's compare apples and apples
        'If you just convert EasyGuess1 To a string and EasyGuess1 is 54
        'the string is "54" You want a 4 character string
        'If Mid(EasyGuess1.ToString("0000"), 1, 1) = Mid(CStr(X), 1, 1) Then
        '    'but you only compared the first character, what about the rest?
        '    'Mid is aroung for backward compatibility. It should not be used for new code.
        '    'The position Integer is one based which is not at all sympatico with .net
        '    Console.WriteLine("You have 1 number correct, try again?")
        '    Attempt = Strings.LCase(Console.ReadLine)
        '    While Attempt <> "yes" And Attempt <> "no"
        '        Console.WriteLine("Enter either yes or no")
        '        Attempt = Strings.LCase(Console.ReadLine)
        '    End While
        'ElseIf Mid(CStr(EasyGuess1), 2, 1) = Mid(CStr(X), 2, 1) Then
        '    Console.WriteLine("You have 1 number correct, try again?")
        '    Attempt = Strings.LCase(Console.ReadLine)
        '    While Attempt <> "yes" And Attempt <> "no"
        '        Console.WriteLine("Enter either yes or no")
        '        Attempt = Strings.LCase(Console.ReadLine)
        '    End While
        'End If
        Dim CorrectCharacters = TestInput(EasyGuess1, X)
        Console.WriteLine($"You have guessed {CorrectCharacters} correctly. Try again?")
        'Use the .net way. The framework is available to all languages in .net
        'so it will be easier to learn other languages.
        Attempt = (Console.ReadLine).ToLower
        If Attempt = "yes" Then
            EasyYes()
        ElseIf Attempt = "no" Then
            EasyNo()
        End If
        Console.WriteLine("incorrect")

        Console.ReadKey()
    End Sub
    Sub EasyYes()
        Dim guess As Integer
        Console.WriteLine("Enter a new guess")
        'You are doing this twice ???
        'EasyGuess1 = Console.ReadLine
        Integer.TryParse(Console.ReadLine, guess)
        'EasyGuess1 will be 0 if the entry is other than an integer
        'Very nice bu this Sub doesn't do anything
    End Sub
    Sub EasyNo()
        Dim Save As String
        'Unused local variable and if you needed this it is a poor choice for a variable name
        'Dim File As System.IO.File
        Console.WriteLine("Do you want to save your tries? Enter Yes or no")
        Save = Console.ReadLine.ToLower
        If Save = "yes" Then
            'Give the file name an extension.
            'When you pass (String, Integer) to the Create method, the Integer is the number of bytes
            'buffered for reads And writes to the file.
            'Not exactly what you were expecting.
            'System.IO.File.Create("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test.txt", Tries)
            'Imports System.IO at top of file
            File.WriteAllText("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test.txt", Tries.ToString)
        End If
    End Sub
    Sub Hard()
        Console.WriteLine("You have chosen the hard difficulty")
    End Sub

    Private Function TestInput(Guessed As Integer, RandString As String) As Integer
        Dim Correct As Integer
        Dim Guess As String = Guessed.ToString("0000")
        'A String can be a Char array
        'Here we check each character in the 2 strings for equality
        'and if true then increment Correct
        For i = 0 To 3
            If Guess(i) = RandString(i) Then
                Correct += 1
            End If
        Next
        Return Correct
    End Function

End Module
</code>```

Body:
I'm a student trying to learn Console App .Net Framework and I want to code a random number between 0000 and 9999 (as a pin that you need to guess). Thus far I've had to set it as a random number from 1000 to 9999 as the system wont let me do 0000. Furthermore, I want to save the amount of tries the user has as a text file e.g. if the user tries 50 times, I'd like it to say

Username          Tries

I've tried Randomise() Rnd(*9999) and X = EasyNum.Next(1000, 9999) but then I can't compare unless I convert that to an integer.

Module Module1
    Dim Tries As String = 0
    Dim EasyNum As New Random
    Dim HardNum As New Random
    Dim Attempt As String
    Sub Main()
        Dim Difficulty As String
        Console.WriteLine("Welcome to MasterMind")
        Console.WriteLine("Choose between Easy and Hard difficulty")

        Difficulty = Strings.LCase(Console.ReadLine)
        While Difficulty <> "easy" And Difficulty <> "hard"
            Console.WriteLine("That's not a correct mode")
            Difficulty = Strings.LCase(Console.ReadLine)
        End While
        If Difficulty = "easy" Then
            Easy()
        ElseIf Difficulty = "hard" Then
            Hard()
        End If

    End Sub

    Dim EasyGuess1 As Integer
    Dim EasyGuess2 As Integer
    Dim X As String
    Dim Y As Integer
    Sub Easy()

        Console.WriteLine("You have chosen the easy difficulty")
        Console.WriteLine("You have to guess a 4 Digit number between 1000 and 9999")
        Console.WriteLine("Enter your guess")

        X = EasyNum.Next(1000, 9999)
        Console.WriteLine(X)
        EasyGuess1 = Console.ReadLine
        Tries = +1
        If Mid(CStr(EasyGuess1), 1, 1) = Mid(CStr(X), 1, 1) Then
            Console.WriteLine("You have 1 number correct, try again?")
            Attempt = Strings.LCase(Console.ReadLine)
            While Attempt <> "yes" And Attempt <> "no"
                Console.WriteLine("Enter either yes or no")
                Attempt = Strings.LCase(Console.ReadLine)
            End While
        ElseIf Mid(CStr(EasyGuess1), 2, 1) = Mid(CStr(X), 2, 1) Then
            Console.WriteLine("You have 1 number correct, try again?")
            Attempt = Strings.LCase(Console.ReadLine)
            While Attempt <> "yes" And Attempt <> "no"
                Console.WriteLine("Enter either yes or no")
                Attempt = Strings.LCase(Console.ReadLine)
            End While
        End If
        If Attempt = "yes" Then
            EasyYes()
        ElseIf Attempt = "no" Then
            EasyNo()
        End If
        Console.WriteLine("incorrect")

        Console.ReadKey()
    End Sub
    Sub EasyYes()
        Console.WriteLine("Enter a new guess")
        EasyGuess1 = Console.ReadLine
    End Sub
    Sub EasyNo()
        Dim Save As String
        Dim File As System.IO.File
        Console.WriteLine("Do you want to save your tries? Enter Yes or no")
        Save = Strings.LCase(Console.ReadLine)
        If Save = "yes" Then
            System.IO.File.Create(Tries, "C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test")
        End If
    End Sub
    Sub Hard()

        Console.WriteLine("You have chosen the hard difficulty")

    End Sub
    Sub HardYes()

    End Sub
    Sub HardNo()

    End Sub

End Module

When I try to save the tries, I get this:

System.InvalidCastException: 'Conversion from string "C:\X\Code\VB\Challenges\Cha" to type 'Integer' is not valid.'
  InnerException
  FormatException: Input string was not in a correct format.

Which I don't understand myself.

Body:
Comments in line. Please read all comments. This program is still not working too well but I will leave it to you to tidy up.

Module Module1
    Dim Tries As Integer = 0
    'Use only a single instance of Random
    Dim EasyNum As New Random
    'Dim HardNum As New Random
    Dim Attempt As String
    Sub Main()
        Dim Difficulty As String
        Console.WriteLine("Welcome to MasterMind")
        Console.WriteLine("Choose between Easy and Hard difficulty")

        Difficulty = Strings.LCase(Console.ReadLine)
        'AndAlso prevents the second condition from executing if the first condition is true
        While Difficulty <> "easy" AndAlso Difficulty <> "hard"
            Console.WriteLine("That's not a correct mode")
            Difficulty = Strings.LCase(Console.ReadLine)
        End While
        If Difficulty = "easy" Then
            Easy()
            'ElseIf Difficulty = "hard" Then
            '    Hard() 'Not implemented
        End If

    End Sub

    'Dim EasyGuess2 As Integer
    'Dim X As String
    'Dim Y As Integer
    Sub Easy()
        Dim EasyGuess1 As Integer
        Console.WriteLine("You have chosen the easy difficulty")
        Console.WriteLine("You have to guess a 4 Digit number between 1000 and 9999")
        Console.WriteLine("Enter your guess")
        'X = EasyNum.Next(1000, 9999)
        'The next method returns a non-negative integer not a string
        'To get 0 to 9999 with leading zeros do the following
        'Returns a non-negative random integer that is less than the specified maximum.
        Dim X = EasyNum.Next(10000).ToString("0000")
        Console.WriteLine(X)
        'Console.ReadLine returns a String. You should Not assign a String to an Integer
        'EasyGuess1 = Console.ReadLine
        'Never trust a user :-) Use .TryParse to set the variable
        Integer.TryParse(Console.ReadLine, EasyGuess1)
        'This just assigns the value of 1 to Tries
        'Tries = +1
        'If you want to increment Tries
        Tries += 1
        'Let's compare apples and apples
        'If you just convert EasyGuess1 To a string and EasyGuess1 is 54
        'the string is "54" You want a 4 character string
        'If Mid(EasyGuess1.ToString("0000"), 1, 1) = Mid(CStr(X), 1, 1) Then
        '    'but you only compared the first character, what about the rest?
        '    'Mid is aroung for backward compatibility. It should not be used for new code.
        '    'The position Integer is one based which is not at all sympatico with .net
        '    Console.WriteLine("You have 1 number correct, try again?")
        '    Attempt = Strings.LCase(Console.ReadLine)
        '    While Attempt <> "yes" And Attempt <> "no"
        '        Console.WriteLine("Enter either yes or no")
        '        Attempt = Strings.LCase(Console.ReadLine)
        '    End While
        'ElseIf Mid(CStr(EasyGuess1), 2, 1) = Mid(CStr(X), 2, 1) Then
        '    Console.WriteLine("You have 1 number correct, try again?")
        '    Attempt = Strings.LCase(Console.ReadLine)
        '    While Attempt <> "yes" And Attempt <> "no"
        '        Console.WriteLine("Enter either yes or no")
        '        Attempt = Strings.LCase(Console.ReadLine)
        '    End While
        'End If
        Dim CorrectCharacters = TestInput(EasyGuess1, X)
        Console.WriteLine($"You have guessed {CorrectCharacters} correctly. Try again?")
        'Use the .net way. The framework is available to all languages in .net
        'so it will be easier to learn other languages.
        Attempt = (Console.ReadLine).ToLower
        If Attempt = "yes" Then
            EasyYes()
        ElseIf Attempt = "no" Then
            EasyNo()
        End If
        Console.WriteLine("incorrect")

        Console.ReadKey()
    End Sub
    Sub EasyYes()
        Dim guess As Integer
        Console.WriteLine("Enter a new guess")
        'You are doing this twice ???
        'EasyGuess1 = Console.ReadLine
        Integer.TryParse(Console.ReadLine, guess)
        'EasyGuess1 will be 0 if the entry is other than an integer
        'Very nice bu this Sub doesn't do anything
    End Sub
    Sub EasyNo()
        Dim Save As String
        'Unused local variable and if you needed this it is a poor choice for a variable name
        'Dim File As System.IO.File
        Console.WriteLine("Do you want to save your tries? Enter Yes or no")
        Save = Console.ReadLine.ToLower
        If Save = "yes" Then
            'Give the file name an extension.
            'When you pass (String, Integer) to the Create method, the Integer is the number of bytes
            'buffered for reads And writes to the file.
            'Not exactly what you were expecting.
            'System.IO.File.Create("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test.txt", Tries)
            'Imports System.IO at top of file
            File.WriteAllText("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test.txt", Tries.ToString)
        End If
    End Sub
    Sub Hard()
        Console.WriteLine("You have chosen the hard difficulty")
    End Sub

    Private Function TestInput(Guessed As Integer, RandString As String) As Integer
        Dim Correct As Integer
        Dim Guess As String = Guessed.ToString("0000")
        'A String can be a Char array
        'Here we check each character in the 2 strings for equality
        'and if true then increment Correct
        For i = 0 To 3
            If Guess(i) = RandString(i) Then
                Correct += 1
            End If
        Next
        Return Correct
    End Function

End Module


问:
Git move directory from one branch to another within the same repository while preserving history?
How to git move directory from one branch to another while preserving history?

I want to move in the same repo.

答:
TL;DR

You can't (quite) get what you want—but if you try sometimes, you might just find, you get what you need.

All you have to do is rename the directory and commit.  You may first need to extract the directory from the other commit, if it's not already in the commit at the tip of the current branch.  That is, you might need an initial:

```<code>git checkout otherbranch -- path/to/directory
git commit                                      # optional, but see below
</code>```

and then in any case, run:

```<code>git mv path/to/directory new/path/to/dir
</code>```

and then git commit the result.  That doesn't do what you want, but it might do what you need—especially if you make that first commit that doesn't have the renaming, so that you have two adjacent commits, one with the old names, and one with the new ones.

You may, instead, want to merge the branches, commit the merge, and only then rename and commit again.  Whether you want this, and why, requires the long explanation.

Long

It's important to understand two things here:

Git stores only files, not directories.1  Each commit stores a full snapshot of all of the files in your project.

Files don't have history, in Git.  In Git, the commits are the history.

People often object to the idea that Git stores snapshots, because git log -p shows patches, i.e., changes.  You view commit 0a36ca1, say, and you see some change to README.md.  Then git log goes on to commit 0a36ca1's parent commit 922bf37, say, and you see another change to README.md and/or some other files, and so on.  Doesn't that mean 0a36ca1 just stores the changes to README.md?  And the answer is: no, 0a36ca1 stores a full copy of README.md and all the other files.  Git showed changes by inspecting both 922bf37—the parent of 0a36ca1, i.e., the commit that comes just before 0a36ca1—and 0a36ca1.  Both commits have copies of every file.  Git compared the two commits' files.  All of the files in those two commits matched except for README.md.  Git then compared the two README.md versions to see what changed, and showed you what changed in that file.

The git show command is similar, except that you typically give it the hash ID of one commit, and git show prints the commit's metadata (who made it, when, and why—the log message) and then compares the snapshot in the parent to the snapshot in that commit.  Whatever's different, is what files you see.

When you ask for history with git log by running git log or git log master, Git:

Starts at the current commit (git log), or the last commit in master, and shows you that commit a la git show.2

Then, moves back to the parent of the commit it just showed.  This gets complicated at merge commits, but for now, just think of a nice simple linear chain.

This repeats until Git runs out of parents, or you get tired of paging through git log output.  Given a nice simple linear chain of commits, like:

```<code>A <-B <-C <-D <-E <-F <-G   <-- master
</code>```

(the single uppercase letters stand in here for the big ugly hash IDs that Git really uses), Git starts by showing you G (as found by the name master), then moving to F and showing you F, then moving to E and showing E, and so on.  Commit A is the very first commit in the repository—it has no parent; there's no backwards arrow coming out of A to let Git move left—so git show shows it as having every file created from scratch.  That means git log -p shows it the same way.  And of course, with no parent, there's no arrow to follow backwards.

1Technically, directories turn into internal tree objects, but Git won't store an empty directory for the simple reason that you can't get a directory into Git's index, and Git doesn't built commits from the work-tree, but rather from the index.  It's easier to think of Git as just storing files, since that's the end effect.

2This assumes you're using git log -p, of course.  There are several important difference between git log and git show: first, git log does this backwards walk; second, git log defaults to not showing a patch; and third, git show shows merge commits in a different default manner: git log -p defaults to saying to itself: ugh, a merge commit, that's too hard: I'll just print the log message and move on, without showing a diff at all.  The git show default here is to show a combined diff, which is a reduced form of diff against multiple parents.

git log can show a subset of history

You can, instead of just running git log or git log master, run:

```<code>git log master -- path/to/file.ext
</code>```

and see what appears to be the history of path/to/file.ext.  What git log is doing here is walking commit history as usual, but then not showing some of the commits.  That is, given our simple linear chain above, git log starts with commit G.  It compares (the snapshots of) F and G to see what files changed.  If those files do include path/to/file.ext, git log shows commit G.  Then it moves back to commit F, even if it showed nothing at all.

In other words, instead of just showing you all the commits it walks, git log can show you selected commits from the walk.  The result is that it seems like Git has file history—but it doesn't: it's just synthesizing a subset history from the real history, working as it goes.

This is important because when Git is doing this synthetic file-history creation, git log is modifying the commit walk.  The git log documentation calls this History Simplification, and it's complicated.  There are a half dozen or so git log options to control how history simplification will be performed.  This means that the "file history" that you see with git log depends on what options you pass to git log, as well as what the actual commit history is.

(Read and study the History Simplification section, at least someday, because there is a lot to it.  I've been using Git for a long time, and like to think I know a lot about it, but even then I have to refer back to the documentation for this.  In particular, the notion of "TREESAME"—which applies after subtracting away unwanted tree components from each commit—and which commits are followed at merges is especially tricky.)

With --follow, git log will try to detect renames

As Git is doing this commit-by-commit, backwards traversal of a chain of commits, the diff from parent to child may show that some file is renamed.  A file named README may have been renamed to one named README.md, for instance.  A simple:

```<code>git log master -- README.md
</code>```

will show you how README.md evolved over time (backwards), but stop when README.md was named README, because it's looking for README.md and commits from here on back don't have README.md.

When you add --follow to git log, it will follow that one file—it only works with one file!—across the rename, simply by changing which file it's looking for.  Having detected that at, say, the commit-D-to-E boundary, the file that is now README.md was called README in commit D, git log stops looking for README.md and starts, with D, looking for changes to a file named README.  It's really that simple.

--follow is too simple for your use case

The problem here is that --follow is that simple, which is too simple.  So it won't do what you want, for two reasons:

First, you're talking about copying files across some fairly large gap:

```<code>...--F--G--H   <-- master
 \
  N--O--P   <-- branch
</code>```

If your directory-full-of-files is in commit H on master, and you're just now copying it to a new commit you'll make on branch that comes after commit P, well, there's no backwards link from P to H.  That's why I proposed that you commit the files without renaming them, then rename them and commit again.  The result will be:

```<code>...--F--G--H   <-- master
 \
  N--O--P--Q--R   <-- branch
</code>```

where commit R has the files renamed, and Q has them not-renamed, just copied from H.  In the commit log message for Q, you can state that the entire directory has been copied from branch master at a time when it pointed to commit H (use H's real hash ID here—run git rev-parse master to see what hash ID master specifies right now).  Then you rename the directory and commit again to make them show up as renames, whenever Git walks from commit R back to commit Q.

The git log --follow option only works on one file.  That is, given a commit that is or descends from R, and therefore has the new directory name, you must run:

```<code>git log --follow [<commit-hash>] [--] new/path/to/dir/file.ext
</code>```

which will eventually work its way to commit R, show new/path/to/dir/file.ext (because it is renamed in commit R as compared to commit Q), then move back to commit Q and start looking for path/to/directory/file.ext.

From this single detected rename, plus the log messages in Q and R, you—a smart human rather than a dumb Git program that just obeys really simple rules—can conclude that, aha, all of those files came from commit H.

This is where you may want a real merge.  Instead of just copying the files from H, you can literally make commit Q as a merge commit, connecting the history from commit Q back to both commits: P and H.  That is, suppose you end up with:

```<code>...--F--G--H   <-- master
 \          \
  N--O--P----Q--R   <-- branch
</code>```

Now when Git walks through commit history, it goes: R, Q, H-and-P, G-and-O, F-and-N, and so on.  That is, git log walks through the actual history, one commit at a time, with a kind of complicated method of tracking through the fork in history where commits H and P merge to form commit Q.

The drawback to doing this merge is kind of obvious: it's a merge.  It will by default bring in all the changes since some common ancestor—since whatever commit comes before N and before F where branch and master eventually lead back to a shared commit: a commit that's on both branches.  You don't necessarily have to commit those changes, or even any changes: you can make commit Q's snapshot match commit P's, except of course for the new directory that you want.

(There are multiple ways to make this merge.  How to achieve it is another StackOverflow question entirely, one that's already well answered.  See (Git Merging) When to use 'ours' strategy, 'ours' option and 'theirs' option?, and also VonC's answer to a different question here.  There are many options here but you probably would want to start with git merge -s ours --no-commit, if you want -s ours at all, and then the extraction of the files with git checkout <commit> -- <path>, and only then making commit Q as a merge.)

The advantage to the merge is that it ties the histories together, so that git log can walk from merge Q back to commit H, which is the source of actual history for the (pre-renaming) files.  The disadvantage is that it ties the histories together, so that from then on, Git believes that the correct result of merging H with P is Q, even if you later change your mind about that.

If the merge isn't what you want, the commit(s) plus log message(s) may be what you need.

Body:
TL;DR

You can't (quite) get what you want—but if you try sometimes, you might just find, you get what you need.

All you have to do is rename the directory and commit.  You may first need to extract the directory from the other commit, if it's not already in the commit at the tip of the current branch.  That is, you might need an initial:

git checkout otherbranch -- path/to/directory
git commit                                      # optional, but see below

and then in any case, run:

git mv path/to/directory new/path/to/dir

and then git commit the result.  That doesn't do what you want, but it might do what you need—especially if you make that first commit that doesn't have the renaming, so that you have two adjacent commits, one with the old names, and one with the new ones.

You may, instead, want to merge the branches, commit the merge, and only then rename and commit again.  Whether you want this, and why, requires the long explanation.

Long

It's important to understand two things here:

Git stores only files, not directories.1  Each commit stores a full snapshot of all of the files in your project.

Files don't have history, in Git.  In Git, the commits are the history.

People often object to the idea that Git stores snapshots, because git log -p shows patches, i.e., changes.  You view commit 0a36ca1, say, and you see some change to README.md.  Then git log goes on to commit 0a36ca1's parent commit 922bf37, say, and you see another change to README.md and/or some other files, and so on.  Doesn't that mean 0a36ca1 just stores the changes to README.md?  And the answer is: no, 0a36ca1 stores a full copy of README.md and all the other files.  Git showed changes by inspecting both 922bf37—the parent of 0a36ca1, i.e., the commit that comes just before 0a36ca1—and 0a36ca1.  Both commits have copies of every file.  Git compared the two commits' files.  All of the files in those two commits matched except for README.md.  Git then compared the two README.md versions to see what changed, and showed you what changed in that file.

The git show command is similar, except that you typically give it the hash ID of one commit, and git show prints the commit's metadata (who made it, when, and why—the log message) and then compares the snapshot in the parent to the snapshot in that commit.  Whatever's different, is what files you see.

When you ask for history with git log by running git log or git log master, Git:

Starts at the current commit (git log), or the last commit in master, and shows you that commit a la git show.2

Then, moves back to the parent of the commit it just showed.  This gets complicated at merge commits, but for now, just think of a nice simple linear chain.

This repeats until Git runs out of parents, or you get tired of paging through git log output.  Given a nice simple linear chain of commits, like:

A <-B <-C <-D <-E <-F <-G   <-- master

(the single uppercase letters stand in here for the big ugly hash IDs that Git really uses), Git starts by showing you G (as found by the name master), then moving to F and showing you F, then moving to E and showing E, and so on.  Commit A is the very first commit in the repository—it has no parent; there's no backwards arrow coming out of A to let Git move left—so git show shows it as having every file created from scratch.  That means git log -p shows it the same way.  And of course, with no parent, there's no arrow to follow backwards.

1Technically, directories turn into internal tree objects, but Git won't store an empty directory for the simple reason that you can't get a directory into Git's index, and Git doesn't built commits from the work-tree, but rather from the index.  It's easier to think of Git as just storing files, since that's the end effect.

2This assumes you're using git log -p, of course.  There are several important difference between git log and git show: first, git log does this backwards walk; second, git log defaults to not showing a patch; and third, git show shows merge commits in a different default manner: git log -p defaults to saying to itself: ugh, a merge commit, that's too hard: I'll just print the log message and move on, without showing a diff at all.  The git show default here is to show a combined diff, which is a reduced form of diff against multiple parents.

git log can show a subset of history

You can, instead of just running git log or git log master, run:

git log master -- path/to/file.ext

and see what appears to be the history of path/to/file.ext.  What git log is doing here is walking commit history as usual, but then not showing some of the commits.  That is, given our simple linear chain above, git log starts with commit G.  It compares (the snapshots of) F and G to see what files changed.  If those files do include path/to/file.ext, git log shows commit G.  Then it moves back to commit F, even if it showed nothing at all.

In other words, instead of just showing you all the commits it walks, git log can show you selected commits from the walk.  The result is that it seems like Git has file history—but it doesn't: it's just synthesizing a subset history from the real history, working as it goes.

This is important because when Git is doing this synthetic file-history creation, git log is modifying the commit walk.  The git log documentation calls this History Simplification, and it's complicated.  There are a half dozen or so git log options to control how history simplification will be performed.  This means that the "file history" that you see with git log depends on what options you pass to git log, as well as what the actual commit history is.

(Read and study the History Simplification section, at least someday, because there is a lot to it.  I've been using Git for a long time, and like to think I know a lot about it, but even then I have to refer back to the documentation for this.  In particular, the notion of "TREESAME"—which applies after subtracting away unwanted tree components from each commit—and which commits are followed at merges is especially tricky.)

With --follow, git log will try to detect renames

As Git is doing this commit-by-commit, backwards traversal of a chain of commits, the diff from parent to child may show that some file is renamed.  A file named README may have been renamed to one named README.md, for instance.  A simple:

git log master -- README.md

will show you how README.md evolved over time (backwards), but stop when README.md was named README, because it's looking for README.md and commits from here on back don't have README.md.

When you add --follow to git log, it will follow that one file—it only works with one file!—across the rename, simply by changing which file it's looking for.  Having detected that at, say, the commit-D-to-E boundary, the file that is now README.md was called README in commit D, git log stops looking for README.md and starts, with D, looking for changes to a file named README.  It's really that simple.

--follow is too simple for your use case

The problem here is that --follow is that simple, which is too simple.  So it won't do what you want, for two reasons:

First, you're talking about copying files across some fairly large gap:

...--F--G--H   <-- master
 \
  N--O--P   <-- branch

If your directory-full-of-files is in commit H on master, and you're just now copying it to a new commit you'll make on branch that comes after commit P, well, there's no backwards link from P to H.  That's why I proposed that you commit the files without renaming them, then rename them and commit again.  The result will be:

...--F--G--H   <-- master
 \
  N--O--P--Q--R   <-- branch

where commit R has the files renamed, and Q has them not-renamed, just copied from H.  In the commit log message for Q, you can state that the entire directory has been copied from branch master at a time when it pointed to commit H (use H's real hash ID here—run git rev-parse master to see what hash ID master specifies right now).  Then you rename the directory and commit again to make them show up as renames, whenever Git walks from commit R back to commit Q.

The git log --follow option only works on one file.  That is, given a commit that is or descends from R, and therefore has the new directory name, you must run:

git log --follow [<commit-hash>] [--] new/path/to/dir/file.ext

which will eventually work its way to commit R, show new/path/to/dir/file.ext (because it is renamed in commit R as compared to commit Q), then move back to commit Q and start looking for path/to/directory/file.ext.

From this single detected rename, plus the log messages in Q and R, you—a smart human rather than a dumb Git program that just obeys really simple rules—can conclude that, aha, all of those files came from commit H.

This is where you may want a real merge.  Instead of just copying the files from H, you can literally make commit Q as a merge commit, connecting the history from commit Q back to both commits: P and H.  That is, suppose you end up with:

...--F--G--H   <-- master
 \          \
  N--O--P----Q--R   <-- branch

Now when Git walks through commit history, it goes: R, Q, H-and-P, G-and-O, F-and-N, and so on.  That is, git log walks through the actual history, one commit at a time, with a kind of complicated method of tracking through the fork in history where commits H and P merge to form commit Q.

The drawback to doing this merge is kind of obvious: it's a merge.  It will by default bring in all the changes since some common ancestor—since whatever commit comes before N and before F where branch and master eventually lead back to a shared commit: a commit that's on both branches.  You don't necessarily have to commit those changes, or even any changes: you can make commit Q's snapshot match commit P's, except of course for the new directory that you want.

(There are multiple ways to make this merge.  How to achieve it is another StackOverflow question entirely, one that's already well answered.  See (Git Merging) When to use 'ours' strategy, 'ours' option and 'theirs' option?, and also VonC's answer to a different question here.  There are many options here but you probably would want to start with git merge -s ours --no-commit, if you want -s ours at all, and then the extraction of the files with git checkout <commit> -- <path>, and only then making commit Q as a merge.)

The advantage to the merge is that it ties the histories together, so that git log can walk from merge Q back to commit H, which is the source of actual history for the (pre-renaming) files.  The disadvantage is that it ties the histories together, so that from then on, Git believes that the correct result of merging H with P is Q, even if you later change your mind about that.

If the merge isn't what you want, the commit(s) plus log message(s) may be what you need.


问:
Haskell getsizeof big integer
I'm trying to get the size in bytes of a big integer, given that there's arbitrary precision math under the hood, and I'd like to know how much space the result is actually using.

Here's a sample:

```<code>Prelude> import Data.Bits
Prelude> let fac1000 = product [1..1000] # big!
Prelude Data.Bits> finiteBitSize fac1000

<interactive>:37:1: error:
    • Ambiguous type variable ‘b0’ arising from a use of ‘finiteBitSize’
      prevents the constraint ‘(FiniteBits b0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘b0’ should be.
      These potential instances exist:
        instance FiniteBits Bool -- Defined in ‘Data.Bits’
        instance FiniteBits Int -- Defined in ‘Data.Bits’
        instance FiniteBits Word -- Defined in ‘Data.Bits’
    • In the expression: finiteBitSize fac1000
      In an equation for ‘it’: it = finiteBitSize fac1000

<interactive>:37:15: error:
    • Ambiguous type variable ‘b0’ arising from a use of ‘fac1000’
      prevents the constraint ‘(Num b0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘b0’ should be.
      These potential instances exist:
        instance Num Integer -- Defined in ‘GHC.Num’
        instance Num Double -- Defined in ‘GHC.Float’
        instance Num Float -- Defined in ‘GHC.Float’
        ...plus two others
        (use -fprint-potential-instances to see them all)
    • In the first argument of ‘finiteBitSize’, namely ‘fac1000’
      In the expression: finiteBitSize fac1000
      In an equation for ‘it’: it = finiteBitSize fac1000
</code>```

The type annotations they are suggesting do not seem reasonable, when I coerce to an integer for example:

```<code>Prelude Data.Bits> finiteBitSize (fac1000 :: Int)
64
</code>```

Well, that's a big number and I don't believe it.  In python, I get:

```<code>>>> import sys, math
>>> sys.getsizeof(math.factorial(1000))
1164
</code>```

which looks a lot more credible to me for the astronomically large 4.02e2568.

答:
You've misunderstood what finiteBitSize does.  From the docs, emphasis mine:

Return the number of bits in the type of the argument. The actual value of the argument is ignored.

The finiteBitSize :: FiniteBits b => b -> Int function tells you a property of the type b, and it uses the argument to pick out which type.  Any Int would give you the same answer:

```<code>ghci> finiteBitSize (0 :: Int)
64
ghci> finiteBitSize (maxBound :: Int)
64
ghci> finiteBitSize (undefined :: Int)
64
</code>```

This is because Int is the type of lazy machine integers, which fit in one word.  Indeed:

```<code>ghci> product [1..1000] :: Int
0
</code>```

A bit smaller than you may have been expecting :-)

If you want to measure the size of product [1..1000] as an unbounded Integer, you'll need a different technique.  Daniel Wagner's answer provides two good approaches, both mathematical (how to compute log2 100!) and GHC-internal.

Title: Haskell getsizeof big integer

Body:
I'm trying to get the size in bytes of a big integer, given that there's arbitrary precision math under the hood, and I'd like to know how much space the result is actually using.

Here's a sample:

Prelude> import Data.Bits
Prelude> let fac1000 = product [1..1000] # big!
Prelude Data.Bits> finiteBitSize fac1000

<interactive>:37:1: error:
    • Ambiguous type variable ‘b0’ arising from a use of ‘finiteBitSize’
      prevents the constraint ‘(FiniteBits b0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘b0’ should be.
      These potential instances exist:
        instance FiniteBits Bool -- Defined in ‘Data.Bits’
        instance FiniteBits Int -- Defined in ‘Data.Bits’
        instance FiniteBits Word -- Defined in ‘Data.Bits’
    • In the expression: finiteBitSize fac1000
      In an equation for ‘it’: it = finiteBitSize fac1000

<interactive>:37:15: error:
    • Ambiguous type variable ‘b0’ arising from a use of ‘fac1000’
      prevents the constraint ‘(Num b0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘b0’ should be.
      These potential instances exist:
        instance Num Integer -- Defined in ‘GHC.Num’
        instance Num Double -- Defined in ‘GHC.Float’
        instance Num Float -- Defined in ‘GHC.Float’
        ...plus two others
        (use -fprint-potential-instances to see them all)
    • In the first argument of ‘finiteBitSize’, namely ‘fac1000’
      In the expression: finiteBitSize fac1000
      In an equation for ‘it’: it = finiteBitSize fac1000

The type annotations they are suggesting do not seem reasonable, when I coerce to an integer for example:

Prelude Data.Bits> finiteBitSize (fac1000 :: Int)
64

Well, that's a big number and I don't believe it.  In python, I get:

>>> import sys, math
>>> sys.getsizeof(math.factorial(1000))
1164

which looks a lot more credible to me for the astronomically large 4.02e2568.

Body:
You've misunderstood what finiteBitSize does.  From the docs, emphasis mine:

Return the number of bits in the type of the argument. The actual value of the argument is ignored.

The finiteBitSize :: FiniteBits b => b -> Int function tells you a property of the type b, and it uses the argument to pick out which type.  Any Int would give you the same answer:

ghci> finiteBitSize (0 :: Int)
64
ghci> finiteBitSize (maxBound :: Int)
64
ghci> finiteBitSize (undefined :: Int)
64

This is because Int is the type of lazy machine integers, which fit in one word.  Indeed:

ghci> product [1..1000] :: Int
0

A bit smaller than you may have been expecting :-)

If you want to measure the size of product [1..1000] as an unbounded Integer, you'll need a different technique.  Daniel Wagner's answer provides two good approaches, both mathematical (how to compute log2 100!) and GHC-internal.


问:
error CS0619: `UnityEngine.RuntimePlatform.WindowsWebPlayer'
I'm a new user trying Unity, and forgive me if this is a dumb question that can easily be solved with a single button, but I have been pulling my hair out trying to figure out why I keep getting these errors. Here is a screenshot:

Assets/Plugins/Uniject/impl/UnibillUnityUtil.cs(74,25): error CS0619: UnityEngine.RuntimePlatform.OSXDashboardPlayer is obsolete: Dashboard widget on Mac OS X export is no longer supported in Unity 5.4+.

答:
As the error states RuntimePlatform.OSXDashboardPlayer as well as RuntimePlatform.OSXWebPlayer and RuntimePlatform.WindowsWebPlayer) are obsolete and were removed in Unity version 5.4.0. If you still need them you will have to use an older version of Unity.

In general I would simply remove those entries from the list. Rather see the full list of available RuntimePlatform and you will see that others are missing now (the Linux ones)

```<code>public static List<RuntimePlatform> PCControlledPlatforms = new List<RuntimePlatform>()
{
    OSXEditor,     // In the Unity editor on macOS.
    OSXPlayer,     // In the player on macOS.
    WindowsPlayer, // In the player on Windows.
    WindowsEditor, // In the Unity editor on Windows.
    LinuxPlayer,   // In the player on Linux.
    LinuxEditor    // In the Unity editor on Linux.
}
</code>```

However, one can see that Uniject seems to be last updated 6 years ago ... so the probability that it is still working in newer Unity versions is quite low.

And also unibill dosen't exist anymore so it is very probably not compatible with newer Unity versions.

Body:
As the error states RuntimePlatform.OSXDashboardPlayer as well as RuntimePlatform.OSXWebPlayer and RuntimePlatform.WindowsWebPlayer) are obsolete and were removed in Unity version 5.4.0. If you still need them you will have to use an older version of Unity.

In general I would simply remove those entries from the list. Rather see the full list of available RuntimePlatform and you will see that others are missing now (the Linux ones)

public static List<RuntimePlatform> PCControlledPlatforms = new List<RuntimePlatform>()
{
    OSXEditor,     // In the Unity editor on macOS.
    OSXPlayer,     // In the player on macOS.
    WindowsPlayer, // In the player on Windows.
    WindowsEditor, // In the Unity editor on Windows.
    LinuxPlayer,   // In the player on Linux.
    LinuxEditor    // In the Unity editor on Linux.
}

However, one can see that Uniject seems to be last updated 6 years ago ... so the probability that it is still working in newer Unity versions is quite low.

And also unibill dosen't exist anymore so it is very probably not compatible with newer Unity versions.


答:
Because you have assigned prop to be either type '0', '1' or '2' instead of being possible values of 0, 1 and 2

The proper way is to create an enum type variable with possible values of 0, 1 and 2 (e.g. enum values) and assign prop to assume the enum type values (e.g. prop: values)

https://www.typescriptlang.org/docs/handbook/enums.html

Title: TypeScript error: "Type 'number' is not assignable to type '0 | 1 | 2' ". Why am I getting this error?


问:
Flutter: How can I make a Random color generator Background

Generate random colors

```<code>return new RaisedButton(

    padding:  EdgeInsets.symmetric(vertical: 30.0),
    color: Colors.primaries random  List <blue,green>,
</code>```

答:
Simplest and best suggested way to do this is:

Step 1: Add dependency in pubspec.yaml
      random_color: ^1.0.3

Step 2: Add import
      import 'package:random_color/random_color.dart';

Step 3: In "color" attribute write
      color: RandomColor().randomColor();

Body:
Generate random colors

return new RaisedButton(

    padding:  EdgeInsets.symmetric(vertical: 30.0),
    color: Colors.primaries random  List <blue,green>,


问:
Logout in a thymeleaf client when we use oauth2
I have 3 application, one for authorization, one with resource (api rest) and one client in thymeleaf who consume the rest.

When I log out of my client, that don't seem to be a real log out, because when i click on login, that login me directly... use previous user.

I took Baeldung example, who are similar to mine and has same issue.

Authorization server
https://github.com/Baeldung/spring-security-oauth/tree/master/oauth-authorization-server

Resource server
https://github.com/Baeldung/spring-security-oauth/tree/master/oauth-resource-server-1

Thymeleaf client
https://github.com/Baeldung/spring-security-oauth/tree/master/clients-thymeleaf/oauth-ui-authorization-code-thymeleaf

In the Authorization server I have

```<code>@Controller
public class TokenController {

    @Resource(name = "tokenServices")
    private ConsumerTokenServices tokenServices;

    @Resource(name = "tokenStore")
    private TokenStore tokenStore;

    @RequestMapping(method = RequestMethod.POST, value = "/oauth/token/revokeById/{tokenId}")
    @ResponseBody
    public void revokeToken(HttpServletRequest request, @PathVariable String tokenId) {
        tokenServices.revokeToken(tokenId);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/tokens")
    @ResponseBody
    public List<String> getTokens() {
        Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientId("sampleClientId");
        return Optional.ofNullable(tokens).orElse(Collections.emptyList()).stream().map(OAuth2AccessToken::getValue).collect(Collectors.toList());
    }

    @RequestMapping(method = RequestMethod.POST, value = "/tokens/revokeRefreshToken/{tokenId:.*}")
    @ResponseBody
    public String revokeRefreshToken(@PathVariable String tokenId) {
        if (tokenStore instanceof JdbcTokenStore) {
            ((JdbcTokenStore) tokenStore).removeRefreshToken(tokenId);
        }
        return tokenId;
    }

}
</code>```

In the thymeleaf client I have

```<code>@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
                .and()
                .logout().logoutSuccessUrl("/");
    }

    @Bean
    public RestTemplate restTemplate(OAuth2AuthorizedClientService clientService) {
        RestTemplate restTemplate = new RestTemplate();
        List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
        if (CollectionUtils.isEmpty(interceptors)) {
            interceptors = new ArrayList<>();
        }
        interceptors.add(new AuthorizationHeaderInterceptor(clientService));
        restTemplate.setInterceptors(interceptors);
        return restTemplate;
    }

}
</code>```

How to really log out from the thymeleaf (token must be surely removed?)

答:
"Security" needs to be on every layer on your applications. But I guess by your post that you mean the authentication layer.

If you don't want your REST API to be available for use by everyone, you should add an authentication layer to it and at least a CORS policy. Think API keys, OAuth or plain old username/password authentication.

Body:
I have 3 application, one for authorization, one with resource (api rest) and one client in thymeleaf who consume the rest.

When I log out of my client, that don't seem to be a real log out, because when i click on login, that login me directly... use previous user.

I took Baeldung example, who are similar to mine and has same issue.

Authorization server
https://github.com/Baeldung/spring-security-oauth/tree/master/oauth-authorization-server

Resource server
https://github.com/Baeldung/spring-security-oauth/tree/master/oauth-resource-server-1

Thymeleaf client
https://github.com/Baeldung/spring-security-oauth/tree/master/clients-thymeleaf/oauth-ui-authorization-code-thymeleaf

In the Authorization server I have

@Controller
public class TokenController {

    @Resource(name = "tokenServices")
    private ConsumerTokenServices tokenServices;

    @Resource(name = "tokenStore")
    private TokenStore tokenStore;

    @RequestMapping(method = RequestMethod.POST, value = "/oauth/token/revokeById/{tokenId}")
    @ResponseBody
    public void revokeToken(HttpServletRequest request, @PathVariable String tokenId) {
        tokenServices.revokeToken(tokenId);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/tokens")
    @ResponseBody
    public List<String> getTokens() {
        Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientId("sampleClientId");
        return Optional.ofNullable(tokens).orElse(Collections.emptyList()).stream().map(OAuth2AccessToken::getValue).collect(Collectors.toList());
    }

    @RequestMapping(method = RequestMethod.POST, value = "/tokens/revokeRefreshToken/{tokenId:.*}")
    @ResponseBody
    public String revokeRefreshToken(@PathVariable String tokenId) {
        if (tokenStore instanceof JdbcTokenStore) {
            ((JdbcTokenStore) tokenStore).removeRefreshToken(tokenId);
        }
        return tokenId;
    }

}

In the thymeleaf client I have

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
                .and()
                .logout().logoutSuccessUrl("/");
    }

    @Bean
    public RestTemplate restTemplate(OAuth2AuthorizedClientService clientService) {
        RestTemplate restTemplate = new RestTemplate();
        List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
        if (CollectionUtils.isEmpty(interceptors)) {
            interceptors = new ArrayList<>();
        }
        interceptors.add(new AuthorizationHeaderInterceptor(clientService));
        restTemplate.setInterceptors(interceptors);
        return restTemplate;
    }

}

How to really log out from the thymeleaf (token must be surely removed?)


问:
Compare two __m128i values for total order
I need a way to compare values of type __m128i in C++ for a total order between any values of type __m128i. The type of order doesn't matter as long as it establishes a total order between all values of type __m128i. Hence the comparison might be less-than between 128-bit integers or something else entirely as long as is provides a total order.

I tried using the < operator, but that didn't return a bool, but instead seems to compare the vector components of __m128i (i.e. SIMD):

#include <emmintrin.h>

inline bool isLessThan(__m128i a, __m128i b) noexcept {
     // error: cannot convert '__vector(2) long int' to 'bool' in return
     return a < b;
}
```

Another possibility would be to use memcmp/strcmp or similar, but this would very likely not be optimal. Targeting modern Intel x86-64 CPUs with at least SSE4.2 and AVX2, are there any intrinsics / instructions I could use for such comparisons? How to do it?

PS: Similar questions have been asked for checking equality but not for ordering:

How to compare __m128 types?

Testing equality between two __m128i variables

答:
Here you go.

```<code>inline bool isLessThan( __m128i a, __m128i b )
{
    /* Compare 8-bit lanes for ( a < b ), store the bits in the low 16 bits of the
       scalar value: */
    const int less = _mm_movemask_epi8( _mm_cmplt_epi8( a, b ) );

    /* Compare 8-bit lanes for ( a > b ), store the bits in the low 16 bits of the
       scalar value: */
    const int greater = _mm_movemask_epi8( _mm_cmpgt_epi8( a, b ) );

    /* It's counter-intuitive, but this scalar comparison does the right thing.
       Essentially, integer comparison searches for the most significant bit that
       differs... */
    return less > greater;
}
</code>```

The order is less than ideal ’coz pcmpgtb treats these bytes as signed integers, but you said it’s not important for your use case.

Update: here’s a slightly slower version with uint128_t sort order.

```<code>// True if a < b, for unsigned 128 bit integers
inline bool cmplt_u128( __m128i a, __m128i b )
{
    // Flip the sign bits in both arguments.
    // Transforms 0 into -128 = minimum for signed bytes,
    // 0xFF into +127 = maximum for signed bytes
    const __m128i signBits = _mm_set1_epi8( (char)0x80 );
    a = _mm_xor_si128( a, signBits );
    b = _mm_xor_si128( b, signBits );

    // Now the signed byte comparisons will give the correct order
    const int less = _mm_movemask_epi8( _mm_cmplt_epi8( a, b ) );
    const int greater = _mm_movemask_epi8( _mm_cmpgt_epi8( a, b ) );
    return less > greater;
}
</code>```

We build unsigned compares out of signed by range-shifting the unsigned inputs to signed (by flipping the high bit = subtract 128).

Body:
I need a way to compare values of type __m128i in C++ for a total order between any values of type __m128i. The type of order doesn't matter as long as it establishes a total order between all values of type __m128i. Hence the comparison might be less-than between 128-bit integers or something else entirely as long as is provides a total order.

I tried using the < operator, but that didn't return a bool, but instead seems to compare the vector components of __m128i (i.e. SIMD):

#include <emmintrin.h>

inline bool isLessThan(__m128i a, __m128i b) noexcept {
     // error: cannot convert '__vector(2) long int' to 'bool' in return
     return a < b;
}

Another possibility would be to use memcmp/strcmp or similar, but this would very likely not be optimal. Targeting modern Intel x86-64 CPUs with at least SSE4.2 and AVX2, are there any intrinsics / instructions I could use for such comparisons? How to do it?

PS: Similar questions have been asked for checking equality but not for ordering:

How to compare __m128 types?

Testing equality between two __m128i variables

Body:
Here you go.

inline bool isLessThan( __m128i a, __m128i b )
{
    /* Compare 8-bit lanes for ( a < b ), store the bits in the low 16 bits of the
       scalar value: */
    const int less = _mm_movemask_epi8( _mm_cmplt_epi8( a, b ) );

    /* Compare 8-bit lanes for ( a > b ), store the bits in the low 16 bits of the
       scalar value: */
    const int greater = _mm_movemask_epi8( _mm_cmpgt_epi8( a, b ) );

    /* It's counter-intuitive, but this scalar comparison does the right thing.
       Essentially, integer comparison searches for the most significant bit that
       differs... */
    return less > greater;
}

The order is less than ideal ’coz pcmpgtb treats these bytes as signed integers, but you said it’s not important for your use case.

Update: here’s a slightly slower version with uint128_t sort order.

// True if a < b, for unsigned 128 bit integers
inline bool cmplt_u128( __m128i a, __m128i b )
{
    // Flip the sign bits in both arguments.
    // Transforms 0 into -128 = minimum for signed bytes,
    // 0xFF into +127 = maximum for signed bytes
    const __m128i signBits = _mm_set1_epi8( (char)0x80 );
    a = _mm_xor_si128( a, signBits );
    b = _mm_xor_si128( b, signBits );

    // Now the signed byte comparisons will give the correct order
    const int less = _mm_movemask_epi8( _mm_cmplt_epi8( a, b ) );
    const int greater = _mm_movemask_epi8( _mm_cmpgt_epi8( a, b ) );
    return less > greater;
}

We build unsigned compares out of signed by range-shifting the unsigned inputs to signed (by flipping the high bit = subtract 128).


问:
How to read information from .3gp and .mp4 using ffmpeg-php?
I have a bit of a problem with ffmpeg-php. I'm trying to get some information from video files  and it works pretty fine with file formats like .avi, .mpg or .flv  but when I try to use .3gp or .mp4 in:

```<code>$movie = new ffmpeg_movie('path/to/file/test.3gp');
</code>```

I get error like this :

```<code>ffmpeg_movie::__construct() []: ISO: File Type Major Brand: 3gp5
</code>```

or

```<code>ffmpeg_movie::__construct() []: ISO: File Type Major Brand: mp42
</code>```

I installed ffmpeg-php on WAMP using instructions found here:
How to install FFMpeg in WampServer 2.0 (Windows XP)

I need those information to send them to ffmpeg using exec(). Anyone could help me with this?

答: You could also use a pure php approach using PHP media reader</p>

Body:
I have a bit of a problem with ffmpeg-php. I'm trying to get some information from video files  and it works pretty fine with file formats like .avi, .mpg or .flv  but when I try to use .3gp or .mp4 in:

$movie = new ffmpeg_movie('path/to/file/test.3gp');

I get error like this :

ffmpeg_movie::__construct() []: ISO: File Type Major Brand: 3gp5

or

ffmpeg_movie::__construct() []: ISO: File Type Major Brand: mp42

I installed ffmpeg-php on WAMP using instructions found here:
How to install FFMpeg in WampServer 2.0 (Windows XP)

I need those information to send them to ffmpeg using exec(). Anyone could help me with this?


问:
Using a permission class on a detail route
How can I only apply a permission class to a detail route?</p>

```<code>class EventViewSet(viewsets.ModelViewSet):

    @detail_route(methods=['post'])
    def messages(self, request, pk=None):
        ### Check a permissions class.
        ...
</code>```

答:
in django rest 3.8 detail route is deprecated in favor of action route
so now it would look something like this.</p>
```<code>from rest_framework.decorators import api_view, permission_classes

class EventViewSet(viewsets.ModelViewSet):

    @action(
        methods=['post'],
        detail=True,
        permission_classes=[YourPermission]
        url_path='messages')
    def messages(self, request, pk=None):
        return Response("200", status=200)
</code>```

Body:
How can I only apply a permission class to a detail route?

class EventViewSet(viewsets.ModelViewSet):

    @detail_route(methods=['post'])
    def messages(self, request, pk=None):
        ### Check a permissions class.
        ...

Body:
in django rest 3.8 detail route is deprecated in favor of action route
so now it would look something like this.

from rest_framework.decorators import api_view, permission_classes

class EventViewSet(viewsets.ModelViewSet):

    @action(
        methods=['post'],
        detail=True,
        permission_classes=[YourPermission]
        url_path='messages')
    def messages(self, request, pk=None):
        return Response("200", status=200)


问:
Getting "Caused by: java.lang.IllegalStateException: HTTP Server cannot be loaded: No implementation of HttpServerFacade found on classpath." error
I am trying out the distributed random forest implementation of H2O using sparkling-water. But I am facing the following error when I run the spark-submit command.

```<code>Exception in thread "H2O Launcher thread" java.lang.ExceptionInInitializerError
    at water.init.NetworkInit.initializeNetworkSockets(NetworkInit.java:77)
    at water.H2O.startLocalNode(H2O.java:1621)
    at water.H2O.main(H2O.java:2081)
    at water.H2OStarter.start(H2OStarter.java:22)
    at water.H2OStarter.start(H2OStarter.java:47)
    at org.apache.spark.h2o.backends.internal.InternalBackendUtils$$anonfun$6$$anon$1.run(InternalBackendUtils.scala:173)
Caused by: java.lang.IllegalStateException: HTTP Server cannot be loaded: No implementation of HttpServerFacade found on classpath. Please refer to https://0xdata.atlassian.net/browse/TN-13 for details.
    at water.webserver.iface.HttpServerLoader.<clinit>(HttpServerLoader.java:16)
    ... 6 more
</code>```

I have tried out the solution mentioned at the location https://0xdata.atlassian.net/browse/TN-13

but for some reason it still isn't able to find the ai.h2o:h2o-jetty-8 on the classpath.

答:
I resolved the issue by adding the following maven coordinates to the packages option in spark-submit

--packages ai.h2o:h2o-jetty-8:3.24.0.3

Body:
I am trying out the distributed random forest implementation of H2O using sparkling-water. But I am facing the following error when I run the spark-submit command.

Exception in thread "H2O Launcher thread" java.lang.ExceptionInInitializerError
    at water.init.NetworkInit.initializeNetworkSockets(NetworkInit.java:77)
    at water.H2O.startLocalNode(H2O.java:1621)
    at water.H2O.main(H2O.java:2081)
    at water.H2OStarter.start(H2OStarter.java:22)
    at water.H2OStarter.start(H2OStarter.java:47)
    at org.apache.spark.h2o.backends.internal.InternalBackendUtils$$anonfun$6$$anon$1.run(InternalBackendUtils.scala:173)
Caused by: java.lang.IllegalStateException: HTTP Server cannot be loaded: No implementation of HttpServerFacade found on classpath. Please refer to https://0xdata.atlassian.net/browse/TN-13 for details.
    at water.webserver.iface.HttpServerLoader.<clinit>(HttpServerLoader.java:16)
    ... 6 more

I have tried out the solution mentioned at the location https://0xdata.atlassian.net/browse/TN-13

but for some reason it still isn't able to find the ai.h2o:h2o-jetty-8 on the classpath.


问:
How are fields set on an entity by Spring Data MongoDB?
I have a MongoRepository class

```<code>public interface UserRepository extends MongoRepository<User, Long> {

  User findById(Long id);
}
</code>```

and my Entity pojo looks like this

```<code>@Document(collection = "user")
class User {

  Long id;
  String name;
  Department department;
  …
}
</code>```

When I call the findBy method, a User object is returned. I want to know how does Spring Data MongoDB converts DBObject to Java object. I was under the impression that Spring Data MongoDB uses some sort of mapper (Jackson?) under the hood which would call setters/constructors method of the java(Entity) class based on the field names in the class or @Field Annotation. But to my surprise, the setters are never invoked. Only the default constructor is invoked.

Then how does the fields are set? The reason I am asking is if the setters are called, it would give me an option to set some other fields may be.

Thanks

答: Take a look at MappingMongoConverter class - it has the logic which does all this.</p>

Body:
I have a MongoRepository class

public interface UserRepository extends MongoRepository<User, Long> {

  User findById(Long id);
}

and my Entity pojo looks like this

@Document(collection = "user")
class User {

  Long id;
  String name;
  Department department;
  …
}

When I call the findBy method, a User object is returned. I want to know how does Spring Data MongoDB converts DBObject to Java object. I was under the impression that Spring Data MongoDB uses some sort of mapper (Jackson?) under the hood which would call setters/constructors method of the java(Entity) class based on the field names in the class or @Field Annotation. But to my surprise, the setters are never invoked. Only the default constructor is invoked.

Then how does the fields are set? The reason I am asking is if the setters are called, it would give me an option to set some other fields may be.

Thanks


问:
How to show search result in a TableView as drop down a TextField in JavaFX?
I need to search something in textfield, the result should show as dropdown in the same text field inside a tableview.</p>

答:
Regarding autocompletion: You can use a TextField and add an AutoComplete binding using ControlsFX TextFields:

```<code>TextField textField = new TextField();
TextFields.bindAutoCompletion(textField, "Paris", "Rome", "Amsterdam");
</code>```

I couldn't understand what you meant by "inside a tableview".

Body:
Regarding autocompletion: You can use a TextField and add an AutoComplete binding using ControlsFX TextFields:

TextField textField = new TextField();
TextFields.bindAutoCompletion(textField, "Paris", "Rome", "Amsterdam");

I couldn't understand what you meant by "inside a tableview".


问:
Should @JoinTable be specified in both sides of a @ManyToMany relationship?
I've an entity Course and an entity User. There's a many-to-many relation ship between course and user, since a course can have many users and a user can be enrolled in many courses. In both entities I've put the @ManyToMany annotation on the specific field, that is, in Course I have:

```<code>@ManyToMany
private List<RegisteredUser> members;
</code>```

and in User I have:

```<code>@ManyToMany
private List<Course> coursesTaken;
</code>```

Now, I know that this kind of many-to-many relationships are usually represented by a third table. I also know that there's the annotation @JoinTable which allows us to do that. What I don't know is if I should add this annotation @JoinTable over both fields in the two different entities or not. By the way, if I need to add to both, the names need to match right?

答:
You actually CAN use @JoinTable on both sides and often it makes perfect sense! I am talking out of experience after I had been looking for this solution for weeks.

Even though all throughout the internet, blogs and articles tell a different story - and the Javadoc of JPA is easily misunderstood (or wrong) in this way. I tried it after seeing this uncommented example in a book for professionals - and it worked.

How to do it:

Singer-Instrument-Association:
Singer side:

```<code>@ManyToMany
@JoinTable(name = "singer_instrument", joinColumns =
@JoinColumn(name = "SINGER_ID"), inverseJoinColumns = @JoinColumn(name = "INSTRUMENT_ID"))
public Set<Instrument> instruments;
</code>```

And exactly the same on the other side!
Instrument side:

```<code>@ManyToMany
@JoinTable(name = "singer_instrument",
joinColumns = @JoinColumn(name = "INSTRUMENT_ID"),
inverseJoinColumns = @JoinColumn(name = "SINGER_ID"))
public Set<Singer> singers;
</code>```

So, if you address the same join table, "singer_instrument", with the same name, it work's.
If you address one join table "singer_instrument" and one join table "instrument-singer" though, it will indead result in two different join tables in the database.

This makes a lot of sense, because a many-to-many relationship has no owning side - seen from the database perspective. Owning side means the side, that owns the foreign key of the relationship. But neither the table "singer" nor "instrument" have a foreign key referring to each other. The foreign keys are inside the neccessary join table between them.

The advantage of @JoinTable on both sides of the relation:
Let's say, a singer starts to learn a new instrument: You can add the instrument to singer (and vise versa, as it is bidirectional) and update/merge the singer. The update will update only the singer and the join table. It won't touch the instrument-table.

Now the other case - a guitar-course has ended, so you want to remove the connection between the guitar and the former course-participants/singers: After removing the instrument "guitar" from the singers (and vise versa!), you update/merge the instrument. The update will update only the instrument and the join table. It won't touch the singer-table.

If you had @JoinTable only on one side, you would always have to update/save/delete this side to safely handle the entries in the join table (the relationships between singers and instruments). In this case, you would have to update each singer, who ended the guitar course. That is not reflecting the type of relationship properly and can cause performance issues and conflicts during data transaction.

Body:
I've an entity Course and an entity User. There's a many-to-many relation ship between course and user, since a course can have many users and a user can be enrolled in many courses. In both entities I've put the @ManyToMany annotation on the specific field, that is, in Course I have:

@ManyToMany
private List<RegisteredUser> members;

and in User I have:

@ManyToMany
private List<Course> coursesTaken;

Now, I know that this kind of many-to-many relationships are usually represented by a third table. I also know that there's the annotation @JoinTable which allows us to do that. What I don't know is if I should add this annotation @JoinTable over both fields in the two different entities or not. By the way, if I need to add to both, the names need to match right?

Body:
You actually CAN use @JoinTable on both sides and often it makes perfect sense! I am talking out of experience after I had been looking for this solution for weeks.

Even though all throughout the internet, blogs and articles tell a different story - and the Javadoc of JPA is easily misunderstood (or wrong) in this way. I tried it after seeing this uncommented example in a book for professionals - and it worked.

How to do it:

Singer-Instrument-Association:
Singer side:

@ManyToMany
@JoinTable(name = "singer_instrument", joinColumns =
@JoinColumn(name = "SINGER_ID"), inverseJoinColumns = @JoinColumn(name = "INSTRUMENT_ID"))
public Set<Instrument> instruments;

And exactly the same on the other side!
Instrument side:

@ManyToMany
@JoinTable(name = "singer_instrument",
joinColumns = @JoinColumn(name = "INSTRUMENT_ID"),
inverseJoinColumns = @JoinColumn(name = "SINGER_ID"))
public Set<Singer> singers;

So, if you address the same join table, "singer_instrument", with the same name, it work's.
If you address one join table "singer_instrument" and one join table "instrument-singer" though, it will indead result in two different join tables in the database.

This makes a lot of sense, because a many-to-many relationship has no owning side - seen from the database perspective. Owning side means the side, that owns the foreign key of the relationship. But neither the table "singer" nor "instrument" have a foreign key referring to each other. The foreign keys are inside the neccessary join table between them.

The advantage of @JoinTable on both sides of the relation:
Let's say, a singer starts to learn a new instrument: You can add the instrument to singer (and vise versa, as it is bidirectional) and update/merge the singer. The update will update only the singer and the join table. It won't touch the instrument-table.

Now the other case - a guitar-course has ended, so you want to remove the connection between the guitar and the former course-participants/singers: After removing the instrument "guitar" from the singers (and vise versa!), you update/merge the instrument. The update will update only the instrument and the join table. It won't touch the singer-table.

If you had @JoinTable only on one side, you would always have to update/save/delete this side to safely handle the entries in the join table (the relationships between singers and instruments). In this case, you would have to update each singer, who ended the guitar course. That is not reflecting the type of relationship properly and can cause performance issues and conflicts during data transaction.