问:
The git local repository size and subfolder size are too different
i am new to git and github, I have some questions about the size of the github repository ：

the size of my repository on github is 38M

the size of local repository directory is 42.1M

my question is why the size of all sub directory in local repository is 3.06M

I tried to solve through git gc, but did not succeed, I even wonder if this is a problem, there is no idea，Anyone know about this? Thanks.

答:
The size of your working tree relative to the size of the database in the repo can vary for a lot of reasons.

On one hand, the repository is packed, compressed, and optimized using deltas.  On the other hand, the effectiveness of those techniques varies based on the content, and the repo contains all of your history whereas your work tree only contains one version (at any given time).

Regarding gc, the main thing it does is remove unreachable objects from the repo.  For example, if you work on a branch for a while, maybe add some large binary assets but later remove them; and then later you rebase the branch in such a way that the new history doesn't show the large binary asset at all... well, eventually gc should wipe out the original commits and the large binary asset, reclaiming some space.

But "unreachable" means not only that no refs can reach it, but also that the reflog can't reach it.  If you want to be sure you reclaim all unused space (and you're confident that you don't need to recover anything from the reflog) then you can wipe out the reflog and then run an "aggressive" gc.

As an aside on that point... Wiping out the reflog in theory is as easy as

```<code>git reflog expire --expire=now
</code>```

but I have seen this fail to remove reflog entries and I don't really know why.  It's possible to remove the actual log files (e.g. using rm in bash), but be careful; if you have any stashes they are also recorded under .git/logs and you probably don't want to destroy those.

The relative size of the repo (as measured in the .git folder) to the work tree may also be affected by whether you use LFS.  I'm not sure how LFS storage would be reflected in github's size reports.

If you've reclaimed all the space you can with gc, and LFS isn't a factor, then I'd say a 10:1 ratio seems surprising to me; but if you have a lot of binary files that change throughout your history, it's not beyond the realm of possibility.

Body:
The size of your working tree relative to the size of the database in the repo can vary for a lot of reasons.

On one hand, the repository is packed, compressed, and optimized using deltas.  On the other hand, the effectiveness of those techniques varies based on the content, and the repo contains all of your history whereas your work tree only contains one version (at any given time).

Regarding gc, the main thing it does is remove unreachable objects from the repo.  For example, if you work on a branch for a while, maybe add some large binary assets but later remove them; and then later you rebase the branch in such a way that the new history doesn't show the large binary asset at all... well, eventually gc should wipe out the original commits and the large binary asset, reclaiming some space.

But "unreachable" means not only that no refs can reach it, but also that the reflog can't reach it.  If you want to be sure you reclaim all unused space (and you're confident that you don't need to recover anything from the reflog) then you can wipe out the reflog and then run an "aggressive" gc.

As an aside on that point... Wiping out the reflog in theory is as easy as

git reflog expire --expire=now

but I have seen this fail to remove reflog entries and I don't really know why.  It's possible to remove the actual log files (e.g. using rm in bash), but be careful; if you have any stashes they are also recorded under .git/logs and you probably don't want to destroy those.

The relative size of the repo (as measured in the .git folder) to the work tree may also be affected by whether you use LFS.  I'm not sure how LFS storage would be reflected in github's size reports.

If you've reclaimed all the space you can with gc, and LFS isn't a factor, then I'd say a 10:1 ratio seems surprising to me; but if you have a lot of binary files that change throughout your history, it's not beyond the realm of possibility.


来源: stackexchange

问:
Storing User Input in a List and writing a loop to find a valid value from that list
New to coding...
i am a student and have been tasked with writing a code that asks the user to input a series of values that will i will store in a list and then to ask to input a value (continue this until user types done) and then to check to determine if it is found in the list of valid values.

I'm assuming this could be done with a while true loop to accomplish the input until 'done' is typed and i'm assuming a search using 'if' and 'in' would accomplish the second part.

I am struggling finding a while true using the list of input. i am using an integer input. what am i comparing the condition to if to continue the loop?

Any help is appreciated! The code below is what i wrote i test if i could store input in a list but the while true is where i'm struggling with what to compare.

```<code>while True:
    if list_of_inputs
list_of_inputs = input("Write numbers: ").split()
list_of_inputs = list(map(int , list_of_inputs))
print (list_of_inputs)
</code>```

答:
Here's some code that does what you described in the comments.

We use two while loops. The first one gets lines of input, one by one, and adds them to the list_of_inputs. If a line consisting of the string "done" is read we break out of the loop, and we don't add "done" to the list.

The second loop gets lines of input and tests whether or not they are present in list_of_inputs, printing an appropriate message. If the user inputs a line that is present in list_of_inputs we break out of the loop and the program ends.

```<code>print('Please enter values for the list, one value per line')
print('Enter "done" (without the quotes) to end the list')

list_of_inputs = []
while True:
    s = input('value: ')
    if s == 'done':
        break
    list_of_inputs.append(s)

print('Here is the list:')
print(list_of_inputs)

while True:
    s = input('Please enter a test value: ')
    if s in list_of_inputs:
        print('Yes!', repr(s), 'is in the list')
        break
    else:
        print('No', repr(s), 'is NOT in the list')
</code>```

test run

```<code>Please enter values for the list, one value per line
Enter "done" (without the quotes) to end the list
value: abc def
value: ghi
value: jkl
value: done
Here is the list:
['abc def', 'ghi', 'jkl']
Please enter a test value: def
No 'def' is NOT in the list
Please enter a test value: ghij
No 'ghij' is NOT in the list
Please enter a test value: jkl
Yes! 'jkl' is in the list
</code>```

ContentLicense: CC BY-SA 3.0

Body:
New to coding...
i am a student and have been tasked with writing a code that asks the user to input a series of values that will i will store in a list and then to ask to input a value (continue this until user types done) and then to check to determine if it is found in the list of valid values.

I'm assuming this could be done with a while true loop to accomplish the input until 'done' is typed and i'm assuming a search using 'if' and 'in' would accomplish the second part.

I am struggling finding a while true using the list of input. i am using an integer input. what am i comparing the condition to if to continue the loop?

Any help is appreciated! The code below is what i wrote i test if i could store input in a list but the while true is where i'm struggling with what to compare.

while True:
    if list_of_inputs
list_of_inputs = input("Write numbers: ").split()
list_of_inputs = list(map(int , list_of_inputs))
print (list_of_inputs)

Body:
Here's some code that does what you described in the comments.

We use two while loops. The first one gets lines of input, one by one, and adds them to the list_of_inputs. If a line consisting of the string "done" is read we break out of the loop, and we don't add "done" to the list.

The second loop gets lines of input and tests whether or not they are present in list_of_inputs, printing an appropriate message. If the user inputs a line that is present in list_of_inputs we break out of the loop and the program ends.

print('Please enter values for the list, one value per line')
print('Enter "done" (without the quotes) to end the list')

list_of_inputs = []
while True:
    s = input('value: ')
    if s == 'done':
        break
    list_of_inputs.append(s)

print('Here is the list:')
print(list_of_inputs)

while True:
    s = input('Please enter a test value: ')
    if s in list_of_inputs:
        print('Yes!', repr(s), 'is in the list')
        break
    else:
        print('No', repr(s), 'is NOT in the list')

test run

Please enter values for the list, one value per line
Enter "done" (without the quotes) to end the list
value: abc def
value: ghi
value: jkl
value: done
Here is the list:
['abc def', 'ghi', 'jkl']
Please enter a test value: def
No 'def' is NOT in the list
Please enter a test value: ghij
No 'ghij' is NOT in the list
Please enter a test value: jkl
Yes! 'jkl' is in the list


问:
How to populate a Combobox with items and one textbox
I have two ComboBoxes, based on the selection of the first, the seconds gets populated.

How to make the second ComboBox act or display a TextBox when Other is selected in first one, so user can enter numbers/letters.

 C#

```<code> public class MyViewModel
 {
     public ICommand UpdateCommand { get; private set; }

     private ObservableCollection<string> _Veh = new ObservableCollection<string>();

     private ObservableCollection<string> _VehTypes = new ObservableCollection<string>();
     private ObservableCollection<string> _cars = new ObservableCollection<string>();
     private ObservableCollection<string> _planes = new ObservableCollection<string>();

     public ObservableCollection<string> Veh
     {
         get { return _Veh; }
         set { SetProperty(ref _Veh, value); }
     }

     public ObservableCollection<string> VehTypes
     {
         get { return _VehTypes; }
         set { SetProperty(ref _VehTypes, value); }
     }

     public MyViewModel()
     {
         UpdateCommand = new DelegateCommand<object>(OnUpdate);

         _Veh.Add("Cars");
         _Veh.Add("Planes");
         _Veh.Add("Other");

         _Cars.Add("GM");
         _Cars.Add("BMW");
         _Cars.Add("Toyota");
         _Cars.Add("Honda");

         _planes.Add("AirBus");
         _planes.Add("Boing");
    }

    private void OnUpdate(object myobj)
    {
        _VehTypes.Clear();
        // Add new vehTypes based on _cars and _planes
    }
}
</code>```

 wpf

```<code><ComboBox Name="ComboVeh" ItemsSource="{Binding Veh}" >
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding UpdateCommand}"
                                                       CommandParameter="{Binding SelectedValue, ElementName=ComboVeh}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ComboBox>

<ComboBox Name="ComboVehTypes" ItemsSource="{Binding VehTypes}"/>
</code>```

答:
You could use a ContentControl with a trigger that sets the ContentTemplate property to a DataTemplate that contains a TextBox when "Other" is selected:

```<code><ComboBox Name="ComboVeh" ItemsSource="{Binding Veh}" >
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding UpdateCommand}"
                                           CommandParameter="{Binding SelectedValue, ElementName=ComboVeh}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ComboBox>

<ContentControl Content="{Binding SelectedValue, ElementName=ComboVeh}">
    <ContentControl.Style>
        <Style TargetType="ContentControl">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <ComboBox Name="ComboVehTypes" ItemsSource="{Binding DataContext.VehTypes, RelativeSource={RelativeSource AncestorType=ContentControl}}"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Content" Value="Other">
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <TextBox />
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ContentControl.Style>
</ContentControl>
</code>```

Body:
I have two ComboBoxes, based on the selection of the first, the seconds gets populated.

How to make the second ComboBox act or display a TextBox when Other is selected in first one, so user can enter numbers/letters.

 C#

 public class MyViewModel
 {
     public ICommand UpdateCommand { get; private set; }

     private ObservableCollection<string> _Veh = new ObservableCollection<string>();

     private ObservableCollection<string> _VehTypes = new ObservableCollection<string>();
     private ObservableCollection<string> _cars = new ObservableCollection<string>();
     private ObservableCollection<string> _planes = new ObservableCollection<string>();

     public ObservableCollection<string> Veh
     {
         get { return _Veh; }
         set { SetProperty(ref _Veh, value); }
     }

     public ObservableCollection<string> VehTypes
     {
         get { return _VehTypes; }
         set { SetProperty(ref _VehTypes, value); }
     }

     public MyViewModel()
     {
         UpdateCommand = new DelegateCommand<object>(OnUpdate);

         _Veh.Add("Cars");
         _Veh.Add("Planes");
         _Veh.Add("Other");

         _Cars.Add("GM");
         _Cars.Add("BMW");
         _Cars.Add("Toyota");
         _Cars.Add("Honda");

         _planes.Add("AirBus");
         _planes.Add("Boing");
    }

    private void OnUpdate(object myobj)
    {
        _VehTypes.Clear();
        // Add new vehTypes based on _cars and _planes
    }
}

 wpf

<ComboBox Name="ComboVeh" ItemsSource="{Binding Veh}" >

</ComboBox>

<ComboBox Name="ComboVehTypes" ItemsSource="{Binding VehTypes}"/>

Body:
You could use a ContentControl with a trigger that sets the ContentTemplate property to a DataTemplate that contains a TextBox when "Other" is selected:

<ComboBox Name="ComboVeh" ItemsSource="{Binding Veh}" >
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding UpdateCommand}"
                                           CommandParameter="{Binding SelectedValue, ElementName=ComboVeh}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ComboBox>

<ContentControl Content="{Binding SelectedValue, ElementName=ComboVeh}">
    <ContentControl.Style>
        <Style TargetType="ContentControl">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <ComboBox Name="ComboVehTypes" ItemsSource="{Binding DataContext.VehTypes, RelativeSource={RelativeSource AncestorType=ContentControl}}"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Content" Value="Other">
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <TextBox />
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ContentControl.Style>
</ContentControl>


问:
TypeScript - Is there an option to disallow using "! in front of anything except a boolean?
I understand this may be a classical javascript issue, but I too often found myself using :

```<code>if (!something) {
    //...
}
</code>```

to validate that this something is not undefined or null, in TypeScript.

This is very error-prone! When used on a number "0" will match, and when used on an enum the first item will match too (by default, the first item has a value of "0")!

Is there a way to deal with this in TypeScript? Is there a way to configure TypeScript to disallow an exclamation mark in front of anything except a boolean (and any)? Would this configuration make sense or am I missing something trivial?

Should :

```<code>if (something === null || something === undefined) {
    //...
}
</code>```

be used instead, to validate that something is defined or not? And is there a way to enforce this in a team?

答:
You can use the strict-boolean-expressions TSLint rule to disallow this sort of thing.

You can see some examples of the rule here, but this is an excerpt that's particularly relevant to your question. Places where the rule would find errors are marked with ~~~ and the error message is written next to that marking:

```<code>/*** PrefixUnary Expressions ***/
/*** Invalid ***/
!!numType;
  ~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is a number. Only booleans are allowed.]
!strType;
 ~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is a string. Only booleans are allowed.]
!objType;
 ~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
!enumType;
 ~~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is an enum. Only booleans are allowed.]
!!classType;
  ~~~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
!bwrapType;
 ~~~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
!!undefined;
 ~~~~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
  ~~~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is always falsy. Only booleans are allowed.]

/*** Valid ***/
!!boolFn();
!boolExpr;
!!boolType;

/*** If Statement ***/
/*** Invalid ***/
if (numType) { /* statements */ }
    ~~~~~~~                       [This type is not allowed in the 'if' condition because it is a number. Only booleans are allowed.]
if (objType) { /* statements */ }
    ~~~~~~~                       [This type is not allowed in the 'if' condition because it is always truthy. Only booleans are allowed.]
if (strType) { /* statements */ }
    ~~~~~~~                       [This type is not allowed in the 'if' condition because it is a string. Only booleans are allowed.]
if (bwrapType) { /* statements */ }
    ~~~~~~~~~                       [This type is not allowed in the 'if' condition because it is always truthy. Only booleans are allowed.]
if (strFn()) { /* statements */ }
    ~~~~~~~                       [This type is not allowed in the 'if' condition because it is a string. Only booleans are allowed.]
if (MyEnum.A) { /* statements */ }
    ~~~~~~~~                       [This type is not allowed in the 'if' condition because it is an enum. Only booleans are allowed.]
if (classType) { /* statements */ }
    ~~~~~~~~~                       [This type is not allowed in the 'if' condition because it is always truthy. Only booleans are allowed.]
</code>```

To answer your other side question briefly, the below code snipped is a nice way to check if something is defined or not:

```<code>if (something == null) {
    // will enter here if `something === null || something === undefined`
}
</code>```

See here for more details on the above

Body:
I understand this may be a classical javascript issue, but I too often found myself using :

if (!something) {
    //...
}

to validate that this something is not undefined or null, in TypeScript.

This is very error-prone! When used on a number "0" will match, and when used on an enum the first item will match too (by default, the first item has a value of "0")!

Is there a way to deal with this in TypeScript? Is there a way to configure TypeScript to disallow an exclamation mark in front of anything except a boolean (and any)? Would this configuration make sense or am I missing something trivial?

Should :

if (something === null || something === undefined) {
    //...
}

be used instead, to validate that something is defined or not? And is there a way to enforce this in a team?

Body:
You can use the strict-boolean-expressions TSLint rule to disallow this sort of thing.

You can see some examples of the rule here, but this is an excerpt that's particularly relevant to your question. Places where the rule would find errors are marked with ~~~ and the error message is written next to that marking:

/*** PrefixUnary Expressions ***/
/*** Invalid ***/
!!numType;
  ~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is a number. Only booleans are allowed.]
!strType;
 ~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is a string. Only booleans are allowed.]
!objType;
 ~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
!enumType;
 ~~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is an enum. Only booleans are allowed.]
!!classType;
  ~~~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
!bwrapType;
 ~~~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
!!undefined;
 ~~~~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
  ~~~~~~~~~  [This type is not allowed in the operand for the '!' operator because it is always falsy. Only booleans are allowed.]

/*** Valid ***/
!!boolFn();
!boolExpr;
!!boolType;

/*** If Statement ***/
/*** Invalid ***/
if (numType) { /* statements */ }
    ~~~~~~~                       [This type is not allowed in the 'if' condition because it is a number. Only booleans are allowed.]
if (objType) { /* statements */ }
    ~~~~~~~                       [This type is not allowed in the 'if' condition because it is always truthy. Only booleans are allowed.]
if (strType) { /* statements */ }
    ~~~~~~~                       [This type is not allowed in the 'if' condition because it is a string. Only booleans are allowed.]
if (bwrapType) { /* statements */ }
    ~~~~~~~~~                       [This type is not allowed in the 'if' condition because it is always truthy. Only booleans are allowed.]
if (strFn()) { /* statements */ }
    ~~~~~~~                       [This type is not allowed in the 'if' condition because it is a string. Only booleans are allowed.]
if (MyEnum.A) { /* statements */ }
    ~~~~~~~~                       [This type is not allowed in the 'if' condition because it is an enum. Only booleans are allowed.]
if (classType) { /* statements */ }
    ~~~~~~~~~                       [This type is not allowed in the 'if' condition because it is always truthy. Only booleans are allowed.]

To answer your other side question briefly, the below code snipped is a nice way to check if something is defined or not:

if (something == null) {
    // will enter here if `something === null || something === undefined`
}

See here for more details on the above


问:
cannot be cast to android.view.View$OnClickListener
I have a fragment for displaying data with many dynamic textViews,when implements setOnClickListener for dynamic view get this error:

```<code>com.Package.activity.DashboardActivity cannot be cast to android.view.View$OnClickListener
</code>```

Activity :DasgboardActivity : load fragment in frameLayout

```<code>  getSupportFragmentManager().beginTransaction().replace(R.id.container,new TestFragment()).commit();
</code>```

Fragment

```<code>public class TestFragment extends Fragment implements View.OnClickListener{

  CreateView createView;
List<Model> listData=new ArrayList();
  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
  createView = new CreateView();
  listData=db.getAllData();
  createView.makeView(getActivity,listData);
}

    @Override
    public void onClick(View v) {}

}
</code>```

CreateView class: for creating dynamic views:

```<code>  public View makeView(Context context, List<Model> words_List) {
        LinearLayout linearLayout = new LinearLayout(context);

        linearLayout.setOrientation(LinearLayout.HORIZONTAL);

            for (Model w : words_List) {

                TextView textView = new TextView(context);

                textView.setText(w.getW_text()+"");
                textView.setId(w.getW_id());
                textView.setTag(w.getW_id());

                    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));

       textView.setOnClickListener((View.OnClickListener) context);

                linearLayout.addView(textView);
            }

        return linearLayout;
    }
</code>```

in this line i got error :
   textView.setOnClickListener((View.OnClickListener) context);

My code completely working on activity but in fragment i have error

How i must fix my bug?

答:
It is the fragment that implements View.OnClickListener, not the activity.
Do this instead:

```<code>public class TestFragment extends Fragment{

    CreateView createView;
    List<Model> listData=new ArrayList();
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
         createView = new CreateView();
         listData=db.getAllData();
         createView.makeView(getActivity,listData);
    }

    View.OnClickListener textViewClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your listener code here
        }
    };
}
</code>```

And when you need to set the OnClickListener to the textView, use

```<code>textView.setOnClickListener(textViewClickListener);
</code>```

Body:
I have a fragment for displaying data with many dynamic textViews,when implements setOnClickListener for dynamic view get this error:

com.Package.activity.DashboardActivity cannot be cast to android.view.View$OnClickListener

Activity :DasgboardActivity : load fragment in frameLayout

  getSupportFragmentManager().beginTransaction().replace(R.id.container,new TestFragment()).commit();

Fragment

public class TestFragment extends Fragment implements View.OnClickListener{

  CreateView createView;
List<Model> listData=new ArrayList();
  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
  createView = new CreateView();
  listData=db.getAllData();
  createView.makeView(getActivity,listData);
}

    @Override
    public void onClick(View v) {}

}

CreateView class: for creating dynamic views:

  public View makeView(Context context, List<Model> words_List) {
        LinearLayout linearLayout = new LinearLayout(context);

        linearLayout.setOrientation(LinearLayout.HORIZONTAL);

            for (Model w : words_List) {

                TextView textView = new TextView(context);

                textView.setText(w.getW_text()+"");
                textView.setId(w.getW_id());
                textView.setTag(w.getW_id());

                    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));

       textView.setOnClickListener((View.OnClickListener) context);

                linearLayout.addView(textView);
            }

        return linearLayout;
    }

in this line i got error :
   textView.setOnClickListener((View.OnClickListener) context);

My code completely working on activity but in fragment i have error

How i must fix my bug?

Body:
It is the fragment that implements View.OnClickListener, not the activity.
Do this instead:

public class TestFragment extends Fragment{

    CreateView createView;
    List<Model> listData=new ArrayList();
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
         createView = new CreateView();
         listData=db.getAllData();
         createView.makeView(getActivity,listData);
    }

    View.OnClickListener textViewClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your listener code here
        }
    };
}

And when you need to set the OnClickListener to the textView, use

textView.setOnClickListener(textViewClickListener);


问:
SaaS provider wanting Single-Signon, do I need to integrate with several Identity Providers?
I work for a SaaS provider that is wanting to SSO enable our application to enterprise customers with our application acting as the service provider.

I understand the concepts behind what needs to happen and that SAML is an  appropriate solution for what we are looking to do.  Looking at bigger SaaS providers (slack, dropbox, new relic etc..) I can see they typically seem to integrate with a number of Identity Providers such as OneLogin, Bitium, Okta, Ping Identity etc... along with generic SAML support

As a smaller outfit we don't have the resources to partner and integrate with multiples of ID providers and to continue to add to that list as new providers emerge.

My question is that in order to provide SAML support in our application do I really need to have integrations with multiple IDPs or can I rely on a generic SAML implementation?

So if for example I used OneLogin to set up Single Sign On does that only enable SSO for clients who are using One Login as their Identity Provider?

答:
No. It is not required IMHO. As long as you are SAML 2.0 compliant (SP-Lite typically), you'll find that you'll have customers using many different commercial (and open source) Identity Provider solutions. The vast majority of SaaS vendors have not done anything specific to support different IDP implementations. The SaaS supports the SAML 2.0 spec and ends up having customers integrating successfully with the different (IDP) products. At that point they claim to "support" the different providers.

Adhere to the spec as best you can and the rest will take care of itself.


问:
preg_replace all numbers before underscore, than replace underscore and end
I would like to replace all numbers before the underscore, than replace underscore too and than end. Underscore should behave like "breakpoint".

I have strings with prefix, like:

```<code>0_xxxx
1_xxxx
2_xxxx
</code>```

and I have to remove that prefix.

Could someone please provide a example?

答:
You can use preg_replace to remove these prefixes using regexes.

```<code>echo preg_replace('/^\d+_/', '', '0_xxxx');
// Will output 'xxxx'
</code>```

This example code will remove all numbers followed by an underscore from the start of your string.

Body:
I would like to replace all numbers before the underscore, than replace underscore too and than end. Underscore should behave like "breakpoint".

I have strings with prefix, like:

0_xxxx
1_xxxx
2_xxxx

and I have to remove that prefix.

Could someone please provide a example?

Body:
You can use preg_replace to remove these prefixes using regexes.

echo preg_replace('/^\d+_/', '', '0_xxxx');
// Will output 'xxxx'

This example code will remove all numbers followed by an underscore from the start of your string.


问:
create a new variable within a for loop in R
I have a dataframe Fix with many variables, among these, there is CURRENT_ID, which is numeric and is between 1 and a number that varies (e.g., in certain cases 12, in other 15, etc.), and also a variable called nitem, that represents the number of the item in my experiment. For each trial and each subject, I would like to identify the minimum and the maximum CURRENT_ID. Then I would like to create a new variable called Remove. In Remove I would like to have a value of 1 if the CURRENT_ID is the minimum or maximum for each trial and participant, and a value of 0, for all the other rows. Following is an example of the data I have and the output I would like to obtain:

```<code>SESSION_LABEL   TRIAL_INDEX CURRENT_ID  nitem   OUTPUT
ppt01           1           1           4       1
ppt01           1           1           4       1
ppt01           1           4           4       0
ppt01           1           2           4       0
ppt01           1           2           4       0
ppt01           1           2           4       0
ppt01           1           4           4       0
ppt01           1           5           4       0
ppt01           1           6           4       0
ppt01           1           7           4       0
ppt01           1           8           4       0
ppt01           1           10          4       0
ppt01           1           11          4       0
ppt01           1           11          4       0
ppt01           1           12          4       0
ppt01           1           13          4       0
ppt01           1           13          4       0
ppt01           1           14          4       1
ppt01           1           1           4       1
ppt01           1           1           4       1
ppt01           2           2           2       0
ppt01           2           1           2       1
ppt01           2           5           2       0
ppt01           2           3           2       0
ppt01           2           4           2       0
ppt01           2           5           2       0
ppt01           2           5           2       0
ppt01           2           5           2       0
ppt01           2           6           2       0
ppt01           2           7           2       0
ppt01           2           8           2       0
ppt01           2           10          2       0
ppt01           2           10          2       0
ppt01           2           11          2       0
ppt01           2           13          2       0
ppt01           2           13          2       0
ppt01           2           13          2       0
ppt01           2           14          2       1
ppt01           2           3           2       0
ppt01           2           2           2       0
ppt01           2           1           2       1
ppt01           2           1           2       1
ppt01           2           1           2       1
ppt01           2           5           2       0
ppt01           2           4           2       0
ppt01           2           4           2       0
ppt01           2           5           2       0
ppt01           2           7           2       0
ppt01           2           9           2       0
ppt01           2           10          2       0
ppt01           2           12          2       0
ppt01           2           10          2       0
ppt01           2           10          2       0
ppt01           2           4           2       0
ppt01           2           5           2       0
ppt01           2           4           2       0
ppt01           2           6           2       0
ppt04           2           1           8       1
ppt04           2           1           8       1
ppt04           2           2           8       0
ppt04           2           3           8       0
ppt04           2           4           8       0
ppt04           2           5           8       0
ppt04           2           6           8       0
ppt04           2           7           8       0
ppt04           2           8           8       0
ppt04           2           7           8       0
ppt04           2           6           8       0
ppt04           2           8           8       0
ppt04           2           8           8       0
ppt04           2           10          8       0
ppt04           2           9           8       0
ppt04           2           10          8       0
ppt04           2           13          8       0
ppt04           2           14          8       1
ppt04           2           14          8       1
ppt04           2           1           8       1
ppt04           3           2           10      0
ppt04           3           2           10      0
ppt04           3           2           10      0
ppt04           3           3           10      0
ppt04           3           2           10      0
ppt04           3           4           10      0
ppt04           3           5           10      0
ppt04           3           6           10      0
ppt04           3           7           10      0
ppt04           3           9           10      0
ppt04           3           11          10      0
ppt04           3           12          10      0
ppt04           3           12          10      0
ppt04           3           13          10      0
ppt04           3           14          10      1
ppt04           3           14          10      1
</code>```

Here is my attempt.

```<code> for (j in 1:nrow(Fix)){
   Fix$Remove[j] <-ifelse(by(Fix$CURRENT_ID, list(Fix$SESSION_LABEL,Fix$nitem), max), 1,
                            ifelse(by(Fix$CURRENT_ID, list(Fix$SESSION_LABEL,Fix$nitem), min), 1,0))
   }
</code>```

Also, I am not sure if a for loop is the best day to do it.

答:
You can do with base R:

```<code>Fix <- within(Fix, {
  mx <- ave(CURRENT_ID, SESSION_LABEL, nitem, FUN=max)
  mn <- ave(CURRENT_ID, SESSION_LABEL, nitem, FUN=min)
  Remove <- ifelse(CURRENT_ID==mx | CURRENT_ID==mn, 1, 0)
})
</code>```

But testing the result with your data gives:

```<code>which(Fix$Remove!=Fix$OUTPUT)
# [1] 78 79 80 82
</code>```

Body:
I have a dataframe Fix with many variables, among these, there is CURRENT_ID, which is numeric and is between 1 and a number that varies (e.g., in certain cases 12, in other 15, etc.), and also a variable called nitem, that represents the number of the item in my experiment. For each trial and each subject, I would like to identify the minimum and the maximum CURRENT_ID. Then I would like to create a new variable called Remove. In Remove I would like to have a value of 1 if the CURRENT_ID is the minimum or maximum for each trial and participant, and a value of 0, for all the other rows. Following is an example of the data I have and the output I would like to obtain:

SESSION_LABEL   TRIAL_INDEX CURRENT_ID  nitem   OUTPUT
ppt01           1           1           4       1
ppt01           1           1           4       1
ppt01           1           4           4       0
ppt01           1           2           4       0
ppt01           1           2           4       0
ppt01           1           2           4       0
ppt01           1           4           4       0
ppt01           1           5           4       0
ppt01           1           6           4       0
ppt01           1           7           4       0
ppt01           1           8           4       0
ppt01           1           10          4       0
ppt01           1           11          4       0
ppt01           1           11          4       0
ppt01           1           12          4       0
ppt01           1           13          4       0
ppt01           1           13          4       0
ppt01           1           14          4       1
ppt01           1           1           4       1
ppt01           1           1           4       1
ppt01           2           2           2       0
ppt01           2           1           2       1
ppt01           2           5           2       0
ppt01           2           3           2       0
ppt01           2           4           2       0
ppt01           2           5           2       0
ppt01           2           5           2       0
ppt01           2           5           2       0
ppt01           2           6           2       0
ppt01           2           7           2       0
ppt01           2           8           2       0
ppt01           2           10          2       0
ppt01           2           10          2       0
ppt01           2           11          2       0
ppt01           2           13          2       0
ppt01           2           13          2       0
ppt01           2           13          2       0
ppt01           2           14          2       1
ppt01           2           3           2       0
ppt01           2           2           2       0
ppt01           2           1           2       1
ppt01           2           1           2       1
ppt01           2           1           2       1
ppt01           2           5           2       0
ppt01           2           4           2       0
ppt01           2           4           2       0
ppt01           2           5           2       0
ppt01           2           7           2       0
ppt01           2           9           2       0
ppt01           2           10          2       0
ppt01           2           12          2       0
ppt01           2           10          2       0
ppt01           2           10          2       0
ppt01           2           4           2       0
ppt01           2           5           2       0
ppt01           2           4           2       0
ppt01           2           6           2       0
ppt04           2           1           8       1
ppt04           2           1           8       1
ppt04           2           2           8       0
ppt04           2           3           8       0
ppt04           2           4           8       0
ppt04           2           5           8       0
ppt04           2           6           8       0
ppt04           2           7           8       0
ppt04           2           8           8       0
ppt04           2           7           8       0
ppt04           2           6           8       0
ppt04           2           8           8       0
ppt04           2           8           8       0
ppt04           2           10          8       0
ppt04           2           9           8       0
ppt04           2           10          8       0
ppt04           2           13          8       0
ppt04           2           14          8       1
ppt04           2           14          8       1
ppt04           2           1           8       1
ppt04           3           2           10      0
ppt04           3           2           10      0
ppt04           3           2           10      0
ppt04           3           3           10      0
ppt04           3           2           10      0
ppt04           3           4           10      0
ppt04           3           5           10      0
ppt04           3           6           10      0
ppt04           3           7           10      0
ppt04           3           9           10      0
ppt04           3           11          10      0
ppt04           3           12          10      0
ppt04           3           12          10      0
ppt04           3           13          10      0
ppt04           3           14          10      1
ppt04           3           14          10      1

Here is my attempt.

 for (j in 1:nrow(Fix)){
   Fix$Remove[j] <-ifelse(by(Fix$CURRENT_ID, list(Fix$SESSION_LABEL,Fix$nitem), max), 1,
                            ifelse(by(Fix$CURRENT_ID, list(Fix$SESSION_LABEL,Fix$nitem), min), 1,0))
   }

Also, I am not sure if a for loop is the best day to do it.

Body:
You can do with base R:

Fix <- within(Fix, {
  mx <- ave(CURRENT_ID, SESSION_LABEL, nitem, FUN=max)
  mn <- ave(CURRENT_ID, SESSION_LABEL, nitem, FUN=min)
  Remove <- ifelse(CURRENT_ID==mx | CURRENT_ID==mn, 1, 0)
})

But testing the result with your data gives:

which(Fix$Remove!=Fix$OUTPUT)
# [1] 78 79 80 82


问:
PlaylistItems: list does not return videoId when using part:id without snippet
Trying to manage the "cost" of API request and so to generate a delta of videos that were added to a playlist since last API request

Would like to make the "0" cost request of just fetching the videoIds before matching getting additional details about the Video in the playlist

GET https://www.googleapis.com/youtube/v3/playlistItems?part=id&playlistId=PLlTLHnxSVuIyeEZPBIQF_krewJkY2JSwi&key={YOUR_API_KEY}

The response is like below
"items": [
  {

"kind": "youtube#playlistItem",
   "etag": "\"5g01s4-wS2b4VpScndqCYc5Y-8k/2wturocJM7aMkvG4Zrmv45tbyWY\"",
   "id": "UExsVExIbnhTVnVJeWVFWlBCSVFGX2tyZXdKa1kySlN3aS4xMjU2MjFGMDJBNEUzQzcw"
  },

The playlistItem id cannot be used in the video list to get additional info about the video and instead part:"snippet" which has a cost associated with it has to be added to the playlistItems request. Is this a bug or intentional ? Also is there a way to map the playlistItem-id to videoId/ResourceId ?

答:
Firstly, all calls have a cost. No matter what it is. Just how much depends on your request.  </p>

<p>Yes, this is by design. They want to limit as much as possible the amount of calls to the system. This will make for better stream lining of call requests, as well as reducing strain on the site.  </p>

Body:
Firstly, all calls have a cost. No matter what it is. Just how much depends on your request.

Yes, this is by design. They want to limit as much as possible the amount of calls to the system. This will make for better stream lining of call requests, as well as reducing strain on the site.


问:
Why Ruby inject method cannot sum up string lengths without initial value?
Why the following code issues an error ?

```<code>['hello','stack','overflow'].inject{|memo,s|memo+s.length}

TypeError: can't convert Fixnum into String
        from (irb):2:in `+'
        from (irb):2:in `block in irb_binding'
        from (irb):2:in `each'
        from (irb):2:in `inject'
        from (irb):2
</code>```

If the initial value is passed, it works OK:

```<code>['hello','stack','overflow'].inject(0){|memo,s|memo+s.length}
=> 18
</code>```

答:
As the error message already tells you, the problem is that you have a TypeError. Just because Ruby is dynamically and implicitly typed doesn't mean that you don't have to think about types.

The type of Enumerable#inject without an explicit accumulator (this is usually called reduce) is something like

```<code>reduce :: [a] → (a → a → a) → a
</code>```

or in a more Rubyish notation I just made up

```<code>Enumerable[A]#inject {|A, A| A } → A
</code>```

You will notice that all the types are the same. The element type of the Enumerable, the two argument types of the block, the return type of the block and the return type of the overall method.

In your case, the types for the block just don't add up. The block gets passed two Strings and it is supposed to return a String. But you call the + method on the first argument (which is a String) with an argument that is an Integer. But String#+ doesn't take an Integer it only takes a String or more precisely something which can be converted to a String, i.e. something that responds to #to_str. That's why you get a TypeError for String#+.

The type of Enumerable#inject with an explicit accumulator (this is usually called fold) is something like

```<code>fold :: [b] → a → (a → b → a) → a
</code>```

or

```<code>Enumerable[B]#inject(A) {|A, B| A } → A
</code>```

Here you see that the accumulator can have a different type than the element type of the collection. Which is precisely what you need.

These two rules generally get you through all Enumerable#inject-related problems:

the type of the accumulator and the return type of the block must be the same

when not passing an explicit accumulator, the type of the accumulator is the same as the element type

Rule #1 will most often bite you when you do something like

```<code>acc[key] = value
</code>```

in your block, because assignments evaluate to the assigned value, not the receiver of the assignment. You'll have to replace this with

```<code>acc.tap { acc[key] = value }
</code>```

In your particular case, the two solutions have already been mentioned. Either use an explicit accumulator

```<code>ary.reduce(0){|acc, e| acc + e.length }
</code>```

or convert to integers first

```<code>ary.map(&:length).reduce(:+)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Why the following code issues an error ?

['hello','stack','overflow'].inject{|memo,s|memo+s.length}

TypeError: can't convert Fixnum into String
        from (irb):2:in `+'
        from (irb):2:in `block in irb_binding'
        from (irb):2:in `each'
        from (irb):2:in `inject'
        from (irb):2

If the initial value is passed, it works OK:

['hello','stack','overflow'].inject(0){|memo,s|memo+s.length}
=> 18

Body:
As the error message already tells you, the problem is that you have a TypeError. Just because Ruby is dynamically and implicitly typed doesn't mean that you don't have to think about types.

The type of Enumerable#inject without an explicit accumulator (this is usually called reduce) is something like

reduce :: [a] → (a → a → a) → a

or in a more Rubyish notation I just made up

Enumerable[A]#inject {|A, A| A } → A

You will notice that all the types are the same. The element type of the Enumerable, the two argument types of the block, the return type of the block and the return type of the overall method.

In your case, the types for the block just don't add up. The block gets passed two Strings and it is supposed to return a String. But you call the + method on the first argument (which is a String) with an argument that is an Integer. But String#+ doesn't take an Integer it only takes a String or more precisely something which can be converted to a String, i.e. something that responds to #to_str. That's why you get a TypeError for String#+.

The type of Enumerable#inject with an explicit accumulator (this is usually called fold) is something like

fold :: [b] → a → (a → b → a) → a

or

Enumerable[B]#inject(A) {|A, B| A } → A

Here you see that the accumulator can have a different type than the element type of the collection. Which is precisely what you need.

These two rules generally get you through all Enumerable#inject-related problems:

the type of the accumulator and the return type of the block must be the same

when not passing an explicit accumulator, the type of the accumulator is the same as the element type

Rule #1 will most often bite you when you do something like

acc[key] = value

in your block, because assignments evaluate to the assigned value, not the receiver of the assignment. You'll have to replace this with

acc.tap { acc[key] = value }

In your particular case, the two solutions have already been mentioned. Either use an explicit accumulator

ary.reduce(0){|acc, e| acc + e.length }

or convert to integers first

ary.map(&:length).reduce(:+)


问:
“Exception in thread ”main“ java.lang.StackOverflowError” in Quick sort for sorted, reversed and Identical data of size greater than 10000
I have tried to implement quick sort algorithm for all the inputs of different data size and formats. The basic code for partition is:

```<code>public static void QuickSortAlgorithm(int[] array) {
    QuickSort(array, 0, array.length-1);
}

public static void QuickSort(int[] A, int p, int r) {
    if (p < r) {
        int q = Partition(A, p, r);
        QuickSort(A, p, q - 1);
        QuickSort(A, q + 1, r);
    }
}

public static int Partition(int[] A, int p, int r) {
    int x = A[r];
    int i = p - 1;
    for (int j = p; j <= r - 1; j++) {
        if (A[j] <= x) {
            i = i + 1;
            int temp1;
            temp1 = A[i];
            A[i] = A[j];
            A[j] = temp1;
        }
    }
    int temp2;
    temp2 = A[i + 1];
    A[i + 1] = A[r];
    A[r] = temp2;

    return i + 1;

}
</code>```

}

But, it works fine for random data of size up to 80,000. But in case of sorted and reversed data it throws error "“Exception in thread ”main“ java.lang.StackOverflowError”. I have tried to run it through command line, passing file name as an argument.

```<code>java -Xss1m QuickSortProgram  sorted_40000.txt
</code>```

But still it throws error. How to solve it? I need to run the program via command line. Thanks.

答:
Sorted and reverse-sorted data are troublesome cases for your particular pivot-selection approach of choosing the last element of the starting partition.  You will always get zero elements in one of the sub-partitions (supposing that you don't attribute the pivot itself to either one).  If you employ a naive implementation of the overall sort, then that means you will recurse to a depth equal to the number of elements to be sorted, and that sets you up for running out of stack space.

Reverse-sorted is in fact a worst case, for even if you solve the recursion depth problem, you'll still get quadratic performance in the size of the input.

There are several things you could do.  The first is to fix the overall sort so that it is not subject to this kind of problem at all.  You can do this by taking a hybrid iterative / recursive approach, wherein the larger of each pair of sub-partitions is sorted without recursing.  This reliably limits the recursion depth to at most log2(n) for inputs of size n.  Example:

```<code>static void quickSort(int[] a, int p, int r) {
    while (r - p > 1) {
        int q = Partition(a, p, r);

        if (q - p <= (r - p) / 2) {
            // the left-hand partition is smaller; sort it recursively
            quickSort(a, p, q - 1);
            // update p so as to sort the right-hand partition iteratively
            p = q + 1;
        } else {
            // the right-hand partition is smaller; sort it recursively
            quickSort(a, q + 1, r);
            // update r so as to sort the left-hand partition iteratively
            r = q - 1;
        }
    }
}
</code>```

You could additionally consider a more advanced pivot selection algorithm.  Median-of-three would improve behavior in the cases where the input is initially sorted or reverse-sorted, though there are median-of-three killer inputs that can still elicit quadratic behavior.  Alternatively, random pivot selection affords no reliable killer inputs, and although behavior is only probabilistically O(n log(n)), the chances of significant differences from that scaling rule become vanishingly small as the size of the input increases.

Body:
I have tried to implement quick sort algorithm for all the inputs of different data size and formats. The basic code for partition is:

public static void QuickSortAlgorithm(int[] array) {
    QuickSort(array, 0, array.length-1);
}

public static void QuickSort(int[] A, int p, int r) {
    if (p < r) {
        int q = Partition(A, p, r);
        QuickSort(A, p, q - 1);
        QuickSort(A, q + 1, r);
    }
}

public static int Partition(int[] A, int p, int r) {
    int x = A[r];
    int i = p - 1;
    for (int j = p; j <= r - 1; j++) {
        if (A[j] <= x) {
            i = i + 1;
            int temp1;
            temp1 = A[i];
            A[i] = A[j];
            A[j] = temp1;
        }
    }
    int temp2;
    temp2 = A[i + 1];
    A[i + 1] = A[r];
    A[r] = temp2;

    return i + 1;

}

}

But, it works fine for random data of size up to 80,000. But in case of sorted and reversed data it throws error "“Exception in thread ”main“ java.lang.StackOverflowError”. I have tried to run it through command line, passing file name as an argument.

java -Xss1m QuickSortProgram  sorted_40000.txt

But still it throws error. How to solve it? I need to run the program via command line. Thanks.

Body:
Sorted and reverse-sorted data are troublesome cases for your particular pivot-selection approach of choosing the last element of the starting partition.  You will always get zero elements in one of the sub-partitions (supposing that you don't attribute the pivot itself to either one).  If you employ a naive implementation of the overall sort, then that means you will recurse to a depth equal to the number of elements to be sorted, and that sets you up for running out of stack space.

Reverse-sorted is in fact a worst case, for even if you solve the recursion depth problem, you'll still get quadratic performance in the size of the input.

There are several things you could do.  The first is to fix the overall sort so that it is not subject to this kind of problem at all.  You can do this by taking a hybrid iterative / recursive approach, wherein the larger of each pair of sub-partitions is sorted without recursing.  This reliably limits the recursion depth to at most log2(n) for inputs of size n.  Example:

static void quickSort(int[] a, int p, int r) {
    while (r - p > 1) {
        int q = Partition(a, p, r);

        if (q - p <= (r - p) / 2) {
            // the left-hand partition is smaller; sort it recursively
            quickSort(a, p, q - 1);
            // update p so as to sort the right-hand partition iteratively
            p = q + 1;
        } else {
            // the right-hand partition is smaller; sort it recursively
            quickSort(a, q + 1, r);
            // update r so as to sort the left-hand partition iteratively
            r = q - 1;
        }
    }
}

You could additionally consider a more advanced pivot selection algorithm.  Median-of-three would improve behavior in the cases where the input is initially sorted or reverse-sorted, though there are median-of-three killer inputs that can still elicit quadratic behavior.  Alternatively, random pivot selection affords no reliable killer inputs, and although behavior is only probabilistically O(n log(n)), the chances of significant differences from that scaling rule become vanishingly small as the size of the input increases.


问:
get jackson to ignore a field in a map
I am combining Spring Boot and jongo/mongo to create a dynamic mongo app that does not use POJO's.  Everything in and out of the database is a Map<String, Object>.  I have everything working exactly the way I want, except one thing.  I don't want to send _id from mongo to the client.  This system uses a "mark obsolete and insert new record" style of updates so we can maintain a change history for the document.  therefore, I don't want any client to even be tempted to use the _id field, I have another I want them to use.

Now I find all kinds of examples on how to ignore fields in pojo's, but i want to write a Jackson Map serializer that ignores a specific value of the map.  I can't find anything like that yet.  I suppose gson would do as well, I just don't currently have spring configured for gson.

any idea how to write this serializer?

答:
If you have Guava in your project, filter your map:

```<code>Map<String, Object> filtered = Maps.filterKeys(map, (k)-> !"_id".equals(k));
</code>```

Serialize the filtered map.

Without Guava, make a copy of the map. Call copy.remove("_id").
Serialize copy.

Title: get jackson to ignore a field in a map

Body:
If you have Guava in your project, filter your map:

Map<String, Object> filtered = Maps.filterKeys(map, (k)-> !"_id".equals(k));

Serialize the filtered map.

Without Guava, make a copy of the map. Call copy.remove("_id").
Serialize copy.


问:
Git Bash (mintty) is extremely slow on Windows 10 OS
I installed Git on my Windows 10 a couple of months ago. It worked well for some time. But now, it's running very slow.

The git status command takes 7 seconds to execute, and git stash takes many minutes for stashing (even if there is nothing to stash). Also, I would like to point out that git status prints the result instantaneously, but I can not enter a new command for a few seconds, as shown in the image below.

I have tried solutions to similar problems like link1, link2, etc., but none of these have worked.

P.S.: I use Windows Defender antivirus, and it is NOT making my Bash slow. Also, cmd takes more time to execute git commands while git bash takes longer to run any command.

Update: I have switched to Ubuntu, and therefore, I don't use Windows presently. So, there is no way I can check if any of the solutions work for me. I have accepted the answer provided by @pschild since it has the most upvotes and seems to have worked for many people.

答:
I had the same problem once and what I found is that the issue for me was with  __git_ps1, basically a variable that includes status informationlike branch name, detached head state, in the git dir, in a bare repo, in the middle of cherry picking or rebasing or merging.

In order to speed up your git bash, go to $GitHome\etc\profile and comment out the if-then where __git_ps1 is added to PS1.

Anyway the information that you are commenting out are quite useful, expecially if you are at the beginning with GIT.
Here is a faster version, found on the internet and used by me quite succesfully on my system:

```<code>fast_git_ps1 ()
{
    printf -- "$(git branch 2>/dev/null | grep -e '\* ' | sed 's/^..\(.*\)/ {\1} /')"
}

PS1='\[\033]0;$MSYSTEM:\w\007
\033[32m\]\u@\h \[\033[33m\w$(fast_git_ps1)\033[0m\]
$ '
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I had the same problem once and what I found is that the issue for me was with  __git_ps1, basically a variable that includes status informationlike branch name, detached head state, in the git dir, in a bare repo, in the middle of cherry picking or rebasing or merging.

In order to speed up your git bash, go to $GitHome\etc\profile and comment out the if-then where __git_ps1 is added to PS1.

Anyway the information that you are commenting out are quite useful, expecially if you are at the beginning with GIT.
Here is a faster version, found on the internet and used by me quite succesfully on my system:

fast_git_ps1 ()
{
    printf -- "$(git branch 2>/dev/null | grep -e '\* ' | sed 's/^..\(.*\)/ {\1} /')"
}

PS1='\[\033]0;$MSYSTEM:\w\007
\033[32m\]\u@\h \[\033[33m\w$(fast_git_ps1)\033[0m\]
$ '


问:
How can I mock SOAPConnection and SOAPConnectionFactory
Here is my code:

URL url = new URL(getURL());
SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnFactory.createConnection();`
response=soapConnection.call(soapMsg, url);
```

<p>I'm trying to create a mock for <code>SOAPConnection</code> but I get an exception.
Can anyone suggest me any work-around for this? </p>

<p>My test is something like this:
I created a <code>SOAPMessage</code> object and <code>URL</code> object.     </p>

<pre class="lang-java prettyprint-override"><code>Resource classUnderTest = new Resource();
SOAPConnection mockConnection = EasyMock.createMock(SOAPConnection.class);
EasyMock.expect(mockConnection.call(soapmsg, url)).andReturn(soapMsg);
EasyMock.replay(mockConnection);
WhiteBox.setinternalState(classUnderTest, SOAPConnection.class, mockConnection);
</code>```

答: A better approach might be to mock the entire service on a localhost port. I've written a small library which does most of the heavily lifting.</p>

Body:
Here is my code:

URL url = new URL(getURL());
SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnFactory.createConnection();`
response=soapConnection.call(soapMsg, url);

I'm trying to create a mock for SOAPConnection but I get an exception.
Can anyone suggest me any work-around for this?

My test is something like this:
I created a SOAPMessage object and URL object.

Resource classUnderTest = new Resource();
SOAPConnection mockConnection = EasyMock.createMock(SOAPConnection.class);
EasyMock.expect(mockConnection.call(soapmsg, url)).andReturn(soapMsg);
EasyMock.replay(mockConnection);
WhiteBox.setinternalState(classUnderTest, SOAPConnection.class, mockConnection);


问:
How to limit tx_news teaser and bodytext length in Backend TCA?
For limiting the maximum length of a news title, i can use this tsConfig setting:

```<code>TCEFORM.tx_news_domain_model_news.title.config.max = 70
</code>```

Is it possible to set such a limitation also for teaser and bodytext of news records? Since these are not simple input fields but textareas or RTE fields, it doesn´t seem to be that easy to limit their length. Is it possible nevertheless?

答:
max does not apply to RTE fields. You can try to limit the length in an editor plugin, e.g. CK Editor Plugin (for TYPO3 8).
Keep in mind that there is not server side length validation.

Body:
For limiting the maximum length of a news title, i can use this tsConfig setting:

TCEFORM.tx_news_domain_model_news.title.config.max = 70

Is it possible to set such a limitation also for teaser and bodytext of news records? Since these are not simple input fields but textareas or RTE fields, it doesn´t seem to be that easy to limit their length. Is it possible nevertheless?


问:
Rotate image with one finger
I'm trying to make a volume knob like this:

https://s-media-cache-ak0.pinimg.com/736x/29/b5/85/29b58559e3d8a09dcd7e1a47c700ca76.jpg

But I only want to use one finger, UIGestureRotate is great but only supports rotation with two fingers and I don't seem to find the solution for UIPanGestureRecognizer to rotate as I want it to? Is there a simple way to simulate the second finger in rotategesture or do I have to calculate pan?

答:
If you ignore gesture recognizers and override touches handlers on a view, you can use math to do this. With a little trig, take an arbitrary anchor point along an axis (say 9 o'clock on the knob), and your touches' locations on the plane with (0, 0) at the center of your knob. Say your anchor point is at (-3, 0) and your touch is at (-1, 1) for the sake of simplicity. Take the arctan of the change in y over the change in x, in this case arctan of 1/2, which is roughly 0.464 radians, or roughly 26.585 degrees. You would rotate your knob 26.6 degrees clockwise (in this case) from your anchor point to have your knob follow your touch. In Swift:

```<code>//Assume you have an anchor point "anchor" and a touch location "loc"
let radiansToRotate = atan2(loc.y - anchor.y, loc.x - anchor.x)
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = radiansToRotate
rotateAnimation.duration = 1.0 //the longer the duration, the "heavier" your knob
</code>```

That rotate animation will make the knob "follow" your finger, the desired effect. For completeness' sake, in a very basic form, atan2 is a math function that protects you from undefined arctan values. You'll have to worry about rotation direction, possibly, if your values fluctuate wildly, so you may consider using a key frame animation for this (I'll leave this to you).

Title: Rotate image with one finger

Body:
If you ignore gesture recognizers and override touches handlers on a view, you can use math to do this. With a little trig, take an arbitrary anchor point along an axis (say 9 o'clock on the knob), and your touches' locations on the plane with (0, 0) at the center of your knob. Say your anchor point is at (-3, 0) and your touch is at (-1, 1) for the sake of simplicity. Take the arctan of the change in y over the change in x, in this case arctan of 1/2, which is roughly 0.464 radians, or roughly 26.585 degrees. You would rotate your knob 26.6 degrees clockwise (in this case) from your anchor point to have your knob follow your touch. In Swift:

//Assume you have an anchor point "anchor" and a touch location "loc"
let radiansToRotate = atan2(loc.y - anchor.y, loc.x - anchor.x)
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = radiansToRotate
rotateAnimation.duration = 1.0 //the longer the duration, the "heavier" your knob

That rotate animation will make the knob "follow" your finger, the desired effect. For completeness' sake, in a very basic form, atan2 is a math function that protects you from undefined arctan values. You'll have to worry about rotation direction, possibly, if your values fluctuate wildly, so you may consider using a key frame animation for this (I'll leave this to you).


问:
Combine nav and jumbotron
I'm trying to combine the navigation and jumbotron divs so that both can encompass the whole page (100vh) and not go further. Essentially, I want both the navigation and jumbotron, but I want the elements to fill up the whole page without it being scrollable.

Currently, the navigation has a fixed height and so does the jumbotron. Take a look at it here (https://jsfiddle.net/orna9gz8/), although JSFiddle doesn't have a big enough screen to see that everything goes beyond the page. Some things I tried, but didn't work:

I tried removing the default Bootstrap margin between the navigation and jumbotron, but there the jumbotron still goes beyond the page.

I tried setting margin-top to -10% and this solved the issue temporarily (everything now fits on one page), but this doesn't seem to be working on smaller devices. This is probably not a mobile-friendly/responsive solution.

HTML:

```<code><header>
    <!-- Navigation -->
    <nav class="navbar navbar-default">
        <div class="container">
            <!-- Brand -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#"></a>
            </div>
            <div class="collapse navbar-collapse" id="navbar-collapse">
                <!-- Nav links -->
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="index.html">Home</a></li>
                    <li><a href="about.html">About</a></li>
                    <li><a href="teams.html">Teams</a></li>
                    <li><a href="involved.html">Get Involved</a></li>
                </ul>
            </div>
        </div>
    </nav>
</header>
<div class="jumbotron vertical-center">
    <div class="container text-center" id="landing">
        <h1>Website</h1><br>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu placerat eros, sed interdum lectus.</p>
        <button type="button" class="btn btn-default">Learn More</button>
    </div>
</div>
</code>```

CSS:

```<code>.navbar {
    margin-bottom: 0;
}

.jumbotron {
    background: none;
}

.navbar-default {
    background-color: transparent !important;
    border-color: transparent;
    background-image: none;
    box-shadow: none;
}
</code>```

答:
You could make the navbar fixed, remove the .jumbotron margin and make it min-height:100vh

https://jsfiddle.net/rf4Lj4y9/

```<code>.navbar-default {
    background-color: transparent !important;
    border-color: transparent;
    background-image: none;
    box-shadow: none;
}

.navbar {
    margin-bottom: 0;
}

.jumbotron {
    background: none;
    min-height: 100vh;
    margin-bottom: 0;
}
</code>```

PS - your fiddle has the CSS in the JavaScript editor.

Title: Combine nav and jumbotron

Body:
I'm trying to combine the navigation and jumbotron divs so that both can encompass the whole page (100vh) and not go further. Essentially, I want both the navigation and jumbotron, but I want the elements to fill up the whole page without it being scrollable.

Currently, the navigation has a fixed height and so does the jumbotron. Take a look at it here (https://jsfiddle.net/orna9gz8/), although JSFiddle doesn't have a big enough screen to see that everything goes beyond the page. Some things I tried, but didn't work:

I tried removing the default Bootstrap margin between the navigation and jumbotron, but there the jumbotron still goes beyond the page.

I tried setting margin-top to -10% and this solved the issue temporarily (everything now fits on one page), but this doesn't seem to be working on smaller devices. This is probably not a mobile-friendly/responsive solution.

HTML:

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false">
                    Toggle navigation

                </button>

Home

About

Teams

Get Involved

Website

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu placerat eros, sed interdum lectus.

        <button type="button" class="btn btn-default">Learn More</button>

CSS:

.navbar {
    margin-bottom: 0;
}

.jumbotron {
    background: none;
}

.navbar-default {
    background-color: transparent !important;
    border-color: transparent;
    background-image: none;
    box-shadow: none;
}

Body:
You could make the navbar fixed, remove the .jumbotron margin and make it min-height:100vh

https://jsfiddle.net/rf4Lj4y9/

.navbar-default {
    background-color: transparent !important;
    border-color: transparent;
    background-image: none;
    box-shadow: none;
}

.navbar {
    margin-bottom: 0;
}

.jumbotron {
    background: none;
    min-height: 100vh;
    margin-bottom: 0;
}

PS - your fiddle has the CSS in the JavaScript editor.


答:
It's actually normal: Quicksort (using the first or last element as pivot as you do) runs in time O(n * log n) in average, but O(n^2) when the data is already sorted. The number of recursive calls is usually O(log n), but O(n) when it's already sorted.

So you just have cases where it takes a lot of time, because of a lot of recursive calls, so you get a stack overflow... You'll get the same error if you try using it on a randomly ordered but much bigger (say 2^40000, I advise you not to do that ;) ) dataset.

If you still need to order your sorted data, you should use another choice for pivot. A simple solution is to take a random one, but it does not ensure that you will never get O(n) recursive calls. If you want to be sure of that, you should use more clever methods, such as those proposed by John Bollinger .

https://en.wikipedia.org/wiki/Quicksort

Title: “Exception in thread ”main“ java.lang.StackOverflowError” in Quick sort for sorted, reversed and Identical data of size greater than 10000


问:
Prevent Shutdown - C#, Powershell or CMD/Bat
I would like to ask how to prevent shutdown, when running a script or at least give a popup that will ask whenever or not you want to shutdown (like when you open a notepad and write a char, but doesn't save it and the click shutdown).

I have been creating scripts that runs installers silent, but some of them still seems to activate windows shutdown (this can happen if they are missing prerequisites).

Here is the code I use for the installation:

```<code># --- Install ---
$fileExtension = (Get-ChildItem -path $installationFilePath).Extension

if(".msi" -eq $fileExtension)
{
    [string[]]$Private:args = New-Object string[] 4
    $args[0] = "/qn"
    $args[1] = "TRANSFORM=1033.mst"
    $args[2] = "REBOOT=Suppress"
    $args[3] = "/l*v $errorLogPath"

    $process = Start-Process $installationFilePath -ArgumentList $args -PassThru
}

if(".exe" -eq $fileExtension)
{
    [string[]]$Private:args = New-Object string[] 2
    $args[0] = '/v"' + "/qn TRANSFORM=1033.mst REBOOT=Suppress /l*v $errorLogPath" + '"'
    $args[1] = "/s"

    $process = Start-Process $installationFilePath -ArgumentList $args -PassThru
}

$processActive = $process

while ($processActive -ne $null)
{
    Start-Sleep -Seconds 1
    Write-Host '.' -NoNewline
    $processActive = Get-Process -Id $processActive.Id -ErrorAction SilentlyContinue
}
</code>```

I know this should be possible, but I have yet to find out how.

答:
Here is an example of aborting shutdown after the install has finished:

```<code>Start-Process yourprogram.exe -Wait
shutdown /a
</code>```

You could even loop the abort a few times to make sure you hit it.

```<code>for($i=0;$i -lt 5;$i++)
{
    shutdown /a
    sleep 1
}
</code>```

Body:
I would like to ask how to prevent shutdown, when running a script or at least give a popup that will ask whenever or not you want to shutdown (like when you open a notepad and write a char, but doesn't save it and the click shutdown).

I have been creating scripts that runs installers silent, but some of them still seems to activate windows shutdown (this can happen if they are missing prerequisites).

Here is the code I use for the installation:

# --- Install ---
$fileExtension = (Get-ChildItem -path $installationFilePath).Extension

if(".msi" -eq $fileExtension)
{
    [string[]]$Private:args = New-Object string[] 4
    $args[0] = "/qn"
    $args[1] = "TRANSFORM=1033.mst"
    $args[2] = "REBOOT=Suppress"
    $args[3] = "/l*v $errorLogPath"

    $process = Start-Process $installationFilePath -ArgumentList $args -PassThru
}

if(".exe" -eq $fileExtension)
{
    [string[]]$Private:args = New-Object string[] 2
    $args[0] = '/v"' + "/qn TRANSFORM=1033.mst REBOOT=Suppress /l*v $errorLogPath" + '"'
    $args[1] = "/s"

    $process = Start-Process $installationFilePath -ArgumentList $args -PassThru
}

$processActive = $process

while ($processActive -ne $null)
{
    Start-Sleep -Seconds 1
    Write-Host '.' -NoNewline
    $processActive = Get-Process -Id $processActive.Id -ErrorAction SilentlyContinue
}

I know this should be possible, but I have yet to find out how.

Body:
Here is an example of aborting shutdown after the install has finished:

Start-Process yourprogram.exe -Wait
shutdown /a

You could even loop the abort a few times to make sure you hit it.

for($i=0;$i -lt 5;$i++)
{
    shutdown /a
    sleep 1
}


问:
Make a if else return in one line
I have a function which takes 4 parameters.

```<code>function fillTheText (selector, arrText, arrEl, j) {
  if (j >= 0) {
    return document.querySelector(selector + [j]).innerHTML = arrText[arrEl][j];
  } else {
    return document.querySelector(selector).innerHTML = arrText[arrEl];
  }
}
</code>```

The above function is invoked three times

```<code>function startQuiz (question) {
  fillTheText('#question', question[i], 'text');
  for (let j = 0; j < question[i].choices.length; j++) {
    fillTheText('#choice', question[i], 'choices', j)
  }
}
</code>```

I want to make changes so that fillTheText returns a single line but have no idea how can I make [j] optional. I tried conditional (ternary) operators but did not succeed.

答:
Use ternary operator

the line j>=0 means j's value is 0 or greater.

The Ternary operator

syntax : condition?true:false

If the condition is true, the part after ? will execute else the part after : will execute

```<code>function fillTheText (selector, arrText, arrEl, j) {
    return (typeof j==typeof 123 && j>=0) ? document.querySelector(selector + [j]).innerHTML = arrText[arrEl][j] : document.querySelector(selector).innerHTML = arrText[arrEl];
 }
</code>```

Title: Make a if else return in one line

Body:
I have a function which takes 4 parameters.

function fillTheText (selector, arrText, arrEl, j) {
  if (j >= 0) {
    return document.querySelector(selector + [j]).innerHTML = arrText[arrEl][j];
  } else {
    return document.querySelector(selector).innerHTML = arrText[arrEl];
  }
}

The above function is invoked three times

function startQuiz (question) {
  fillTheText('#question', question[i], 'text');
  for (let j = 0; j < question[i].choices.length; j++) {
    fillTheText('#choice', question[i], 'choices', j)
  }
}

I want to make changes so that fillTheText returns a single line but have no idea how can I make [j] optional. I tried conditional (ternary) operators but did not succeed.

Body:
Use ternary operator

the line j>=0 means j's value is 0 or greater.

The Ternary operator

syntax : condition?true:false

If the condition is true, the part after ? will execute else the part after : will execute

function fillTheText (selector, arrText, arrEl, j) {
    return (typeof j==typeof 123 && j>=0) ? document.querySelector(selector + [j]).innerHTML = arrText[arrEl][j] : document.querySelector(selector).innerHTML = arrText[arrEl];
 }


答:
You can create an instance of OnClickListener interface in CreateView class like this : </p>

```<code>   public class CreateView {

        View.OnClickListener onClickListener = null;

        public CreateView(View.OnClickListener  listener){
            this.onClickListener = listener ;
        }

        public View createLabelForMainWordsInOneLine(Context context, List<Model> words_List) {
            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);

            for (Model w : words_List) {

                TextView textView = new TextView(context);

                textView.setText(w.getW_text() + "");
                textView.setId(w.getW_id());
                textView.setTag(w.getW_id());

                textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));

                textView.setOnClickListener(onClickListener);

                linearLayout.addView(textView);
            }

            return linearLayout;
        }
    }
</code>```

<p>Then , You can instanciate CreateView like this : </p>

```<code> @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
  createView = new CreateView(this);
  listData=db.getAllData();
  createView.makeView(getActivity,listData);
}
</code>```

Body:
I have a fragment for displaying data with many dynamic textViews,when implements setOnClickListener for dynamic view get this error:

com.Package.activity.DashboardActivity cannot be cast to android.view.View$OnClickListener

Activity :DasgboardActivity : load fragment in frameLayout

  getSupportFragmentManager().beginTransaction().replace(R.id.container,new TestFragment()).commit();

Fragment

public class TestFragment extends Fragment implements View.OnClickListener{

  CreateView createView;
List<Model> listData=new ArrayList();
  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
  createView = new CreateView();
  listData=db.getAllData();
  createView.makeView(getActivity,listData);
}

    @Override
    public void onClick(View v) {}

}

CreateView class: for creating dynamic views:

  public View makeView(Context context, List<Model> words_List) {
        LinearLayout linearLayout = new LinearLayout(context);

        linearLayout.setOrientation(LinearLayout.HORIZONTAL);

            for (Model w : words_List) {

                TextView textView = new TextView(context);

                textView.setText(w.getW_text()+"");
                textView.setId(w.getW_id());
                textView.setTag(w.getW_id());

                    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));

       textView.setOnClickListener((View.OnClickListener) context);

                linearLayout.addView(textView);
            }

        return linearLayout;
    }

in this line i got error :
   textView.setOnClickListener((View.OnClickListener) context);

My code completely working on activity but in fragment i have error

How i must fix my bug?

Body:
You can create an instance of OnClickListener interface in CreateView class like this :

   public class CreateView {

        View.OnClickListener onClickListener = null;

        public CreateView(View.OnClickListener  listener){
            this.onClickListener = listener ;
        }

        public View createLabelForMainWordsInOneLine(Context context, List<Model> words_List) {
            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);

            for (Model w : words_List) {

                TextView textView = new TextView(context);

                textView.setText(w.getW_text() + "");
                textView.setId(w.getW_id());
                textView.setTag(w.getW_id());

                textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));

                textView.setOnClickListener(onClickListener);

                linearLayout.addView(textView);
            }

            return linearLayout;
        }
    }

Then , You can instanciate CreateView like this :

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
  createView = new CreateView(this);
  listData=db.getAllData();
  createView.makeView(getActivity,listData);
}


问:
Jira Custom Order By on Updated date/time
I have got the below ORDER BY JQL script added to my boards. For some reason though the issues are not re-ordering. Is there something that I am missing?</p>

```<code>ORDER BY updatedDate desc
</code>```

答: JIRA boards can be set to sort by "Rank", which will override and remove any other ranking; see Enabling Ranking and Ranking an Issue. If that's not set, ORDER BY works for me in JIRA Cloud.</p>

Body:
I have got the below ORDER BY JQL script added to my boards. For some reason though the issues are not re-ordering. Is there something that I am missing?

ORDER BY updatedDate desc


问:
Shell - how i can use a variable in sed command
I'm having a problem when use a variable in sed command.

My script:

```<code>#!/bin/sh

#Declaracao de variaveis
dominio=$1
host=$2

#Configuração do Varnish
varnish_config=$(cat <<-END
if (req.http.host ~ "$dominio") {
        set req.backend_hint = $host;
        return (pass);
}
END
)

sed '51i\'"${varnish_config}" $PWD/teste
</code>```

The error:

```<code>sed: -e expression #1, char 53: unknown option to `s'
</code>```

答:
Going the detour via a shell variable and sed (which is not suited for multiline substitutions) is tedious. The way to insert a file into another file at some position is to use a capable editor, like ex:

```<code>$ seq 5 > 5.txt
$ seq 10 > 10.txt
$ cat 10.txt
1
2
3
4
5
6
7
8
9
10
$ printf '6\nr 5.txt\nw\nq\n' | ex 10.txt
$ cat 10.txt
1
2
3
4
5
6
1
2
3
4
5
7
8
9
10
</code>```

The ex comands are:

```<code>6            set position to line 6
r 5.txt      read file 5.txt
w            write file
q            quit
</code>```

Body:
I'm having a problem when use a variable in sed command.

My script:

#!/bin/sh

#Declaracao de variaveis
dominio=$1
host=$2

#Configuração do Varnish
varnish_config=$(cat <<-END
if (req.http.host ~ "$dominio") {
        set req.backend_hint = $host;
        return (pass);
}
END
)

sed '51i\'"${varnish_config}" $PWD/teste

The error:

sed: -e expression #1, char 53: unknown option to `s'

Body:
Going the detour via a shell variable and sed (which is not suited for multiline substitutions) is tedious. The way to insert a file into another file at some position is to use a capable editor, like ex:

$ seq 5 > 5.txt
$ seq 10 > 10.txt
$ cat 10.txt
1
2
3
4
5
6
7
8
9
10
$ printf '6\nr 5.txt\nw\nq\n' | ex 10.txt
$ cat 10.txt
1
2
3
4
5
6
1
2
3
4
5
7
8
9
10

The ex comands are:

6            set position to line 6
r 5.txt      read file 5.txt
w            write file
q            quit


问:
Managing the localization of Java properties files
I have a Web application written in Java that is targeting several countries, all of which speak different languages (and more often than not, several languages -- that's Europe for you).

We have a bunch of .properties files that hold the localized strings, and our current procedure is to e-mail the language-specific files to our partners for updating before doing major updates.

However, this process is rather error-prone, as sometimes people forget to translate new strings and sometimes new strings don't get added to every language file, thus small mistakes get through very easily.

Does anyone know of any existing software that could help us clear this mess?

At a bare minimum, I'm thinking of something that would allow you to load a master file (for example, in English), a localized file and then would highlight the keys that were added to or removed from the master file.

答: For importing, managing, and potentially even ordering translations for languages you don't have in-house translators for, myGengo's String (http://mygengo.com/string/about) is a free hosted solution.  Supports importing of various language-files for a variety of platforms.  (Full disclosure - I'm a co-founder of myGengo)</p>


问:
android: no such instance field
I'm trying to get data thru AsyncTask with web service.
I have no idea why as I declared global variable 'arrayList1' and it has been initialized, but I'm getting error for the 'arrayList1' and it skipped doin the new AsyncTask.</p>

```<code>private Context mContext;
private ArrayList arrayList1;
private ArrayList<List> mData;
private ListView mListView;
private ListViewAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

mContext = getApplicationContext();
mListView = (ListView)findViewById(R.id.listView1);
mData = new ArrayList<List>();
mData = LoadListView();
}

public ArrayList<List> LoadListView(Void...params) {
    arrayList1 = new ArrayList();
    //here error occurred.
    new AsyncTask<Void, Void, ArrayList<List>>() {
        @Override
        protected ArrayList<List> doInBackground(Void...params) {
            arrayList1 = GetData();
            //GetData() is another function will return a arraylist from web service.
            return arrayList1;
        }

        @Override
        protected void onPostExecute(ArrayList<List> arrayList) {
            mAdapter = new ListViewAdapter(arrayList, mContext);
            mAdapter.notifyDataSetChanged();
            mListView.setAdapter(mAdapter);
        }
    }.execute((Void[]) params); //error occurred skipped directly to here.

    return arrayList1;
}
</code>```

答:
No need to send void parameter.</p>

```<code>.execute();
</code>```

Title: android: no such instance field

Body:
I'm trying to get data thru AsyncTask with web service.
I have no idea why as I declared global variable 'arrayList1' and it has been initialized, but I'm getting error for the 'arrayList1' and it skipped doin the new AsyncTask.

private Context mContext;
private ArrayList arrayList1;
private ArrayList<List> mData;
private ListView mListView;
private ListViewAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

mContext = getApplicationContext();
mListView = (ListView)findViewById(R.id.listView1);
mData = new ArrayList<List>();
mData = LoadListView();
}

public ArrayList<List> LoadListView(Void...params) {
    arrayList1 = new ArrayList();
    //here error occurred.
    new AsyncTask<Void, Void, ArrayList<List>>() {
        @Override
        protected ArrayList<List> doInBackground(Void...params) {
            arrayList1 = GetData();
            //GetData() is another function will return a arraylist from web service.
            return arrayList1;
        }

        @Override
        protected void onPostExecute(ArrayList<List> arrayList) {
            mAdapter = new ListViewAdapter(arrayList, mContext);
            mAdapter.notifyDataSetChanged();
            mListView.setAdapter(mAdapter);
        }
    }.execute((Void[]) params); //error occurred skipped directly to here.

    return arrayList1;
}

Body:
No need to send void parameter.

.execute();


问:
Applying .gitignore to committed files
I have committed loads of files that I now want to ignore. How can I tell git to now ignore these files from future commits?

EDIT: I do want to remove them from the repository too. They are files created after ever build or for user-specific tooling support.

答:
Be sure that your actual repo is the latest version and without ongoing changes

Edit .gitignore as you wish

git rm -r --cached . (remove all files)

git add . (re-add all files according to gitignore)

then commit as usual

Title: Applying .gitignore to committed files


问:
How to associate list with each enum item in c#
I have website to perform match action. I am writing code to restrict some of the action based on current match stage. For example, If first half is current stage then I should restrict direct end match without second half. For each stage, I have multiple restrict stages. Below is my stage enum.

```<code>public enum MatchStage
    {
        FirstHalfAssumedStartTime = 1,
        FirstHalfAssumedEndTime = 2,
        SecondHalfAssumedStartTime = 3,
        SecondHalfAssumedEndTime = 4,
        ExtraFirstHalfAssumedStartTime = 5,
        ExtraFirstHalfAssumedEndTime = 6,
        ExtraSecondHalfAssumedStartTime = 7,
        ExtraSecondHalfAssumedEndTime = 8,
        PauseStartTime = 9,
        PauseEndTime = 10,
        EndMatchTime = 11
    }
</code>```

I would like to make below method work. I want to call something like currentSiteCoreStage.RestrictedStages which returns List of restricted stages. How can I achieve this?

```<code>public static bool IsProposedStageValid(MatchStage currentSiteCoreStage, MatchStage proposedStage )
        {
            if (currentSiteCoreStage.RestrictedStages.Contains(proposedStage)) // I am hoping to make this work
                return false;
        }
</code>```

答:
One approach is to have a class that knows about your current stage and can generate RestrictedStages based on the current stage. Something like:

```<code>public enum Stage
{
    First, Second, Third
}

public class CoreStage
{
    public Stage CurrentStage { get; private set; }

    public IEnumerable<Stage> RestrictedStages { get; private set; }

    public CoreStage(Stage currentStage)
    {
        CurrentStage = currentStage;
        RestrictedStages = GenerateRestrictedStages();
    }

    private IEnumerable<Stage> GenerateRestrictedStages()
    {
        //apply your logic to determine Restricted stages based on current stage.
        return null;
    }
}
</code>```

Now in your IsProposedStageValid method would look sth like below:

```<code>public static bool IsProposedStageValid(Stage currentSiteCoreStage, Stage proposedStage)
    {
        var coreStage = new CoreStage(currentSiteCoreStage);
        if (coreStage.RestrictedStages.Contains(proposedStage))
        {
            //do whatever you want.
        }
        return false;
    }
</code>```

Body:
I have website to perform match action. I am writing code to restrict some of the action based on current match stage. For example, If first half is current stage then I should restrict direct end match without second half. For each stage, I have multiple restrict stages. Below is my stage enum.

public enum MatchStage
    {
        FirstHalfAssumedStartTime = 1,
        FirstHalfAssumedEndTime = 2,
        SecondHalfAssumedStartTime = 3,
        SecondHalfAssumedEndTime = 4,
        ExtraFirstHalfAssumedStartTime = 5,
        ExtraFirstHalfAssumedEndTime = 6,
        ExtraSecondHalfAssumedStartTime = 7,
        ExtraSecondHalfAssumedEndTime = 8,
        PauseStartTime = 9,
        PauseEndTime = 10,
        EndMatchTime = 11
    }

I would like to make below method work. I want to call something like currentSiteCoreStage.RestrictedStages which returns List of restricted stages. How can I achieve this?

public static bool IsProposedStageValid(MatchStage currentSiteCoreStage, MatchStage proposedStage )
        {
            if (currentSiteCoreStage.RestrictedStages.Contains(proposedStage)) // I am hoping to make this work
                return false;
        }

Body:
One approach is to have a class that knows about your current stage and can generate RestrictedStages based on the current stage. Something like:

public enum Stage
{
    First, Second, Third
}

public class CoreStage
{
    public Stage CurrentStage { get; private set; }

    public IEnumerable<Stage> RestrictedStages { get; private set; }

    public CoreStage(Stage currentStage)
    {
        CurrentStage = currentStage;
        RestrictedStages = GenerateRestrictedStages();
    }

    private IEnumerable<Stage> GenerateRestrictedStages()
    {
        //apply your logic to determine Restricted stages based on current stage.
        return null;
    }
}

Now in your IsProposedStageValid method would look sth like below:

public static bool IsProposedStageValid(Stage currentSiteCoreStage, Stage proposedStage)
    {
        var coreStage = new CoreStage(currentSiteCoreStage);
        if (coreStage.RestrictedStages.Contains(proposedStage))
        {
            //do whatever you want.
        }
        return false;
    }


问:
How can my Android app use the system's background image as its image?
I'm not sure about older versions of Android, but in Android 2.1 and 2.2, the system clock application doesn't have its own background. Instead, it uses the system's background. Does anyone know how to accomplish this?</p>

答: I think it is using a transparent image</p>

Body: I think it is using a transparent image