问:
Calculate Max Token Size for a specified Computer Object?
I am aware of CheckMaxTokenSize.ps1 (and unfortunately TokenSZ.exe is no longer available, and only works in 32 bit OS), how would I calculate max token size for a specific computer object?  I was able to modify a script to find the total number of recursive membership objects (there is a hard MS max of 1015 per computer), but need to take it further.

here is that simple powershell script

```<code>Import-Module ActiveDirectory
$forestName = ([System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()).Name
$ADsPath = [ADSI]"GC://$forestName"
$Search = New-Object System.DirectoryServices.DirectorySearcher($ADsPath)
$computer = Read-Host "Computer Name"
Write-Host ""; Write-Host "Processing....." -nonewline
if ($computer -eq "") {$computer = "<BLANK>"}
$Search.Filter = "(&(objectCategory=Computer)(name=$computer))"
$computercn = $Search.FindAll().Properties.distinguishedname
$csv = dsget computer $computercn -memberof -expand
Write-Host ($csv.Length -1) "items in List" -ForegroundColor Green
Write-Host "-----------------------------------"
</code>```

How would I return Token Size of the AD computer object without being on the device?

答:
I would suggest you start over and really review what information you need in order to break down this task into simple steps.

Before we begin, let's review the token size formula:

TokenSize = 1200 + 40d + 8s

This formula uses the following values:

  d:
  The number of domain local groups a user is a member of plus the
  number of universal groups outside the user's account domain that the
  user is a member of plus the number of groups represented in security
  ID (SID) history.

  s:
  The number of security global groups that a user
  is a member of plus the number of universal groups in a user's account
  domain that the user is a member of.

  1200: The estimated value for
  ticket overhead. This value can vary, depending on factors such as DNS
  domain name length, client name, and other factors.

Assuming that you have the computer name already (potentially from user input), what we need is:

Retrieve the computer account object, with its sid history

Find all its group memberships (recursively)

Split the groups into two buckets based on domain and scope

So, let's get to work.
Since you have the ActiveDirectory module handy, finding the computer is easy:

```<code># Define computer name
$ComputerName = "computer01"

# Find the computer in the directory
$Computer = Get-ADComputer -LDAPFilter "(&(name=$ComputerName))" -Properties PrimaryGroup,SidHistory
</code>```

Now, we could use the Get-ADPrincipalGroupMembership cmdlet to retrieve all the group memberships, but it doesn't support recursive searches, so I would use the IN_CHAIN query rule control in an LDAP filter with Get-ADGroup:

```<code># Locate a Global Catalog server
$GC = Get-ADDomainController -Discover -Service GlobalCatalog

# Search the global catalog using our recursive ldap filter
$Groups = Get-ADGroup -LDAPFilter "(&(member:1.2.840.113556.1.4.1941:=$($Computer.DistinguishedName)))" -Server "$($GC.HostName):3268"

# Don't forget the primary group
$Groups = @($Groups; Get-ADGroup -Identity $Computer.PrimaryGroup)
</code>```

Now we just need to split the groups into two sets, one containing Domain Local groups and foreign Universal Groups, and one containing Global groups and local Universal groups:

```<code># These are the "d" groups from the original formula
$LargeGroups = @($Groups |Where-Object {$_.GroupScope -eq 'DomainLocal' -or ($_.GroupScope -eq 'Universal' -and $_.DistinguishedName -notlike "*,DC=$($GC.Domain -split '\.' -join ',DC=')")})

# These are the "s" groups from the original formula
$SmallGroups = @($Groups |Where-Object {$_.GroupScope -eq 'Global' -or ($_.GroupScope -eq 'Universal' -and $_.DistinguishedName -like "*,DC=$($GC.Domain -split '\.' -join ',DC=')")})
</code>```

Now just calculate according to the formula:

```<code># Calculate TokenSize based on groups
$TokenSize = 1200 + (40 * $LargeGroups.Count) + (8 * $SmallGroups.Count)

# Factory in SIDHistory principals
if($Computer.SIDHistory){
    $TokenSize += 40 * $Computer.SIDHistory.Count
}
</code>```

And we're done :-)

Body:
I am aware of CheckMaxTokenSize.ps1 (and unfortunately TokenSZ.exe is no longer available, and only works in 32 bit OS), how would I calculate max token size for a specific computer object?  I was able to modify a script to find the total number of recursive membership objects (there is a hard MS max of 1015 per computer), but need to take it further.

here is that simple powershell script

Import-Module ActiveDirectory
$forestName = ([System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()).Name
$ADsPath = [ADSI]"GC://$forestName"
$Search = New-Object System.DirectoryServices.DirectorySearcher($ADsPath)
$computer = Read-Host "Computer Name"
Write-Host ""; Write-Host "Processing....." -nonewline
if ($computer -eq "") {$computer = "<BLANK>"}
$Search.Filter = "(&(objectCategory=Computer)(name=$computer))"
$computercn = $Search.FindAll().Properties.distinguishedname
$csv = dsget computer $computercn -memberof -expand
Write-Host ($csv.Length -1) "items in List" -ForegroundColor Green
Write-Host "-----------------------------------"

How would I return Token Size of the AD computer object without being on the device?

Body:
I would suggest you start over and really review what information you need in order to break down this task into simple steps.

Before we begin, let's review the token size formula:

TokenSize = 1200 + 40d + 8s

This formula uses the following values:

  d:
  The number of domain local groups a user is a member of plus the
  number of universal groups outside the user's account domain that the
  user is a member of plus the number of groups represented in security
  ID (SID) history.

  s:
  The number of security global groups that a user
  is a member of plus the number of universal groups in a user's account
  domain that the user is a member of.

  1200: The estimated value for
  ticket overhead. This value can vary, depending on factors such as DNS
  domain name length, client name, and other factors.

Assuming that you have the computer name already (potentially from user input), what we need is:

Retrieve the computer account object, with its sid history

Find all its group memberships (recursively)

Split the groups into two buckets based on domain and scope

So, let's get to work.
Since you have the ActiveDirectory module handy, finding the computer is easy:

# Define computer name
$ComputerName = "computer01"

# Find the computer in the directory
$Computer = Get-ADComputer -LDAPFilter "(&(name=$ComputerName))" -Properties PrimaryGroup,SidHistory

Now, we could use the Get-ADPrincipalGroupMembership cmdlet to retrieve all the group memberships, but it doesn't support recursive searches, so I would use the IN_CHAIN query rule control in an LDAP filter with Get-ADGroup:

# Locate a Global Catalog server
$GC = Get-ADDomainController -Discover -Service GlobalCatalog

# Search the global catalog using our recursive ldap filter
$Groups = Get-ADGroup -LDAPFilter "(&(member:1.2.840.113556.1.4.1941:=$($Computer.DistinguishedName)))" -Server "$($GC.HostName):3268"

# Don't forget the primary group
$Groups = @($Groups; Get-ADGroup -Identity $Computer.PrimaryGroup)

Now we just need to split the groups into two sets, one containing Domain Local groups and foreign Universal Groups, and one containing Global groups and local Universal groups:

# These are the "d" groups from the original formula
$LargeGroups = @($Groups |Where-Object {$_.GroupScope -eq 'DomainLocal' -or ($_.GroupScope -eq 'Universal' -and $_.DistinguishedName -notlike "*,DC=$($GC.Domain -split '\.' -join ',DC=')")})

# These are the "s" groups from the original formula
$SmallGroups = @($Groups |Where-Object {$_.GroupScope -eq 'Global' -or ($_.GroupScope -eq 'Universal' -and $_.DistinguishedName -like "*,DC=$($GC.Domain -split '\.' -join ',DC=')")})

Now just calculate according to the formula:

# Calculate TokenSize based on groups
$TokenSize = 1200 + (40 * $LargeGroups.Count) + (8 * $SmallGroups.Count)

# Factory in SIDHistory principals
if($Computer.SIDHistory){
    $TokenSize += 40 * $Computer.SIDHistory.Count
}

And we're done :-)


来源: stackexchange

问:
How to reset position of View to undo TranslateAnimation?
This method

```<code>animation.setFillAfter(false);
</code>```

doesn't reset view's position.

Also, the methods

```<code>getLocationInWindow(), getLocationOnScreen(), getMatrix()
</code>```

produce the same result before animation starts and after animation ends.
What properties of a View does TranslateAnimation change?

答:
How to reset position of View to undo TranslateAnimation?

You can reset the view state into it's default using the following.

```<code>imageView.clearAnimation()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This method

animation.setFillAfter(false);

doesn't reset view's position.

Also, the methods

getLocationInWindow(), getLocationOnScreen(), getMatrix()

produce the same result before animation starts and after animation ends.
What properties of a View does TranslateAnimation change?

Body:
How to reset position of View to undo TranslateAnimation?

You can reset the view state into it's default using the following.

imageView.clearAnimation()


问:
How to load and show images asynchronously
I'm new to WPF but I've done C# for quite some time now and I am currently developing a simple window (Windows Desktop) that should visualize all photos in a directory. The application should also know about EXIF data like ISO, aperture and so on, for which I use a DLL.

I have defined a Photo class:

```<code>public class Photo {

    public string FileName { get; set; }
    public int ISO { get; set; }
    ...
}
</code>```

that I want to store in a List<Photo> at runtime.

I've then declared a PhotoItem (XAML User Control) with an Image control and a TextBlock on it. For every Photo created there will be one PhotoItem created that holds the corresponding Photo as a property:

```<code>public partial class PhotoItem : UserControl {
    ...
    public Photo Photo { get; set; }
    ...
}
</code>```

From this Photo property the PhotoItem knows where to look for the image and what ISO etc. to display.

Now to my problem. Because it would take way too long to load the Image itself as well as the metadata already if the user selects the directory, I want to first add all the PhotoItems to the window (still empty) and then run the metadata lookup and Image thumbnail loading for each of them. Of course it would be best if these operations don't block the UI thread, hence I'm currently using one Task for gathering metadata and one for gathering the thumbnail.

How would I make the PhotoItems update if metadata for the image is now available? Basically how can you have one centralized location where all data is stored, to which Tasks can provide updates and from which the UI thread can build information. I know a bit about Bindings in XAML/WPF, but binding e.g. a TextBlock's text to the Photo.ISO variable would always display zero if the metadata was not gathered yet. In this case I would want to hide all the text detail on the PhotoItem.

On the other hand I've also thought about implementing something like a 'Refresh' function inside the PhotoItem, but that would reload the image and would take a long time (this was probably my favorite WinForms way to do it, haha).

Can anyone give me an idea of how to realize this?

Thanks in advance!

答:
Let's take a look at a basic example without a UserControl.

The first step is to create a view model to enable data binding. You would make the Photo class implement the INotifyPropertyChanged interface to update bindings when property values change.

The class below also declares an Image property that holds an ImageSource derived object, which is loaded asynchronously.

```<code>public class Photo : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this,
            new PropertyChangedEventArgs(propertyName));
    }

    public string FileName { get; set; }

    private string iso = string.Empty;
    public string ISO
    {
        get { return iso; }
        set
        {
            iso = value;
            NotifyPropertyChanged(nameof(ISO));
        }
    }

    private ImageSource image;
    public ImageSource Image
    {
        get { return image; }
        set
        {
            image = value;
            NotifyPropertyChanged(nameof(Image));
        }
    }

    public async Task Load()
    {
        Image = await Task.Run(() =>
        {
            using (var fileStream = new FileStream(
                FileName, FileMode.Open, FileAccess.Read))
            {
                return BitmapFrame.Create(
                    fileStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            }
        });

        ISO = "1600";
    }
}
</code>```

The second part of the view model is a class that holds a collection of Photo instances:

```<code>public class ViewModel
{
    public ObservableCollection<Photo> Photos { get; }
        = new ObservableCollection<Photo>();
}
</code>```

For the typical data binding scenario, you would assign an instance of this class to the DataContext of your Window, either in code or in XAML:

```<code><Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>
</code>```

The last part is the declaration of the ListBox with a DataTemplate that visualizes a Photo:

```<code><ListBox ItemsSource="{Binding Photos}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Image}" Width="100" Height="100"/>
                <StackPanel>
                    <TextBlock Text="{Binding ISO, StringFormat=ISO: {0}}"/>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

Now you could fill the Photos collection for instance in an asynchronous Loaded event handler of the MainWindow like this:

```<code>private async void Window_Loaded(object sender, RoutedEventArgs e)
{
    var vm = (ViewModel)DataContext;

    foreach (var file in Directory.EnumerateFiles(...))
    {
        vm.Photos.Add(new Photo { FileName = file });
    }

    foreach (var photo in vm.Photos)
    {
        await photo.Load();
    }
}
</code>```

Body:
I'm new to WPF but I've done C# for quite some time now and I am currently developing a simple window (Windows Desktop) that should visualize all photos in a directory. The application should also know about EXIF data like ISO, aperture and so on, for which I use a DLL.

I have defined a Photo class:

public class Photo {

    public string FileName { get; set; }
    public int ISO { get; set; }
    ...
}

that I want to store in a List<Photo> at runtime.

I've then declared a PhotoItem (XAML User Control) with an Image control and a TextBlock on it. For every Photo created there will be one PhotoItem created that holds the corresponding Photo as a property:

public partial class PhotoItem : UserControl {
    ...
    public Photo Photo { get; set; }
    ...
}

From this Photo property the PhotoItem knows where to look for the image and what ISO etc. to display.

Now to my problem. Because it would take way too long to load the Image itself as well as the metadata already if the user selects the directory, I want to first add all the PhotoItems to the window (still empty) and then run the metadata lookup and Image thumbnail loading for each of them. Of course it would be best if these operations don't block the UI thread, hence I'm currently using one Task for gathering metadata and one for gathering the thumbnail.

How would I make the PhotoItems update if metadata for the image is now available? Basically how can you have one centralized location where all data is stored, to which Tasks can provide updates and from which the UI thread can build information. I know a bit about Bindings in XAML/WPF, but binding e.g. a TextBlock's text to the Photo.ISO variable would always display zero if the metadata was not gathered yet. In this case I would want to hide all the text detail on the PhotoItem.

On the other hand I've also thought about implementing something like a 'Refresh' function inside the PhotoItem, but that would reload the image and would take a long time (this was probably my favorite WinForms way to do it, haha).

Can anyone give me an idea of how to realize this?

Thanks in advance!

Body:
Let's take a look at a basic example without a UserControl.

The first step is to create a view model to enable data binding. You would make the Photo class implement the INotifyPropertyChanged interface to update bindings when property values change.

The class below also declares an Image property that holds an ImageSource derived object, which is loaded asynchronously.

public class Photo : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this,
            new PropertyChangedEventArgs(propertyName));
    }

    public string FileName { get; set; }

    private string iso = string.Empty;
    public string ISO
    {
        get { return iso; }
        set
        {
            iso = value;
            NotifyPropertyChanged(nameof(ISO));
        }
    }

    private ImageSource image;
    public ImageSource Image
    {
        get { return image; }
        set
        {
            image = value;
            NotifyPropertyChanged(nameof(Image));
        }
    }

    public async Task Load()
    {
        Image = await Task.Run(() =>
        {
            using (var fileStream = new FileStream(
                FileName, FileMode.Open, FileAccess.Read))
            {
                return BitmapFrame.Create(
                    fileStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            }
        });

        ISO = "1600";
    }
}

The second part of the view model is a class that holds a collection of Photo instances:

public class ViewModel
{
    public ObservableCollection<Photo> Photos { get; }
        = new ObservableCollection<Photo>();
}

For the typical data binding scenario, you would assign an instance of this class to the DataContext of your Window, either in code or in XAML:

<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>

The last part is the declaration of the ListBox with a DataTemplate that visualizes a Photo:

<ListBox ItemsSource="{Binding Photos}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Image}" Width="100" Height="100"/>
                <StackPanel>
                    <TextBlock Text="{Binding ISO, StringFormat=ISO: {0}}"/>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Now you could fill the Photos collection for instance in an asynchronous Loaded event handler of the MainWindow like this:

private async void Window_Loaded(object sender, RoutedEventArgs e)
{
    var vm = (ViewModel)DataContext;

    foreach (var file in Directory.EnumerateFiles(...))
    {
        vm.Photos.Add(new Photo { FileName = file });
    }

    foreach (var photo in vm.Photos)
    {
        await photo.Load();
    }
}


问:
How to split text per paragraph based on length?
Hi I am using RedCloth, Rails 3.

Currently I splitling a long text based based on string "-BREAK-".
How do I split text based on character length without splitting in the middle of a sentence.

E.g.,

```<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas at purus eu nisl consequat mattis. Morbi pretium eros eget erat ornare elementum.

Vivamus in dui sit amet tellus bibendum volutpat. Sed lorem sem, porttitor at mattis quis, volutpat sed quam. Vestibulum eu justo nec dui ullamcorper molestie. Sed eleifend malesuada mattis. Curabitur eleifend elit vitae justo feugiat iaculis. Etiam sed lectus eu quam suscipit fermentum id a sem.

Phasellus sed odio eu urna gravida venenatis venenatis non justo. Praesent tincidunt velit adipiscing ligula pretium commodo. Cras blandit, nibh ac sagittis egestas, enim odio rutrum metus, vel hendrerit felis urna cursus odio. Maecenas elementum erat et arcu vulputate eu fermentum orci semper. Proin luctus purus sit amet nibh blandit cursus.
</code>```

That will be comprise one page. It's about 794 characters.

答:
I don't think there's any built in logic for this, so you should just look for "." with a nice regex also specifying that it has to be straight after a word (not whitespace), followed by a space and a capital letter.

Edit: that should give you an array of occurrences from which you can pick the one closest to the character limit.

ContentLicense: CC BY-SA 2.5

Body:
Hi I am using RedCloth, Rails 3.

Currently I splitling a long text based based on string "-BREAK-".
How do I split text based on character length without splitting in the middle of a sentence.

E.g.,

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas at purus eu nisl consequat mattis. Morbi pretium eros eget erat ornare elementum.

Vivamus in dui sit amet tellus bibendum volutpat. Sed lorem sem, porttitor at mattis quis, volutpat sed quam. Vestibulum eu justo nec dui ullamcorper molestie. Sed eleifend malesuada mattis. Curabitur eleifend elit vitae justo feugiat iaculis. Etiam sed lectus eu quam suscipit fermentum id a sem.

Phasellus sed odio eu urna gravida venenatis venenatis non justo. Praesent tincidunt velit adipiscing ligula pretium commodo. Cras blandit, nibh ac sagittis egestas, enim odio rutrum metus, vel hendrerit felis urna cursus odio. Maecenas elementum erat et arcu vulputate eu fermentum orci semper. Proin luctus purus sit amet nibh blandit cursus.

That will be comprise one page. It's about 794 characters.


问:
Codenameone Connect to Google Drive
This may be a dumb questions, but I haven't found an answer after lots of searching. I need to do two things, I need to allow my app to login to google, then save a file the users google drive.

I've found some steps on how to connect to google drive, but either its outdated or I don't have the correct libraries because it fails to compile:  https://www.codenameone.com/google-login.html

Any help would be greatly appreciated.

答:
Check the Integrating Google Sign-In into your web app. There's even an video guide explaining the concept.

There's a quick Save to Drive which enables your web site to allow users to save files to their Drive account from an arbitrary URL via their browser. If that's not sufficient enough, you can always check the Uploading Files where you can upload file data by creating or updating a File resource.

Title: Codenameone Connect to Google Drive


问:
What is wrong with this makefile and how to fix it?
I have got 4 files: pass1.c , pass2.c, main.c and header1.h.

Each of these files, include the file header.h

I wrote the following makefile:

```<code>assembler: pass1.o pass2.o main.o
    gcc pass1.o pass2.o -o assembler

pass1.o:     pass1.c
    gcc -c -ansi -Wall -pedantic pass1.c -o pass1.o

pass2.o:     pass2.c
    gcc -c -ansi -Wall -pedantic pass2.c -o pass2.o

main.o:    main.c
    gcc -c -ansi -Wall -pedantic main.c -o main.o
</code>```

When I did make, I got the following error:

```<code>/usr/lib/gcc/x86_64-linux-gnu/6/../../../x86_64-linux-gnu/Scrt1.o: In     function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
makefile:2: recipe for target 'assembler' failed
make: *** [assembler] Error 1
</code>```

Note that I didn't write a function called 'start'.

What is the problem here and how can I fix it?

答:
```<code>gcc pass1.o pass2.o -o assembler
</code>```

should be

```<code>gcc main.o pass1.o pass2.o -o assembler
</code>```

Rename main.c to assembler.c and your entire makefile can be condensed to

```<code>CFLAGS  := -ansi -Wall -pedantic
objects := assembler.o pass1.o pass2.o
assembler: $(objects)
$(objects): header.h
</code>```

assuming that cc on your system is a symlink to gcc.

Body:
I have got 4 files: pass1.c , pass2.c, main.c and header1.h.

Each of these files, include the file header.h

I wrote the following makefile:

assembler: pass1.o pass2.o main.o
    gcc pass1.o pass2.o -o assembler

pass1.o:     pass1.c
    gcc -c -ansi -Wall -pedantic pass1.c -o pass1.o

pass2.o:     pass2.c
    gcc -c -ansi -Wall -pedantic pass2.c -o pass2.o

main.o:    main.c
    gcc -c -ansi -Wall -pedantic main.c -o main.o

When I did make, I got the following error:

/usr/lib/gcc/x86_64-linux-gnu/6/../../../x86_64-linux-gnu/Scrt1.o: In     function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
makefile:2: recipe for target 'assembler' failed
make: *** [assembler] Error 1

Note that I didn't write a function called 'start'.

What is the problem here and how can I fix it?

Body:
gcc pass1.o pass2.o -o assembler

should be

gcc main.o pass1.o pass2.o -o assembler

Rename main.c to assembler.c and your entire makefile can be condensed to

CFLAGS  := -ansi -Wall -pedantic
objects := assembler.o pass1.o pass2.o
assembler: $(objects)
$(objects): header.h

assuming that cc on your system is a symlink to gcc.


问:
com.sun.jersey.api.view.Viewable cannot be resolved, it is indirectly referenced form required.class
I upgraded jersey version from 1.13 to 2.25.1. I've changed all the packages form com.sun.jersey to org.glassfish.jersey. App started working as expected but one of the classes is throwing com.sun.jersey.view.Viewable cannot be resolved, it is indirectly referenced from required.class error. Viewable class was present in older version of jersey and I am no longer referencing it but why I am getting error then? I've cleaned the project and updated the project via Maven but same error.  Is there anything missing?

Thanks.

答:
This may not be an ideal solution but the only way to get rid of this issue for me was to add the lower version of the jersey jars. As I said, this is not the right approach because now I got two version of Jersey jars in my classpath.

We have to carefully build the project and test all the services just to make sure they are working as expected because jersey get confuse what to pick up if there are two version of jars.

In these kind of cases, usually the third party api breaks because of the fact that you don't provide the implementation of certain interfaces or abstract classes which are not in the latest version but the compiler refers to the lower version and look for an implementation. Therefore I don't like this approach at all.


问:
vim-powerline shows a weird red color in the left side
I don't know what is wrong with my vim-powerline. A unexpected red bar on the left side of powerline in Macvim, whereas it doesn't appear when I use vim in terminal.

Here is the screenshot:

Both Macvim and vim share the same vimrc file. How can I solve this issue in macvim?

答:
Lokaltog/vim-powerline is outdated and no longer maintained.

https://github.com/powerline/powerline/issues/1745

I solved my version of this problem by removing vim-powerline, installing powerline via pip install --user powerline-status and adding the following to my .vimrc file:

```<code>set rtp+=$HOME/.local/lib/python3.5/site-packages/powerline/bindings/vim/
set laststatus=2
</code>```

Body:
Lokaltog/vim-powerline is outdated and no longer maintained.

https://github.com/powerline/powerline/issues/1745

I solved my version of this problem by removing vim-powerline, installing powerline via pip install --user powerline-status and adding the following to my .vimrc file:

set rtp+=$HOME/.local/lib/python3.5/site-packages/powerline/bindings/vim/
set laststatus=2


问:
how to save arraylist<object> after app is closed
how to save arraylist after the app is closed.
This is my global class

```<code>public class GlobalClass extends Application {

ArrayList<Trip> allTrips = new ArrayList<>();

public ArrayList<String> allTripsString() {
    ArrayList<String> allTripsString = new ArrayList<String>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getName());
    }
    return allTripsString;
    }
}
</code>```

This is my trip class

```<code>public class Trip {

/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;

private String name;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public double budget = 0;

/** An item in the expanses list */
static class Item {
    final String name;
    final double cost;
    final String Category;
    public Item(String name, double cost, String Category) {
        this.name = name;
        this.cost = cost;
        this.Category = Category;
    }
    @Override public String toString() {
        return this.name + " (" + this.cost + "$)";
    }
    public String getName(){
        return name;
    }
    public String getCategory(){
        return Category;
    }
    public double getCost(){
        return cost;
    }
}

public Trip(String name) {
    this.name = name;
    this.expanses = new HashMap<String,List<Item>>();
    for (String cat: ExpensesCategory) { // init the categories with empty lists
        this.expanses.put(cat, new ArrayList<Item>());
    }
}

public String getName(){
    return name;
}

/** Register a new expanse to the trip. */
public void add(String item, double cost, String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        throw new IllegalArgumentException("Category '"+category+"' does not exist.");
    list.add( new Item(item, cost, category) );
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing the category elements, or null if the category does not exists
 */
public List<Item> getItems(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return null;
    return new ArrayList<Item>(list);
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing all the elements
 */
public List<Item> getItems() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    return list;
}

public ArrayList<String> getItemsString() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getName());
    }
    return listString;
}

public ArrayList<Double> getItemsCost(){
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Item item : list){
        listDouble.add(item.getCost());
    }
    return listDouble;
}

public ArrayList<String> getItemsCategory() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getCategory());
    }
    return listString;
}

/** Get the total cost, given a category. */
public double getCost(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return -1;
    double cost = 0;
    for (Item item: list)
        cost += item.cost;
    return cost;
}

/** Get the total cost. */
public double getCost() {
    double cost = 0;
    for (List<Item> l: this.expanses.values())
        for (Item item: l)
            cost += item.cost;
    cost *= 1000;
    cost = (int)(cost);
    cost /= 1000;
    return cost;
    }
}
</code>```

I want to save the array list and when I close and open the app the array list (alltrips) is saved. How to do this?

I want to use shared preferences but I don't know how to do this because it is not a string it array list with Trip. Can anyone help me to save the arraylist in shared preferences?

答: I dont think there is lifecyle method which will be called in production mode . the user just moves out of the activity page . you should probably do whatever you want in onPause method .

Body:
how to save arraylist after the app is closed.
This is my global class

public class GlobalClass extends Application {

ArrayList<Trip> allTrips = new ArrayList<>();

public ArrayList<String> allTripsString() {
    ArrayList<String> allTripsString = new ArrayList<String>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getName());
    }
    return allTripsString;
    }
}

This is my trip class

public class Trip {

/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;

private String name;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public double budget = 0;

/** An item in the expanses list */
static class Item {
    final String name;
    final double cost;
    final String Category;
    public Item(String name, double cost, String Category) {
        this.name = name;
        this.cost = cost;
        this.Category = Category;
    }
    @Override public String toString() {
        return this.name + " (" + this.cost + "$)";
    }
    public String getName(){
        return name;
    }
    public String getCategory(){
        return Category;
    }
    public double getCost(){
        return cost;
    }
}

public Trip(String name) {
    this.name = name;
    this.expanses = new HashMap<String,List<Item>>();
    for (String cat: ExpensesCategory) { // init the categories with empty lists
        this.expanses.put(cat, new ArrayList<Item>());
    }
}

public String getName(){
    return name;
}

/** Register a new expanse to the trip. */
public void add(String item, double cost, String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        throw new IllegalArgumentException("Category '"+category+"' does not exist.");
    list.add( new Item(item, cost, category) );
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing the category elements, or null if the category does not exists
 */
public List<Item> getItems(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return null;
    return new ArrayList<Item>(list);
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing all the elements
 */
public List<Item> getItems() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    return list;
}

public ArrayList<String> getItemsString() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getName());
    }
    return listString;
}

public ArrayList<Double> getItemsCost(){
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Item item : list){
        listDouble.add(item.getCost());
    }
    return listDouble;
}

public ArrayList<String> getItemsCategory() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getCategory());
    }
    return listString;
}

/** Get the total cost, given a category. */
public double getCost(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return -1;
    double cost = 0;
    for (Item item: list)
        cost += item.cost;
    return cost;
}

/** Get the total cost. */
public double getCost() {
    double cost = 0;
    for (List<Item> l: this.expanses.values())
        for (Item item: l)
            cost += item.cost;
    cost *= 1000;
    cost = (int)(cost);
    cost /= 1000;
    return cost;
    }
}

I want to save the array list and when I close and open the app the array list (alltrips) is saved. How to do this?

I want to use shared preferences but I don't know how to do this because it is not a string it array list with Trip. Can anyone help me to save the arraylist in shared preferences?


问:
How do I use an equivalent to C++ reference parameters in Java?
Suppose I have this in C++:

```<code>void test(int &i, int &j)
{
    ++i;
    ++j;
}
</code>```

The values are altered inside the function and then used outside. How could I write a code that does the same in Java? I imagine I could return a class that encapsulates both values, but that seems really cumbersome.

答:
A better question: why are you creating methods with such side-effects?

Generally, this is a strong indication that you should extract the data into a separate class, with public accessors that describe why the operation is taking place.

OwnerDisplayName: al bundy

Body:
Suppose I have this in C++:

void test(int &i, int &j)
{
    ++i;
    ++j;
}

The values are altered inside the function and then used outside. How could I write a code that does the same in Java? I imagine I could return a class that encapsulates both values, but that seems really cumbersome.

OwnerDisplayName: kdgregory


问:
Connecting to DashDB on Bluemix using Bluemix PHP App
I'm failing to connect to the dashdb on bluemix using php. I tried troubleshooting and I think that my error is within the function $conn = db2_connect( $conn_string, "", "" );

What values do I need to put in the empty inverted commas? Please help.

```<code><!DOCTYPE html>
<html>
<head>
<title>PHP Starter Application</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="style.css" />
</head>
<body>
<?php
    $usern = $_POST['un'];
    $passw = $_POST['pw'];
    if( getenv( "VCAP_SERVICES" ) )
    {
        # Get database details from the VCAP_SERVICES environment variable
        #
        # *This can only work if you have used the Bluemix dashboard to
        # create a connection from your dashDB service to your PHP App.
        #
        $details  = json_decode( getenv( "VCAP_SERVICES" ), true );
        $dsn      = $details [ "dashDB" ][0][ "credentials" ][ "dsn" ];
        //$ssl_dsn  = $details [ "dashDB" ][0][ "credentials" ][ "ssldsn" ];

        # Build the connection string
        #
        $driver = "DRIVER={IBM DB2 ODBC DRIVER};";
        $conn_string = $driver . $dsn;     # Non-SSL
        //$conn_string = $driver . $ssl_dsn; # SSL
            echo $conn_string;
        $conn = db2_connect( $conn_string, "", "" );
        //echo "<meta http-equiv='refresh' content='0; url=index.php'>";
        if( $conn )
        {
            echo "<p>Connection succeeded.</p>";
            db2_close( $conn );
        }
        else
        {
            echo "<p>Connection failed.</p>";
        }
    }
    else
    {
        //echo "<meta http-equiv='refresh' content='0; url=index.php'>";
        //echo "<p> <a href='index.php'>Missing DB Connection.</p>";
    }
?>
</body>
</html>
</code>```

答:
Try replacing double quotes with single quotes

$conn = db2_connect($conn_string, ' ', ' ' );

Body:
I'm failing to connect to the dashdb on bluemix using php. I tried troubleshooting and I think that my error is within the function $conn = db2_connect( $conn_string, "", "" );

What values do I need to put in the empty inverted commas? Please help.

<!DOCTYPE html>

<title>PHP Starter Application</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="style.css" />

<?php
    $usern = $_POST['un'];
    $passw = $_POST['pw'];
    if( getenv( "VCAP_SERVICES" ) )
    {
        # Get database details from the VCAP_SERVICES environment variable
        #
        # *This can only work if you have used the Bluemix dashboard to
        # create a connection from your dashDB service to your PHP App.
        #
        $details  = json_decode( getenv( "VCAP_SERVICES" ), true );
        $dsn      = $details [ "dashDB" ][0][ "credentials" ][ "dsn" ];
        //$ssl_dsn  = $details [ "dashDB" ][0][ "credentials" ][ "ssldsn" ];

        # Build the connection string
        #
        $driver = "DRIVER={IBM DB2 ODBC DRIVER};";
        $conn_string = $driver . $dsn;     # Non-SSL
        //$conn_string = $driver . $ssl_dsn; # SSL
            echo $conn_string;
        $conn = db2_connect( $conn_string, "", "" );
        //echo "<meta http-equiv='refresh' content='0; url=index.php'>";
        if( $conn )
        {
            echo "
Connection succeeded.
";
            db2_close( $conn );
        }
        else
        {
            echo "
Connection failed.
";
        }
    }
    else
    {
        //echo "<meta http-equiv='refresh' content='0; url=index.php'>";
        //echo "
 Missing DB Connection.
";
    }
?>


问:
Using the docs but completely confused... mongoose Model#save
I am trying to return specific status codes such as, 409 Conflict. I have used the Model#save docs

Edit: I am not trying to solve the error, it is deliberate.

According to the docs, there is three parameters on the callback: err, product, and numAffected.

EDIT: I wrote this code wrong and I edited. Either way, I got an excellent answer from Ryan.

```<code>  app.post('/skill', (req, res) => {
    const skill = new Skill({some_duplicate_object});
    skill.save((err, product, numAffected) => {
        console.log("Error: ", err);

    });
</code>```

NOT my console.log, in the Mocha test cli, I get an error:

```<code>(node:19760) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 5): ValidationError: Path `name` is required.
</code>```

By playing around and shear luck, I did this: This is NOT in the mongoose docs and is my main reason for writing this post.

```<code>  app.post('/skill', (req, res) => {
    const skill = new Skill({});
    skill.save()
      .then((err, product, numAffected) => {
        console.log("Nothing displayed here");
    }, (err) => {
      console.log(err.errors);
    });
</code>```

Even though this is not in the docs, it shows the error I want. As someone that is REALLY trying to use official docs more, I find it so hard to understand what is really going on. Why does this work and if it is in the docs, where would this info be?

```<code>{ name:
   { MongooseError: Path `name` is required.
       at ValidatorError (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/error/validator.js:24:11)
       at validate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:706:13)
       at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:752:11
       at Array.forEach (native)
       at SchemaString.SchemaType.doValidate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:712:19)
       at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/document.js:1408:9
       at _combinedTickCallback (internal/process/next_tick.js:73:7)
       at process._tickCallback (internal/process/next_tick.js:104:9)
     message: 'Path `name` is required.',
     name: 'ValidatorError',
     properties:
      { type: 'required',
        message: 'Path `{PATH}` is required.',
        validator: [Function],
        path: 'name',
        value: undefined },
     kind: 'required',
     path: 'name',
     value: undefined,
     reason: undefined } }
</code>```

Extra info:

```<code>  "devDependencies": {
    "chai": "^3.5.0",
    "mocha": "^2.4.5",
    "request": "^2.81.0",
    "supertest": "^3.0.0"
  },
  "dependencies": {
    "body-parser": "^1.17.1",
    "express": "^4.15.2",
    "mongoose": "^4.9.2"
  }
</code>```

答:
Your problem is two fold, and both of the errors you are getting are telling you exactly what is wrong. The source of your troubles is lack of understanding (not trying to pick on you). This is kind of the same as if you were a beginner at electronics and I told your that a tube is biased improperly and you said "I don't understand" - well, you need to learn about tubes then because I just described to you the exact problem with your circuit.

1. Promise error - UnhandledPromiseRejectionWarning: Unhandled promise rejection.... This cannot be more descript. Promises are either 1) resolved or 2) rejected. If you fail to "handle" the rejected case, you will get an error. Handling a rejected promise can happen one of two ways:

```<code>// pass a 2nd function to `.then()`:
somePromise.then(function (result) {
  // promise was "resolved" successfully
}, function (err) {
  // Promise was "rejected"
});

// use `.catch()` - this is preferred in my opinion:
somePromise.then(function (result) {
  // promise was "resolved" successfully
}).catch(function (err) {
  // Promise was "rejected"
});
</code>```

Using either of the above scenarios means you "handled" the promise rejection correctly.

2. Database validation - Path 'name' is required.. This literally means that you have a required path called "name" which is required (meaning, it must have a value). So looking at your code it's pretty obvious:

```<code>const skill = new Skill({});
skill.save() //-> results in error
</code>```

This is fixed by adding all required data before saving:

```<code>const skill = new Skill({ name: "Jason" });
skill.save() //-> yay, no error
</code>```

Body:
I am trying to return specific status codes such as, 409 Conflict. I have used the Model#save docs

Edit: I am not trying to solve the error, it is deliberate.

According to the docs, there is three parameters on the callback: err, product, and numAffected.

EDIT: I wrote this code wrong and I edited. Either way, I got an excellent answer from Ryan.

  app.post('/skill', (req, res) => {
    const skill = new Skill({some_duplicate_object});
    skill.save((err, product, numAffected) => {
        console.log("Error: ", err);

    });

NOT my console.log, in the Mocha test cli, I get an error:

(node:19760) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 5): ValidationError: Path `name` is required.

By playing around and shear luck, I did this: This is NOT in the mongoose docs and is my main reason for writing this post.

  app.post('/skill', (req, res) => {
    const skill = new Skill({});
    skill.save()
      .then((err, product, numAffected) => {
        console.log("Nothing displayed here");
    }, (err) => {
      console.log(err.errors);
    });

Even though this is not in the docs, it shows the error I want. As someone that is REALLY trying to use official docs more, I find it so hard to understand what is really going on. Why does this work and if it is in the docs, where would this info be?

{ name:
   { MongooseError: Path `name` is required.
       at ValidatorError (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/error/validator.js:24:11)
       at validate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:706:13)
       at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:752:11
       at Array.forEach (native)
       at SchemaString.SchemaType.doValidate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:712:19)
       at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/document.js:1408:9
       at _combinedTickCallback (internal/process/next_tick.js:73:7)
       at process._tickCallback (internal/process/next_tick.js:104:9)
     message: 'Path `name` is required.',
     name: 'ValidatorError',
     properties:
      { type: 'required',
        message: 'Path `{PATH}` is required.',
        validator: [Function],
        path: 'name',
        value: undefined },
     kind: 'required',
     path: 'name',
     value: undefined,
     reason: undefined } }

Extra info:

  "devDependencies": {
    "chai": "^3.5.0",
    "mocha": "^2.4.5",
    "request": "^2.81.0",
    "supertest": "^3.0.0"
  },
  "dependencies": {
    "body-parser": "^1.17.1",
    "express": "^4.15.2",
    "mongoose": "^4.9.2"
  }

Body:
Your problem is two fold, and both of the errors you are getting are telling you exactly what is wrong. The source of your troubles is lack of understanding (not trying to pick on you). This is kind of the same as if you were a beginner at electronics and I told your that a tube is biased improperly and you said "I don't understand" - well, you need to learn about tubes then because I just described to you the exact problem with your circuit.

1. Promise error - UnhandledPromiseRejectionWarning: Unhandled promise rejection.... This cannot be more descript. Promises are either 1) resolved or 2) rejected. If you fail to "handle" the rejected case, you will get an error. Handling a rejected promise can happen one of two ways:

// pass a 2nd function to `.then()`:
somePromise.then(function (result) {
  // promise was "resolved" successfully
}, function (err) {
  // Promise was "rejected"
});

// use `.catch()` - this is preferred in my opinion:
somePromise.then(function (result) {
  // promise was "resolved" successfully
}).catch(function (err) {
  // Promise was "rejected"
});

Using either of the above scenarios means you "handled" the promise rejection correctly.

2. Database validation - Path 'name' is required.. This literally means that you have a required path called "name" which is required (meaning, it must have a value). So looking at your code it's pretty obvious:

const skill = new Skill({});
skill.save() //-> results in error

This is fixed by adding all required data before saving:

const skill = new Skill({ name: "Jason" });
skill.save() //-> yay, no error


问:
How to add background image on iphone Navigation bar?
I want to add an image background to my navigation bar.

Is it right?

```<code>//set custom background image
UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"NavigationBackground.png"]];
[self.navigationBar insertSubview:backgroundView atIndex:0];
[backgroundView release];
</code>```

答:
Try this code in your AppDelegate Class to show image at navigation bar. It will help you alot. </p>

```<code>[[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"headerImg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)] forBarMetrics:UIBarMetricsDefault];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to add an image background to my navigation bar.

Is it right?

//set custom background image
UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"NavigationBackground.png"]];
[self.navigationBar insertSubview:backgroundView atIndex:0];
[backgroundView release];

Body:
Try this code in your AppDelegate Class to show image at navigation bar. It will help you alot.

[[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"headerImg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)] forBarMetrics:UIBarMetricsDefault];


问:
MaterializeCSS Icons not working
I'm having an issue with getting the icons to display while using MaterializeCSS. I'm using the bare bones "Getting Started" from the documentation but for whatever reason icons refuse to show up. Below is the code I'm using

```<code><!DOCTYPE html>
<html>

<head>
   <!--Import Google Icon Font-->
   <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
   <!--Import materialize.css-->
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css">
   <!--Let browser know website is optimized for mobile-->
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body>
    <nav>
        <ul class="hide-on-med-and-down">
            <li><a href="#!">First Sidebar Link</a></li>
            <li><a href="#!">Second Sidebar Link</a></li>
        </ul>
        <ul id="slide-out" class="side-nav fixed">
            <li class="bold"><a href="#!" class="waves-effect waves-teal">First Sidebar Link</a></li>
            <li class="bold"><a href="#!" class="">Second Sidebar Link</a></li>
            <li class="no-padding">
                <ul class="collapsible collapsible-accordion">
                    <li>
                        <a class="collapsible-header waves-effect waves-teal">Dropdown<i class="mdi-navigation-arrow-drop-down"></i></a>
                        <div class="collapsible-body">
                            <ul>
                                <li><a href="#!">First</a></li>
                                <li><a href="#!">Second</a></li>
                                <li><a href="#!">Third</a></li>
                                <li><a href="#!">Fourth</a></li>
                            </ul>
                         </div>
                    </li>
                </ul>
            </li>
        </ul>
        <a href="#" data-activates="slide-out" class="button-collapse"><i class="mdi-navigation-menu"></i></a>
  </nav>
  <!--Import jQuery before materialize.js-->
  <script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script>
  <script>
    $('.button-collapse').sideNav({
        menuWidth: 300, // Default is 240
        closeOnClick: true // Closes side-nav on <a> clicks, useful for Angular/Meteor
    });
    $('.collapsible').collapsible();
  </script>
</body>

</html>
</code>```

All this code is trying to do is display a navbar, it was pulled directly from the documentation.

The hamburger menu doesn't appear when the browser is resized

The dropdown arrow doesn't appear beside the dropdown menu item.

I feel like it's something stupid that I'm missing but I've been looking at it for 2 hours and my brain is melted. Any help would be appreciated.

答: CHANGE HTTP TO HTTPS in linking font library. It worked for me.

Title: MaterializeCSS Icons not working

Body:
I'm having an issue with getting the icons to display while using MaterializeCSS. I'm using the bare bones "Getting Started" from the documentation but for whatever reason icons refuse to show up. Below is the code I'm using

<!DOCTYPE html>

   <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css">

   <meta name="viewport" content="width=device-width, initial-scale=1.0" />

First Sidebar Link

Second Sidebar Link

First Sidebar Link

Second Sidebar Link

                        Dropdown

First

Second

Third

Fourth

All this code is trying to do is display a navbar, it was pulled directly from the documentation.

The hamburger menu doesn't appear when the browser is resized

The dropdown arrow doesn't appear beside the dropdown menu item.

I feel like it's something stupid that I'm missing but I've been looking at it for 2 hours and my brain is melted. Any help would be appreciated.


问:
php strstr not detecting substring in a arabic string
Can anyone please tell me ,How to make string matching function work with Arabic keywords?
                 The Following keywords are detected as Unmatched in php. Though these are matching in normal browser searching.

```<code>    if (strstr('الهيئة العامة للقوى العاملة', 'قوى العامله') != false) {
       echo'in';
          } else {
          echo'out';
           }die;
</code>```

Result comes as 'out'.

Thanks

答: The result for the match you are doing should be out, so it's working just fine for you. There is no match for the search you are doing since the last letter in the word العاملة is different between the two strings.

Body:
Can anyone please tell me ,How to make string matching function work with Arabic keywords?
                 The Following keywords are detected as Unmatched in php. Though these are matching in normal browser searching.

    if (strstr('الهيئة العامة للقوى العاملة', 'قوى العامله') != false) {
       echo'in';
          } else {
          echo'out';
           }die;

Result comes as 'out'.

Thanks


问:
Error in generating javadoc using UMLGraph, getting error in processing "dot file"
I am trying to generate class diagram from the source code through UmlGraph.
I have built and created the umlgraph.jar but while i am using it in my project it is giving me the below error ::

```<code>[javadoc] java.io.IOException: Cannot run program "dot": CreateProcess error=2, The system cannot find the file specified
  [javadoc]     at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
  [javadoc]     at java.lang.Runtime.exec(Runtime.java:593)
  [javadoc]     at java.lang.Runtime.exec(Runtime.java:466)
  [javadoc]     at org.umlgraph.doclet.UmlGraphDoc.runGraphviz(UmlGraphDoc.java:131)
  [javadoc]     at org.umlgraph.doclet.UmlGraphDoc.generatePackageDiagrams(UmlGraphDoc.java:95)
  [javadoc]     at org.umlgraph.doclet.UmlGraphDoc.start(UmlGraphDoc.java:63)
  [javadoc]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  [javadoc]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  [javadoc]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  [javadoc]     at java.lang.reflect.Method.invoke(Method.java:597)
  [javadoc]     at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:269)
  [javadoc]     at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:143)
  [javadoc]     at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:340)
  [javadoc]     at com.sun.tools.javadoc.Start.begin(Start.java:128)
  [javadoc]     at com.sun.tools.javadoc.Main.execute(Main.java:41)
  [javadoc]     at com.sun.tools.javadoc.Main.main(Main.java:31)
</code>```

I have downloaded the GraphViz and set the path for the graphviz.
please help me guys i am new to this one.

The javadoc target in ant file ::

```<code>    <fileset dir="${srcroot.dir}" >
            <filename name="**/*.java"/>
        </fileset>

               <doclet name="org.umlgraph.doclet.UmlGraphDoc"
                  path="${umlLib.dir}/UmlGraph.jar">
                    <param name="-attributes"  />
                    <param name="-operations"  />
                    <param name="-qualify" />
                    <param name="-types"  />
                    <param name="-visibility"  />
                </doclet>
              </javadoc>
      <apply executable="dot" dest="${reports.dir}" parallel="false">
        <arg value="-Tpng"/>
        <arg value="-o"/>
         <targetfile/>
         <srcfile/>
         <fileset dir="${reports.dir}" includes="*.dot"/>
         <mapper type="glob" from="*.dot" to="*.png"/>
      </apply>
</target>
</code>```

答:
I had the common issues about the mysql-connector and the dot executable file. It's not necessary to restart the machine if you pass the correct value to -gv, believe me. I've installed the Graphviz and found the mysql-connector performing a sorted search of *.jar files.

The following lines are how I executed the statement.

```<code>java
-jar schemaSpy.jar
-t mysql
-o library
-host localhost
-db dummyDB
-u user
-p user
-dp C:\Oracle\Middleware\Oracle_Home\oracle_common\modules\mysql-connector-java-commercial-5.1.22\mysql-connector-java-commercial-5.1.22-bin.jar
-gv "C:\Program Files (x86)\Graphviz2.38"
</code>```

Body:
I am trying to generate class diagram from the source code through UmlGraph.
I have built and created the umlgraph.jar but while i am using it in my project it is giving me the below error ::

[javadoc] java.io.IOException: Cannot run program "dot": CreateProcess error=2, The system cannot find the file specified
  [javadoc]     at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
  [javadoc]     at java.lang.Runtime.exec(Runtime.java:593)
  [javadoc]     at java.lang.Runtime.exec(Runtime.java:466)
  [javadoc]     at org.umlgraph.doclet.UmlGraphDoc.runGraphviz(UmlGraphDoc.java:131)
  [javadoc]     at org.umlgraph.doclet.UmlGraphDoc.generatePackageDiagrams(UmlGraphDoc.java:95)
  [javadoc]     at org.umlgraph.doclet.UmlGraphDoc.start(UmlGraphDoc.java:63)
  [javadoc]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  [javadoc]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  [javadoc]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  [javadoc]     at java.lang.reflect.Method.invoke(Method.java:597)
  [javadoc]     at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:269)
  [javadoc]     at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:143)
  [javadoc]     at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:340)
  [javadoc]     at com.sun.tools.javadoc.Start.begin(Start.java:128)
  [javadoc]     at com.sun.tools.javadoc.Main.execute(Main.java:41)
  [javadoc]     at com.sun.tools.javadoc.Main.main(Main.java:31)

I have downloaded the GraphViz and set the path for the graphviz.
please help me guys i am new to this one.

The javadoc target in ant file ::

    <fileset dir="${srcroot.dir}" >
            <filename name="**/*.java"/>
        </fileset>

               <doclet name="org.umlgraph.doclet.UmlGraphDoc"
                  path="${umlLib.dir}/UmlGraph.jar">
                    <param name="-attributes"  />
                    <param name="-operations"  />
                    <param name="-qualify" />
                    <param name="-types"  />
                    <param name="-visibility"  />
                </doclet>
              </javadoc>
      <apply executable="dot" dest="${reports.dir}" parallel="false">
        <arg value="-Tpng"/>
        <arg value="-o"/>
         <targetfile/>
         <srcfile/>
         <fileset dir="${reports.dir}" includes="*.dot"/>
         <mapper type="glob" from="*.dot" to="*.png"/>
      </apply>
</target>

Body:
I had the common issues about the mysql-connector and the dot executable file. It's not necessary to restart the machine if you pass the correct value to -gv, believe me. I've installed the Graphviz and found the mysql-connector performing a sorted search of *.jar files.

The following lines are how I executed the statement.

java
-jar schemaSpy.jar
-t mysql
-o library
-host localhost
-db dummyDB
-u user
-p user
-dp C:\Oracle\Middleware\Oracle_Home\oracle_common\modules\mysql-connector-java-commercial-5.1.22\mysql-connector-java-commercial-5.1.22-bin.jar
-gv "C:\Program Files (x86)\Graphviz2.38"


问:
How to make a 3D flip from a fragment to an activity?
I am trying to make the flip transition to another activity on clicking a button in a fragment. I have set up onClickListener for the required button which calls another function, something like:

```<code>Button btn = (Button) getActivity().findViewById(R.id.button1);

btn.setOnClickListener(View.onClicListener(

@Override

public void onClick(View v)

{

fnTransition(v);

});
</code>```

I tried opening an activity from a fragment using 2D animation defined in an xml file.

eg:

```<code>private void fnTransition(View v)

{

//some condition check

startActivity(getActivity(), intendedActivity.class));

getActivity.overridePendingTransition (R.layout.new_activity_animation,

R.layout.leaving_activity_animation);

getActivity().finish();

}
</code>```

Can a similar approach be employed to perform 3D animation transitions?

答:
Replacing the 2 mentioned xml files with these nearly does the trick, although this is probably not the best way to do it.

xml 1 -> from_middle.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <scale
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromXScale="1.0" android:toXScale="1.0"
        android:pivotX="50%"
        android:fromYScale="0.0" android:toYScale="1.0"
        android:pivotY="50%"
        android:duration="500" />

</set>
</code>```

xml 2-> to_middle

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <scale
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromXScale="1.0" android:toXScale="1.0"
        android:pivotX="50%"
        android:fromYScale="1.0" android:toYScale="0.0"
        android:pivotY="50%"
        android:duration="500" />

</set>
</code>```

While this nearly does the trick, a better way would be preferable as it can be made out that this is not a proper flip.

Body:
I am trying to make the flip transition to another activity on clicking a button in a fragment. I have set up onClickListener for the required button which calls another function, something like:

Button btn = (Button) getActivity().findViewById(R.id.button1);

btn.setOnClickListener(View.onClicListener(

@Override

public void onClick(View v)

{

fnTransition(v);

});

I tried opening an activity from a fragment using 2D animation defined in an xml file.

eg:

private void fnTransition(View v)

{

//some condition check

startActivity(getActivity(), intendedActivity.class));

getActivity.overridePendingTransition (R.layout.new_activity_animation,

R.layout.leaving_activity_animation);

getActivity().finish();

}

Can a similar approach be employed to perform 3D animation transitions?

Body:
Replacing the 2 mentioned xml files with these nearly does the trick, although this is probably not the best way to do it.

xml 1 -> from_middle.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <scale
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromXScale="1.0" android:toXScale="1.0"
        android:pivotX="50%"
        android:fromYScale="0.0" android:toYScale="1.0"
        android:pivotY="50%"
        android:duration="500" />

</set>

xml 2-> to_middle

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <scale
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromXScale="1.0" android:toXScale="1.0"
        android:pivotX="50%"
        android:fromYScale="1.0" android:toYScale="0.0"
        android:pivotY="50%"
        android:duration="500" />

</set>

While this nearly does the trick, a better way would be preferable as it can be made out that this is not a proper flip.


问:
How Cashew and Mobile Roadie work (online iPhone app creation tools)?
I discovered today two websites that allow people creating native iPhone apps directly in the browser!
theses are the links:

http://mobileroadie.com/

http://cashew.madebykawet.com/

I tried the second one and it's really amazing:
You create your app online then customize it by adding RSS feeds, tabs, videos, etc ... and to test, all you have to do is to download the "cashew" app, enter your nickname and password and then preview your app. Amazing.

How did they do it? How the whole system works? It's pretty weird because you create an app that will not be submitted to the appstore and will be published live!!

Thank you,

Regards.

答:
interesting things :-) Without any deeper insights to both applications, I think the main point is that there is an app connecting to a protected section of a CMS. Content, navigation, media, etc. is stored in this CMS database and is loaded after starting the app either from server, if you are online, or from cache. All GUI elements like views, tabs, ... are created programmatically using the information from CMS.

There seem to be only few differences between both approaches.

1) mobileroadies.com

You create your own app once which will then be submitted by the mobileroadie guys. The FAQ writes "Once you’re ready, let us know through the CMS. We check your App and assuming there are no issues submit it to Apple and/or Google on your behalf". That means you cannot test your app on the device until you have got the approval.

If once accepted by Apple, content will be updated by connecting to their web site when the user starts the app. Videos, music and so on are provided as streams and seem to be available only within the app, as long as they are not hosted on youtube or any other location outside mobileroadie's CMS database.

2) cashew

There is one app for all developers to test their stuff on the device, because on start you have to provide your user name and password. This is different from the simulator only approach from mobileroadies (and fancy :-). The technical process of creating an app seems pretty similar i.e. CMS with database and dynamic creation of views. If you are satisfied with your app, again they will do the approval process for you: "For 590€ (then 29€/month) we add it on the App Store"

There are some small differences in pricing model. If you are planning to work with such a system, you should take a closer look at testing and versioning capabilities. For me as developer it's extremely important to test new content before going live.

Hope that helps and: My thoughts are pure guessing I am not connected at all to one of the companies.

Regards

Kay


问:
In T-SQL, why is like operator not working for a variable but works for a literal?
Here is the script:

First script:

```<code>declare @a char(10) = 'AA%'
declare @b char(10) = 'AA001'

if @b LIKE @a
     print 'Equals'
else
begin
     print 'Not equals'
end
</code>```

It prints:

```<code>Not Equals
</code>```

I was expecting it to print Equals. But the script below which does not use @a in the condition:

Second script:

```<code>declare @a char(10) = 'AA%'
declare @b char(10) = 'AA001'

if @b LIKE 'AA%'
    print 'Equals'
else
begin
    print 'Not equals'
end
</code>```

prints

```<code>Equals
</code>```

So why does the first script consider them not-equal but the second script consider them equal?

答:
The answer is actually simple but this is a big gotcha: It is because of the char type.

If we were to print out the 2 variables:

```<code>print @a
print @b
</code>```

The output would be (dots mean empty space):

```<code>AA%.......
AA001.....
</code>```

So the first query does a like on the two variables and the trailing blanks make it not equal because according to MSDN, and logically speaking, the trailing blanks (empty spaces) are significant:

If a comparison in a query is to return all rows with the string LIKE 'abc' (abc without a space), all rows that start with abc and have zero or more trailing blanks are returned. +
  A string comparison using a pattern that contains char and varchar data may not pass a LIKE comparison because of how the data is stored.

Second Query

The second query has the literal AA% whose implicit type is varchar and since AA001 (whose type is char) will be like AA%, it prints Equals. To reaffirm that the type of the literal is varchar, I used this query:

```<code>SELECT SQL_VARIANT_PROPERTY('AA%', 'BaseType')
</code>```

which returns varchar.

Some More Info

Here is some more examples from MSDN for further clarity:

The following example passes a local char variable to a stored procedure and then uses pattern matching to find all of the employees whose last names start with a specified set of characters.

```<code>-- Uses AdventureWorks

CREATE PROCEDURE FindEmployee @EmpLName char(20)
AS
SELECT @EmpLName = RTRIM(@EmpLName) + '%';
SELECT p.FirstName, p.LastName, a.City
FROM Person.Person p JOIN Person.Address a ON p.BusinessEntityID = a.AddressID
WHERE p.LastName LIKE @EmpLName;
GO
EXEC FindEmployee @EmpLName = 'Barb';
GO
</code>```

In the FindEmployee procedure, no rows are returned because the char variable (@EmpLName) contains trailing blanks whenever the name contains fewer than 20 characters. Because the LastName column is varchar, there are no trailing blanks. This procedure fails because the trailing blanks are significant.
However, the following example succeeds because trailing blanks are not added to a varchar variable.

-- Uses AdventureWorks

```<code>CREATE PROCEDURE FindEmployee @EmpLName varchar(20)
AS
SELECT @EmpLName = RTRIM(@EmpLName) + '%';
SELECT p.FirstName, p.LastName, a.City
FROM Person.Person p JOIN Person.Address a ON p.BusinessEntityID = a.AddressID
WHERE p.LastName LIKE @EmpLName;
GO
EXEC FindEmployee @EmpLName = 'Barb';
</code>```

Here is the result set:

```<code>FirstName LastName City
---------- -------------------- ---------------
Angela Barbariol Snohomish
David Barber Snohomish
(2 row(s) affected)
</code>```

Body:
Here is the script:

First script:

declare @a char(10) = 'AA%'
declare @b char(10) = 'AA001'

if @b LIKE @a
     print 'Equals'
else
begin
     print 'Not equals'
end

It prints:

Not Equals

I was expecting it to print Equals. But the script below which does not use @a in the condition:

Second script:

declare @a char(10) = 'AA%'
declare @b char(10) = 'AA001'

if @b LIKE 'AA%'
    print 'Equals'
else
begin
    print 'Not equals'
end

prints

Equals

So why does the first script consider them not-equal but the second script consider them equal?

Body:
The answer is actually simple but this is a big gotcha: It is because of the char type.

If we were to print out the 2 variables:

print @a
print @b

The output would be (dots mean empty space):

AA%.......
AA001.....

So the first query does a like on the two variables and the trailing blanks make it not equal because according to MSDN, and logically speaking, the trailing blanks (empty spaces) are significant:

If a comparison in a query is to return all rows with the string LIKE 'abc' (abc without a space), all rows that start with abc and have zero or more trailing blanks are returned. +
  A string comparison using a pattern that contains char and varchar data may not pass a LIKE comparison because of how the data is stored.

Second Query

The second query has the literal AA% whose implicit type is varchar and since AA001 (whose type is char) will be like AA%, it prints Equals. To reaffirm that the type of the literal is varchar, I used this query:

SELECT SQL_VARIANT_PROPERTY('AA%', 'BaseType')

which returns varchar.

Some More Info

Here is some more examples from MSDN for further clarity:

The following example passes a local char variable to a stored procedure and then uses pattern matching to find all of the employees whose last names start with a specified set of characters.

-- Uses AdventureWorks

CREATE PROCEDURE FindEmployee @EmpLName char(20)
AS
SELECT @EmpLName = RTRIM(@EmpLName) + '%';
SELECT p.FirstName, p.LastName, a.City
FROM Person.Person p JOIN Person.Address a ON p.BusinessEntityID = a.AddressID
WHERE p.LastName LIKE @EmpLName;
GO
EXEC FindEmployee @EmpLName = 'Barb';
GO

In the FindEmployee procedure, no rows are returned because the char variable (@EmpLName) contains trailing blanks whenever the name contains fewer than 20 characters. Because the LastName column is varchar, there are no trailing blanks. This procedure fails because the trailing blanks are significant.
However, the following example succeeds because trailing blanks are not added to a varchar variable.

-- Uses AdventureWorks

CREATE PROCEDURE FindEmployee @EmpLName varchar(20)
AS
SELECT @EmpLName = RTRIM(@EmpLName) + '%';
SELECT p.FirstName, p.LastName, a.City
FROM Person.Person p JOIN Person.Address a ON p.BusinessEntityID = a.AddressID
WHERE p.LastName LIKE @EmpLName;
GO
EXEC FindEmployee @EmpLName = 'Barb';

Here is the result set:

FirstName LastName City
---------- -------------------- ---------------
Angela Barbariol Snohomish
David Barber Snohomish
(2 row(s) affected)


问:
Subscribing to Observable in service from component
I have searched for quite some time to understand how to subscribe to an array whose values are constantly updated.

I need to understand how to setup my Angular 2+ service observable correctly and subscribe to it in my component correctly. Please assume all other parts of the code works correctly.

```<code>@Injectable()
export class AutocompleteService {

    searchTerm: string;
    results = [];
    observe$ = Observable.from(this.results);

    searchTest(term){
        this.searchTerm = term.toLowerCase();

        if(this.searchTerm.length > 2){
            this.recruiters.forEach(function(el){
                if(el.name.toLowerCase().indexOf(term) != -1) {
                    this.results.push(el);
                }
            });

        }
    }

    getCurrentResults():Observable<Object> {
        return this.observe$;
    }
</code>```

Everything in the service works as expected. If I log the term I get user input from my component. Or the results array after matching search results are pushed onto it.

```<code>@Component({
    selector: 'autocomplete',
    templateUrl: './autocomplete.component.html',
    providers: [AutocompleteService]
})
export class AutocompleteComponent implements OnInit{
    constructor(private autocompleteService: AutocompleteService){}

    value: string = '';
    searchControl = new FormControl();

    // fired when input happens
    getResults(event){
        this.autocompleteService.searchTest(event.target.value);

        this.autocompleteService.getCurrentResults().subscribe(
            value => console.log(value)
        );

    }
</code>```

I have setup the observable pattern to the best of my ability but I'm not getting anything out of the .subscribe in getResults

答:
I addition to what jonrsharpe and echonax said:

you can use Subject :

```<code>@Injectable()
export class AutocompleteService {

    searchTerm: string;
    results = [];
    subject = new Subject();

    searchTest(term){
        this.searchTerm = term.toLowerCase();

        if(this.searchTerm.length > 2){
            this.recruiters.forEach(el =>{
                if(el.name.toLowerCase().indexOf(term) != -1) {
                    this.subject.next(el);
                }
            });

        }
    }

    getCurrentResults():Subject<Object> {
        return this.subject;
    }
</code>```

}

and subscribe to getCurrentResults() the same way you did.

you demo : plunker

Body:
I have searched for quite some time to understand how to subscribe to an array whose values are constantly updated.

I need to understand how to setup my Angular 2+ service observable correctly and subscribe to it in my component correctly. Please assume all other parts of the code works correctly.

@Injectable()
export class AutocompleteService {

    searchTerm: string;
    results = [];
    observe$ = Observable.from(this.results);

    searchTest(term){
        this.searchTerm = term.toLowerCase();

        if(this.searchTerm.length > 2){
            this.recruiters.forEach(function(el){
                if(el.name.toLowerCase().indexOf(term) != -1) {
                    this.results.push(el);
                }
            });

        }
    }

    getCurrentResults():Observable<Object> {
        return this.observe$;
    }

Everything in the service works as expected. If I log the term I get user input from my component. Or the results array after matching search results are pushed onto it.

@Component({
    selector: 'autocomplete',
    templateUrl: './autocomplete.component.html',
    providers: [AutocompleteService]
})
export class AutocompleteComponent implements OnInit{
    constructor(private autocompleteService: AutocompleteService){}

    value: string = '';
    searchControl = new FormControl();

    // fired when input happens
    getResults(event){
        this.autocompleteService.searchTest(event.target.value);

        this.autocompleteService.getCurrentResults().subscribe(
            value => console.log(value)
        );

    }

I have setup the observable pattern to the best of my ability but I'm not getting anything out of the .subscribe in getResults

Body:
I addition to what jonrsharpe and echonax said:

you can use Subject :

@Injectable()
export class AutocompleteService {

    searchTerm: string;
    results = [];
    subject = new Subject();

    searchTest(term){
        this.searchTerm = term.toLowerCase();

        if(this.searchTerm.length > 2){
            this.recruiters.forEach(el =>{
                if(el.name.toLowerCase().indexOf(term) != -1) {
                    this.subject.next(el);
                }
            });

        }
    }

    getCurrentResults():Subject<Object> {
        return this.subject;
    }

}

and subscribe to getCurrentResults() the same way you did.

you demo : plunker


问:
Cannot update params when use warden.authenticate in devise
I have upgrade my rails from 3.2.8 to rails 4, also devise is upgrade from 2.1.2 to 3.5.6 and warden from 1.2.3 to 1.2.6.
I found an issue that I don't know what it should belongs to devise or warden.

Before I call

```<code>resource = warden.authenticate(:scope => resource_name, :recall =>"#{controller_path}#new")
</code>```

I update params value like below:

```<code>params[:admin] = Hash.new
params[:admin][:email] = params[:email]
params[:admin][:password] = params[:password]
</code>```

But when I print params in proxy.rb, the function def authenticate(*args)
the params is still the original, there are no any admin in it.

The issue is not happened when I use the old system.

Here is my part of code and logs:
controllers.rb

```<code>params[:admin] = Hash.new
params[:admin][:email] = params[:email]
params[:admin][:password] = params[:password]
params[:password] = '11111111111111'
# authenticate with warden
p '===================================='
p params
p warden
resource = warden.authenticate(:scope => resource_name, :recall => "#{controller_path}#new")
p params
p '===================================='
</code>```

proxy.rb

```<code>def authenticate(*args)
  p 'sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss'
  p params
  params[:password] = '111111111'
  p params
  p 'sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss'
  user, _opts = _perform_authentication(*args)
  user
end
</code>```

logs:

```<code>"===================================="
{"email"=>"syter@xxxx.com", "password"=>"11111111111111", "controller"=>"admin_sessions", "action"=>"create", "version"=>"v1", "format"=>"json", "admin"=>{"email"=>"syter@xxxx.com", "password"=>"xxxxxxxx"}}
Warden::Proxy:70145506030260 @config={:default_scope=>:admin, :scope_defaults=>{}, :default_strategies=>{:admin=>[:rememberable, :database_authenticatable]}, :intercept_401=>false, :failure_app=>#Devise::Delegator:0x007f980f873e18}
"sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
{"email"=>"syter@xxxx.com", "password"=>"xxxxxxxx", "controller"=>"admin_sessions", "action"=>"create", "version"=>"v1", "format"=>"json"}
{"email"=>"syter@xxxx.com", "password"=>"111111111", "controller"=>"admin_sessions", "action"=>"create", "version"=>"v1", "format"=>"json"}
"sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
"sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
{"email"=>"syter@xxxx.com", "password"=>"111111111", "controller"=>"admin_sessions", "action"=>"create", "version"=>"v1", "format"=>"json"}
"sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
{"email"=>"syter@xxxx.com", "password"=>"11111111111111", "controller"=>"admin_sessions", "action"=>"create", "version"=>"v1", "format"=>"json", "admin"=>{"email"=>"syter@xxxx.com", "password"=>"xxxxxxxx"}}
"===================================="
</code>```

It seems there are two params, one is in controller, one is in warden.

Is there any configuration or any other things I missed?

Hope ur answers,
Thank u.

答:
Didn't see this question when I asked and answered something similar here https://stackoverflow.com/a/40512141/208769

Annoyingly, it seems that the params you see in the controller is a clone of the params that rack maintains, rather than a reference to it. And because warden intercepts the request in a middleware layer, it maintains its link to the request params, and knows nothing about the controller's clone.

In short, if you want to modify params and have warden see your modifications, you need to modify request.params

Body:
I have upgrade my rails from 3.2.8 to rails 4, also devise is upgrade from 2.1.2 to 3.5.6 and warden from 1.2.3 to 1.2.6.
I found an issue that I don't know what it should belongs to devise or warden.

Before I call

resource = warden.authenticate(:scope => resource_name, :recall =>"#{controller_path}#new")

I update params value like below:

params[:admin] = Hash.new
params[:admin][:email] = params[:email]
params[:admin][:password] = params[:password]

But when I print params in proxy.rb, the function def authenticate(*args)
the params is still the original, there are no any admin in it.

The issue is not happened when I use the old system.

Here is my part of code and logs:
controllers.rb

params[:admin] = Hash.new
params[:admin][:email] = params[:email]
params[:admin][:password] = params[:password]
params[:password] = '11111111111111'
# authenticate with warden
p '===================================='
p params
p warden
resource = warden.authenticate(:scope => resource_name, :recall => "#{controller_path}#new")
p params
p '===================================='

proxy.rb

def authenticate(*args)
  p 'sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss'
  p params
  params[:password] = '111111111'
  p params
  p 'sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss'
  user, _opts = _perform_authentication(*args)
  user
end

logs:

"===================================="
{"email"=>"syter@xxxx.com", "password"=>"11111111111111", "controller"=>"admin_sessions", "action"=>"create", "version"=>"v1", "format"=>"json", "admin"=>{"email"=>"syter@xxxx.com", "password"=>"xxxxxxxx"}}
Warden::Proxy:70145506030260 @config={:default_scope=>:admin, :scope_defaults=>{}, :default_strategies=>{:admin=>[:rememberable, :database_authenticatable]}, :intercept_401=>false, :failure_app=>#Devise::Delegator:0x007f980f873e18}
"sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
{"email"=>"syter@xxxx.com", "password"=>"xxxxxxxx", "controller"=>"admin_sessions", "action"=>"create", "version"=>"v1", "format"=>"json"}
{"email"=>"syter@xxxx.com", "password"=>"111111111", "controller"=>"admin_sessions", "action"=>"create", "version"=>"v1", "format"=>"json"}
"sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
"sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
{"email"=>"syter@xxxx.com", "password"=>"111111111", "controller"=>"admin_sessions", "action"=>"create", "version"=>"v1", "format"=>"json"}
"sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
{"email"=>"syter@xxxx.com", "password"=>"11111111111111", "controller"=>"admin_sessions", "action"=>"create", "version"=>"v1", "format"=>"json", "admin"=>{"email"=>"syter@xxxx.com", "password"=>"xxxxxxxx"}}
"===================================="

It seems there are two params, one is in controller, one is in warden.

Is there any configuration or any other things I missed?

Hope ur answers,
Thank u.