问:
how use Optional with cascaded objects not created with Optional
Context: I have chained objects generated by wsdl2java so none of them contains java.util.Optional. There is an already created method that call the soap web services, receives the xml and unmarshalling it in cascaded objects.

Desire: I want to use Optional in order to avoid null tests.

I have already posted my dificults to accomplish it (how to use optional and filter along to retrieve an object from chained/cascaded objects generated by wsdl2java) but, after 3 days searching and reading I really got stuck and I realised that I have some gap in my knowlodge so I decided take a step back and try a more simple solution before moving forward.

I am wondering if I am really trying something that is possible to do: use Optional with a cascaded objects that weren't created with Optional pattern in mind. Most of the example I found in internet either use cascaded objects coded with "private Optional myObj" or they are limited to use Optional.of to an object, not to a tree of objects like generated by wsdl2java.

Here is what I tried so far to figure out if it is possible and I got stuck as well: I followed http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html and I tryed to apply same idea imagining the objects were coded originally with Java 7 (no private Optional myObj at all).

Firstly, exactly as showed by Oracle article (from parent to child dependency):

USB

```<code>public class USB {

    String version;
    public USB() {

    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
}
</code>```

OptionalSoundcard

```<code>public class OptionalSoundcard {

    private Optional<USB> usb;

    public OptionalSoundcard() {
        // TODO Auto-generated constructor stub
    }

    public Optional<USB> getUsb() {
        return usb;
    }

    public void setUsb(Optional<USB> usb) {
        this.usb = usb;
    }

}
</code>```

OptionalComputer

```<code>public class OptionalComputer {

    private Optional<OptionalSoundcard> soundcard;

    public OptionalComputer() {
    }

    public Optional<OptionalSoundcard> getSoundcard() {
        return soundcard;
    }

    public void setSoundcard(Optional<OptionalSoundcard> soundcard) {
        this.soundcard = soundcard;
    }

}
</code>```

And the well-successed test

```<code>@Test
public void runOptionalClassicOracleExample() throws Exception {

    USB usb = new USB();
    usb.setVersion("1");

    OptionalSoundcard soundcard = new OptionalSoundcard();
    soundcard.setUsb(Optional.ofNullable(usb));

    OptionalComputer computer = new OptionalComputer();
    computer.setSoundcard(Optional.ofNullable(soundcard));

    Optional<OptionalComputer> sc = Optional.of(computer);
    // Optional<Computer> sc = Optional.ofNullable(computer);
    String v1 = sc.flatMap(OptionalComputer::getSoundcard).flatMap(OptionalSoundcard::getUsb).map(USB::getVersion)
            .orElse("UNKNOWN");

    assertThat(v1, is(equalTo("1")));

}
</code>```

Now, imagine same Computer and Soundcar created with Java 7 pattern in mind (USB class is the same as above)

Soundcard

```<code>public class Soundcard {

    private USB usb;

    public Soundcard() {
        // TODO Auto-generated constructor stub
    }

    public USB getUsb() {
        return usb;
    }

    public void setUsb(USB usb) {
        this.usb = usb;
    }

}
</code>```

Computer

```<code>public class Computer {

    private Soundcard soundcard;

    public Computer() {
        // TODO Auto-generated constructor stub
    }

    public Soundcard getSoundcard() {
        return soundcard;
    }

    public void setSoundcard(Soundcard soundcard) {
        this.soundcard = soundcard;
    }

}
</code>```

And the test that even doesn't compile

```<code>@Test
public void runClassicOracleExample() throws Exception {

    USB usb = new USB();
    usb.setVersion("2");

    Soundcard soundcard = new Soundcard();
    soundcard.setUsb(usb);

    Computer computer = new Computer();
    computer.setSoundcard(soundcard);

    Optional<Computer> sc = Optional.ofNullable(computer);
    String v1 = sc.flatMap(Computer::getSoundcard).flatMap(Soundcard::getUsb).map(USB::getVersion)
            .orElse("UNKNOWN");

    assertThat(v1, is(equalTo("2")));
}
</code>```

The error is:

The method flatMap(Function>) in the type Optional is not applicable for the arguments
     (Computer::getSoundcard)
    - The type of getSoundcard() from the type Computer is Soundcard, this is incompatible with the descriptor's return type: Optional

*** edited

in real world I have

```<code>NamenOndernemingType 1 X 1 NaamOndernemingLijstCommercieelType 1 X List<> NaamOndernemingType
</code>```

I understand that all these three will produce the same results, except for one detail: null safety

```<code>// no Optional at all and no map() at all
NaamOndernemingLijstCommercieelType naamOndernemingLijstCommercieel = onderneming.getNamen()
        .getCommercieleNamen();
NaamOndernemingType naamOnderneming1 = naamOndernemingLijstCommercieel.getCommercieleNaam().stream()
        .filter(x -> x.getTaalcode().getValue() == "nl").findFirst().get();

// Optional.ofNullable wrapped only the list and flatMap the list
Optional<List<NaamOndernemingType>> optionalList = Optional
        .ofNullable(onderneming.getNamen().getCommercieleNamen().getCommercieleNaam());
NaamOndernemingType naamOnderneming2 = optionalList
        .flatMap(list -> list.stream().filter(s -> "nl".equals(s.getTaalcode().getValue())).findFirst()).get();

// Optional.ofNUllable on root element and map all other "levels" until get the
// list and strem()
Optional<NamenOndernemingType> optionalNamenOnderneming = Optional.ofNullable(onderneming.getNamen());
NaamOndernemingType naamOnderneminge = optionalNamenOnderneming.map(NamenOndernemingType::getCommercieleNamen)
        .map(NaamOndernemingLijstCommercieelType::getCommercieleNaam).get().stream().filter(Objects::nonNull)
        .filter(x -> x.getTaalcode().getValue() == "nl").findFirst().get();
</code>```

*** Future readers may find worth to read
how to use optional and filter along to retrieve an object from chained/cascaded objects generated by wsdl2java

My final solution become:

```<code>Optional.ofNullable(onderneming.getNamen()).map(NamenOndernemingType::getCommercieleNamen)
                .map(NaamOndernemingLijstCommercieelType::getCommercieleNaam).get().stream().filter(Objects::nonNull)
                .filter(x -> x.getTaalcode().getValue() == "nl").findFirst()
                .ifPresent(o -> myMethod("onderneming_commerciele_naam", o.getNaam().getValue()));
</code>```

答:
Why not just use .map()?

Because according to java doc of Optional#flatMap():

If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional.  This method is similar to #map(Function), but the provided mapper is one whose result is already an Optional, and if invoked, flatMap does not wrap it with an additional Optional.

The mapper used in flatMap must return an Optional. I think map will suit your needs better. because it wraps the result from Computer#getSoundcard() in an Optional.

Body:
Context: I have chained objects generated by wsdl2java so none of them contains java.util.Optional. There is an already created method that call the soap web services, receives the xml and unmarshalling it in cascaded objects.

Desire: I want to use Optional in order to avoid null tests.

I have already posted my dificults to accomplish it (how to use optional and filter along to retrieve an object from chained/cascaded objects generated by wsdl2java) but, after 3 days searching and reading I really got stuck and I realised that I have some gap in my knowlodge so I decided take a step back and try a more simple solution before moving forward.

I am wondering if I am really trying something that is possible to do: use Optional with a cascaded objects that weren't created with Optional pattern in mind. Most of the example I found in internet either use cascaded objects coded with "private Optional myObj" or they are limited to use Optional.of to an object, not to a tree of objects like generated by wsdl2java.

Here is what I tried so far to figure out if it is possible and I got stuck as well: I followed http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html and I tryed to apply same idea imagining the objects were coded originally with Java 7 (no private Optional myObj at all).

Firstly, exactly as showed by Oracle article (from parent to child dependency):

USB

public class USB {

    String version;
    public USB() {

    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
}

OptionalSoundcard

public class OptionalSoundcard {

    private Optional<USB> usb;

    public OptionalSoundcard() {
        // TODO Auto-generated constructor stub
    }

    public Optional<USB> getUsb() {
        return usb;
    }

    public void setUsb(Optional<USB> usb) {
        this.usb = usb;
    }

}

OptionalComputer

public class OptionalComputer {

    private Optional<OptionalSoundcard> soundcard;

    public OptionalComputer() {
    }

    public Optional<OptionalSoundcard> getSoundcard() {
        return soundcard;
    }

    public void setSoundcard(Optional<OptionalSoundcard> soundcard) {
        this.soundcard = soundcard;
    }

}

And the well-successed test

@Test
public void runOptionalClassicOracleExample() throws Exception {

    USB usb = new USB();
    usb.setVersion("1");

    OptionalSoundcard soundcard = new OptionalSoundcard();
    soundcard.setUsb(Optional.ofNullable(usb));

    OptionalComputer computer = new OptionalComputer();
    computer.setSoundcard(Optional.ofNullable(soundcard));

    Optional<OptionalComputer> sc = Optional.of(computer);
    // Optional<Computer> sc = Optional.ofNullable(computer);
    String v1 = sc.flatMap(OptionalComputer::getSoundcard).flatMap(OptionalSoundcard::getUsb).map(USB::getVersion)
            .orElse("UNKNOWN");

    assertThat(v1, is(equalTo("1")));

}

Now, imagine same Computer and Soundcar created with Java 7 pattern in mind (USB class is the same as above)

Soundcard

public class Soundcard {

    private USB usb;

    public Soundcard() {
        // TODO Auto-generated constructor stub
    }

    public USB getUsb() {
        return usb;
    }

    public void setUsb(USB usb) {
        this.usb = usb;
    }

}

Computer

public class Computer {

    private Soundcard soundcard;

    public Computer() {
        // TODO Auto-generated constructor stub
    }

    public Soundcard getSoundcard() {
        return soundcard;
    }

    public void setSoundcard(Soundcard soundcard) {
        this.soundcard = soundcard;
    }

}

And the test that even doesn't compile

@Test
public void runClassicOracleExample() throws Exception {

    USB usb = new USB();
    usb.setVersion("2");

    Soundcard soundcard = new Soundcard();
    soundcard.setUsb(usb);

    Computer computer = new Computer();
    computer.setSoundcard(soundcard);

    Optional<Computer> sc = Optional.ofNullable(computer);
    String v1 = sc.flatMap(Computer::getSoundcard).flatMap(Soundcard::getUsb).map(USB::getVersion)
            .orElse("UNKNOWN");

    assertThat(v1, is(equalTo("2")));
}

The error is:

The method flatMap(Function>) in the type Optional is not applicable for the arguments
     (Computer::getSoundcard)
    - The type of getSoundcard() from the type Computer is Soundcard, this is incompatible with the descriptor's return type: Optional

*** edited

in real world I have

NamenOndernemingType 1 X 1 NaamOndernemingLijstCommercieelType 1 X List<> NaamOndernemingType

I understand that all these three will produce the same results, except for one detail: null safety

// no Optional at all and no map() at all
NaamOndernemingLijstCommercieelType naamOndernemingLijstCommercieel = onderneming.getNamen()
        .getCommercieleNamen();
NaamOndernemingType naamOnderneming1 = naamOndernemingLijstCommercieel.getCommercieleNaam().stream()
        .filter(x -> x.getTaalcode().getValue() == "nl").findFirst().get();

// Optional.ofNullable wrapped only the list and flatMap the list
Optional<List<NaamOndernemingType>> optionalList = Optional
        .ofNullable(onderneming.getNamen().getCommercieleNamen().getCommercieleNaam());
NaamOndernemingType naamOnderneming2 = optionalList
        .flatMap(list -> list.stream().filter(s -> "nl".equals(s.getTaalcode().getValue())).findFirst()).get();

// Optional.ofNUllable on root element and map all other "levels" until get the
// list and strem()
Optional<NamenOndernemingType> optionalNamenOnderneming = Optional.ofNullable(onderneming.getNamen());
NaamOndernemingType naamOnderneminge = optionalNamenOnderneming.map(NamenOndernemingType::getCommercieleNamen)
        .map(NaamOndernemingLijstCommercieelType::getCommercieleNaam).get().stream().filter(Objects::nonNull)
        .filter(x -> x.getTaalcode().getValue() == "nl").findFirst().get();

*** Future readers may find worth to read
how to use optional and filter along to retrieve an object from chained/cascaded objects generated by wsdl2java

My final solution become:

Optional.ofNullable(onderneming.getNamen()).map(NamenOndernemingType::getCommercieleNamen)
                .map(NaamOndernemingLijstCommercieelType::getCommercieleNaam).get().stream().filter(Objects::nonNull)
                .filter(x -> x.getTaalcode().getValue() == "nl").findFirst()
                .ifPresent(o -> myMethod("onderneming_commerciele_naam", o.getNaam().getValue()));


来源: stackexchange

问:
Error to build .apk file of an ionic project
```<code>pampa@Pampa:~/Desktop/DemoApp$ ionic cordova platform add android
Platform android created
pampa@Pampa:~/Desktop/DemoApp$ cd platforms/android
pampa@Pampa:~/Desktop/DemoApp/platforms/android$ ionic android --release

[ERROR] Unable to find command: android
</code>```

答:
Which version of Ionic CLI are you using?

Since version 3.0.0 you should add the keyword cordova in your cmd if you want to build the cordova platform, like

```<code> ionic cordova android --prod --release
</code>```

Reference: https://github.com/ionic-team/ionic-cli/blob/master/CHANGELOG.md

ContentLicense: CC BY-SA 3.0

Body:
Which version of Ionic CLI are you using?

Since version 3.0.0 you should add the keyword cordova in your cmd if you want to build the cordova platform, like

 ionic cordova android --prod --release

Reference: https://github.com/ionic-team/ionic-cli/blob/master/CHANGELOG.md


问:
Converting ControlTemplate XAML to C#
I have been stumped with trying to convert the following code into pure c#.  This XAML code is from Cavanaghs blog on how to make rounded corners on anything.  The code works but I need to convert it to c# as i need it to be dynamic in some cases.  If you could help that would be great.

```<code><Setter Property="Template">
<Setter.Value>
    <ControlTemplate TargetType='{x:Type ListViewItem}'>
        <Grid>
            <Border CornerRadius="15" Name="mask" Background="White"/>
            <StackPanel Background="Beige">
                <StackPanel.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </StackPanel.OpacityMask>
                <GridViewRowPresenter Content="{TemplateBinding Content}" Columns="{TemplateBinding GridView.ColumnCollection}"/>
                <TextBlock Background="LightBlue" Text="{Binding News}" />
            </StackPanel>
        </Grid>
    </ControlTemplate>
</Setter.Value>
</code>```

So far I have the following but I am getting errors.

```<code>FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
border.SetValue(Border.BackgroundProperty, Brushes.White);
border.SetValue(Border.CornerRadiusProperty, new CornerRadius(8, 8, 8, 8));
border.SetValue(Border.NameProperty, "roundedMask");
</code>```

As far as I can tell I cant make the VisualBrush as a FrameworkElementFactory (crashes), but if i declare it as a regular element VisualBrush i cant pass border in as a Visual since its a FrameworkElementFactory.

Simply i am getting lost, any help would be appreciated.
Thanks for any help

答:
You don't actually have to convert this into C# to apply it dynamically. If you add it to your application resources, within your App.xaml file as follows:

```<code><Application.Resources>
    <ControlTemplate TargetType='{x:Type ListViewItem}' x:Key="MyListViewItemTemplate">
        <Grid>
            <Border CornerRadius="15" Name="mask" Background="White"/>
            <StackPanel Background="Beige">
                <StackPanel.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </StackPanel.OpacityMask>
                <GridViewRowPresenter Content="{TemplateBinding Content}" Columns="{TemplateBinding GridView.ColumnCollection}"/>
                <TextBlock Background="LightBlue" Text="{Binding News}" />
            </StackPanel>
        </Grid>
    </ControlTemplate>
</Application.Resources>
</code>```

Note the x:Key attribute which keys this item.

You can then look it up anywhere in your code ...

```<code>ControlTemplate template = this.Findresource("MyListViewItemTemplate") as ControlTemplate
</code>```

You can then apply it as and when you need it!

Title: Converting ControlTemplate XAML to C#

Body:
I have been stumped with trying to convert the following code into pure c#.  This XAML code is from Cavanaghs blog on how to make rounded corners on anything.  The code works but I need to convert it to c# as i need it to be dynamic in some cases.  If you could help that would be great.

<Setter Property="Template">
<Setter.Value>
    <ControlTemplate TargetType='{x:Type ListViewItem}'>
        <Grid>
            <Border CornerRadius="15" Name="mask" Background="White"/>
            <StackPanel Background="Beige">
                <StackPanel.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </StackPanel.OpacityMask>
                <GridViewRowPresenter Content="{TemplateBinding Content}" Columns="{TemplateBinding GridView.ColumnCollection}"/>
                <TextBlock Background="LightBlue" Text="{Binding News}" />
            </StackPanel>
        </Grid>
    </ControlTemplate>
</Setter.Value>

So far I have the following but I am getting errors.

FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
border.SetValue(Border.BackgroundProperty, Brushes.White);
border.SetValue(Border.CornerRadiusProperty, new CornerRadius(8, 8, 8, 8));
border.SetValue(Border.NameProperty, "roundedMask");

As far as I can tell I cant make the VisualBrush as a FrameworkElementFactory (crashes), but if i declare it as a regular element VisualBrush i cant pass border in as a Visual since its a FrameworkElementFactory.

Simply i am getting lost, any help would be appreciated.
Thanks for any help

Body:
You don't actually have to convert this into C# to apply it dynamically. If you add it to your application resources, within your App.xaml file as follows:

<Application.Resources>
    <ControlTemplate TargetType='{x:Type ListViewItem}' x:Key="MyListViewItemTemplate">
        <Grid>
            <Border CornerRadius="15" Name="mask" Background="White"/>
            <StackPanel Background="Beige">
                <StackPanel.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </StackPanel.OpacityMask>
                <GridViewRowPresenter Content="{TemplateBinding Content}" Columns="{TemplateBinding GridView.ColumnCollection}"/>
                <TextBlock Background="LightBlue" Text="{Binding News}" />
            </StackPanel>
        </Grid>
    </ControlTemplate>
</Application.Resources>

Note the x:Key attribute which keys this item.

You can then look it up anywhere in your code ...

ControlTemplate template = this.Findresource("MyListViewItemTemplate") as ControlTemplate

You can then apply it as and when you need it!

ContentLicense: CC BY-SA 2.5


问:
Architecture of activity / fragments for search bar
I have a project in which on main screen I show a list of items . (An activity and a fragment that contains the list )
In title bar I want to add a search functionality with autocompletetextview .
Now in title bar there are the title and "search" button . When the search will be clicked the title will be gone and autocomplete visible .
I would like to follow the functionality that is now in common apps : messages , gmail etc but I can t figure what it is the best solution regarding architecture of fragments/activity components to implement .
1, When I clicks the search button to show another fragment ?
2. When I click search button , title change visibility to gone and it will be used the same fragment with items and it will be updated ? </p>

答:
try with a simple MVP, organizing the view in a passive view(less data as possible). I have the feeling you are not practical of architecture if you ask, because looks as a simple question. MVP is in my personal opinion the best way to start.

you can test your app View using Espresso, and the business logic into the presenter with Junit.

From the project indicated on the first link, you can easy clone the project and see an App that is quite similar to the one you use( on click opens a new activity, activities/fragment) plus much more.


问:
Restoring of django database taking more time
For Django database backups and restore. I used this tool https://github.com/django-dbbackup/django-dbbackup. It is taking so much time to restore the database.

It is taking 3hours of time to restore a 500MB Compressed file. I used the below command.

```<code>time python manage.py dbrestore -i django_db_production_backup_20171109_0200.dump.gz -z
</code>```

Is there any alternative methods to reduce the time consumption.

答: Use the native tools of your database. E.g., PostgreSQL has pg_dump and pg_restore, which probably would backup and restore a 500 MB database in less than a minute.

Body:
For Django database backups and restore. I used this tool https://github.com/django-dbbackup/django-dbbackup. It is taking so much time to restore the database.

It is taking 3hours of time to restore a 500MB Compressed file. I used the below command.

time python manage.py dbrestore -i django_db_production_backup_20171109_0200.dump.gz -z

Is there any alternative methods to reduce the time consumption.


问:
How can I get the number of enums as a constant?
From Total number of items defined in an enum, I see I can get the number of enums by using:

```<code>Enum.GetNames(typeof(Item.Type)).Length;
</code>```

Works great!

But, I need this number as a constant number, so that I can use it in Unity's [Range(int, int)] feature.

```<code>private const int constEnumCount = Enum.GetNames(typeof(Item.Type)).Length;
</code>```

The above does not work, because the enum count is not a constant number, so I cannot assign it to a constant variable.

How can I get the number of enums as a constant?

答:
In C#, a const is defined as constant, i.e. the value (not the calculation which produced it!) is directly embedded in the compiled assembly.

To stop you from doing something problematic, the compiler does not allow you to assign the result of a calculation to a const. To understand why, imagine it were possible:

```<code>A.dll
  public enum Foo { A, B }

B.dll
  public const NumberOfFoos = Enum.GetNames(typeof(Foo)).Length;

// Compiles to:
B.dll
  public const NumberOfFoos = 2;
</code>```

Now you change A.dll:

```<code>A.dll
  public enum Foo { A, B, C, D }

B.dll
      public const NumberOfFoos = 2; // Oh no!
</code>```

So you would need to recompile B.dll to get the correct value.

It gets worse: Imagine you had an assembly C.dll, which uses B.NumberOfFoos. The value 2 would be directly embedded in C.dll, so it also would need to be recompiled, after B.dll, in order to get the correct value. Therefore (pit of success), C# does not allow you to do that assignment to a const.

Body:
From Total number of items defined in an enum, I see I can get the number of enums by using:

Enum.GetNames(typeof(Item.Type)).Length;

Works great!

But, I need this number as a constant number, so that I can use it in Unity's [Range(int, int)] feature.

private const int constEnumCount = Enum.GetNames(typeof(Item.Type)).Length;

The above does not work, because the enum count is not a constant number, so I cannot assign it to a constant variable.

How can I get the number of enums as a constant?

Body:
In C#, a const is defined as constant, i.e. the value (not the calculation which produced it!) is directly embedded in the compiled assembly.

To stop you from doing something problematic, the compiler does not allow you to assign the result of a calculation to a const. To understand why, imagine it were possible:

A.dll
  public enum Foo { A, B }

B.dll
  public const NumberOfFoos = Enum.GetNames(typeof(Foo)).Length;

// Compiles to:
B.dll
  public const NumberOfFoos = 2;

Now you change A.dll:

A.dll
  public enum Foo { A, B, C, D }

B.dll
      public const NumberOfFoos = 2; // Oh no!

So you would need to recompile B.dll to get the correct value.

It gets worse: Imagine you had an assembly C.dll, which uses B.NumberOfFoos. The value 2 would be directly embedded in C.dll, so it also would need to be recompiled, after B.dll, in order to get the correct value. Therefore (pit of success), C# does not allow you to do that assignment to a const.


问:
Activate a window using its Window ID
How would I programmatically activate i.e move-to-front-and-focus a window on macOS (not belonging to my app) given its Window ID. My app would run with user granted Accessibility permissions etc.

Surprisingly, none of the functions described on the Quartz Window Services page seem to do that.

Am using Swift currently, but am open to using Objective-C, AppleScript or whatever.

EDIT:

I don't want to bring to front all windows of the parent app - only the specific that matches the window ID.

Edit:

I know that the NSWindow type is only meant to refer to windows of the current process, but is there no class that represents windows owned by external apps? Like we have NSRunningApplication to refer to any running app including external ones, I was expecting an API to deal all open windows (assuming the right permissions). Is there some class like NSOpenWindow or CGWindow buried somewhere?

答:
I didn't find a way to switch to a specific window yet, but you can switch to the app that contains a specific window using this function:

```<code>func switchToApp(withWindow windowNumber: Int32) {
    let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
    let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
    guard let infoList = windowListInfo as NSArray? as? [[String: AnyObject]] else { return }
    if let window = infoList.first(where: { ($0["kCGWindowNumber"] as? Int32) == windowNumber}), let pid = window["kCGWindowOwnerPID"] as? Int32 {
        let app = NSRunningApplication(processIdentifier: pid)
        app?.activate(options: .activateIgnoringOtherApps)
    }
}
</code>```

It is probably usefull to switch by name as well:

```<code>func switchToApp(named windowOwnerName: String) {
    let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
    let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
    guard let infoList = windowListInfo as NSArray? as? [[String: AnyObject]] else { return }

    if let window = infoList.first(where: { ($0["kCGWindowOwnerName"] as? String) == windowOwnerName}), let pid = window["kCGWindowOwnerPID"] as? Int32 {
        let app = NSRunningApplication(processIdentifier: pid)
        app?.activate(options: .activateIgnoringOtherApps)
    }
}
</code>```

Example: switchToApp(named: "OpenOffice")

On my mac OpenOffice was started with a window with kCGWindowNumber = 599, so this has the same effect: switchToApp(withWindow: 599)

As far as I found out so far, your options seem to be to show the currently active window of the app, or to show all windows (using .activateAllWindows as activation option)

Title: Activate a window using its Window ID

Body:
I didn't find a way to switch to a specific window yet, but you can switch to the app that contains a specific window using this function:

func switchToApp(withWindow windowNumber: Int32) {
    let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
    let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
    guard let infoList = windowListInfo as NSArray? as? [[String: AnyObject]] else { return }
    if let window = infoList.first(where: { ($0["kCGWindowNumber"] as? Int32) == windowNumber}), let pid = window["kCGWindowOwnerPID"] as? Int32 {
        let app = NSRunningApplication(processIdentifier: pid)
        app?.activate(options: .activateIgnoringOtherApps)
    }
}

It is probably usefull to switch by name as well:

func switchToApp(named windowOwnerName: String) {
    let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
    let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
    guard let infoList = windowListInfo as NSArray? as? [[String: AnyObject]] else { return }

    if let window = infoList.first(where: { ($0["kCGWindowOwnerName"] as? String) == windowOwnerName}), let pid = window["kCGWindowOwnerPID"] as? Int32 {
        let app = NSRunningApplication(processIdentifier: pid)
        app?.activate(options: .activateIgnoringOtherApps)
    }
}

Example: switchToApp(named: "OpenOffice")

On my mac OpenOffice was started with a window with kCGWindowNumber = 599, so this has the same effect: switchToApp(withWindow: 599)

As far as I found out so far, your options seem to be to show the currently active window of the app, or to show all windows (using .activateAllWindows as activation option)


问:
Restrict a column of any type to specific values?
Similar to this question, can we use the pattern:

```<code>CONSTRAINT chk_X CHECK (X IN (...))
</code>```

For any SQL data type? E.g.:

```<code>CONSTRAINT chk_SomeIntField CHECK (SomeIntField IN (1,2,3,4))
</code>```

Where SomeIntField is an INTEGER?

答: You can use this for any data type that supports IN.  So it works for strings, numbers, and date/time values.

Body:
Similar to this question, can we use the pattern:

CONSTRAINT chk_X CHECK (X IN (...))

For any SQL data type? E.g.:

CONSTRAINT chk_SomeIntField CHECK (SomeIntField IN (1,2,3,4))

Where SomeIntField is an INTEGER?


问:
Implement restful url in .net where service is implemented using IHTTPHandler
I want to implement a restful service in ASP.NET. I want it to be compatible with .Net 2.0 and IIS 5+. I am constrained to not use ASP.NET MVC or REST starter kit. By reading on internet I have learned that it can be implemented using HTTPHandlers. The problem is, the request will come in as a POST request. And I want to URL to be like:

http://abc.com/MyService/MyMethod1/
and
http://abc.com/MyService/MyMethod2/

Any workarounds for this?

Thanks,
Vamyip

答:
I think this will be difficult to do because IIS 5 will not let you handle non ASP.NET file extensions without some additional configuration in IIS. That means you are limited to URLs ending in .aspx etc. To handle URLs like those in your examples you need to map ASP.NET to handle all URLs in IIS, implement some type of URL rewriting, or introduce some kind of hacky 404 redirection.

Once you have the correct mapping in place you can wire up an IHttpHandler, but you will have to parse the incoming request yourself to work out which is /MyService/MyMethod1/ and which is for /MyService/MyMethod2/. If your methods are simple then it is easy to do this with a regular expression.

You should start with a simple handler like this one.


问:
`setAppends([])` on relation which is being loaded by `with` in Laravel
So for my project model setAppends([]) works as below:

```<code>Project::find($projectId)->setAppends([])
</code>```

but what if I want to set appends to empty array for a relation which I'm eager loading with with, like below:

```<code>$project = Project::with('pages')->find($projectId);
</code>```

->setAppends([]) not working in above code, as it will set it to empty array for Project not for Page.

Can anyone guide how to achieve that ?

Update:

page.php Model has appends and hidden like this:

```<code>class Page extends Model {
    // I don't want to load this (`appends`) attributes when I call Project::find($projectId)
    protected $appends = ['thumbnail_url', 'total_annotations', 'total_tasks', 'total_done_tasks', 'image_url', 'edited_data_items_count'];
    protected $hidden = ['tasksCount', 'doneTasksCount', 'annotationsCount', 'xsl', 'xml', 'dataxml_version', 'sort_order', 'editedDataItemsCount', 'deletedDataItemsCount'];
}
</code>```

Project.php model looks like this:

```<code>class Project extends Model {

    use SoftDeletes;

    protected $appends = ['total_tasks', 'total_done_tasks', 'total_pages', 'total_annotations', 'edited_dataitems_total_count'];
    protected $hidden = ['tasksCount', 'doneTasksCount', 'pagesCount', 'annotationsCount', 'folder_path', 'attachment_url', 'pages'];
}
</code>```

答:
On Project you may provide a static method, which allows you to iterate over the eagerly loaded pages and adjust their append-array.

```<code>    class Project
    {
        ...

        public static function eagerFindWithoutAppends($projectId)
        {
            $model = self::with('pages')->find($projectId);
            $model->setAppends([]);

            foreach ($model->pages as $page) {
                $page->setAppends([]);
            }

            return $model;
        }

        ...
    }
</code>```

But if I understand correctly, the dynamic data in your Pages class does more than just providing convenient shortcuts based on the regularly loaded data (such as something like getFullName which would combine first_name and last_name).

What do your appends do?

I don't want to load this (appends) attributes

Another possible solution I could think of is to inherit NoneAppendPages from Pages and override $append and all the related get... methods.

Then in Project declare another relationship to NoneAppendPages next to Pages. You then eager load Project::::with('none_append_pages')->find($projectId);

```<code>class NoneAppendPages extends Pages
{

    protected $appends = [];

    getYourDynamicAttributeMethodName() { return null; } // for all your appends

}

class Project
{
    public function pages()
    {
       // I don't know what relationship you declared / assuming on to many
        return $this->hasMany('App\Page');
    }

    public function noneAppendPages()
    {
       // declare the same way you did with pages
        return $this->hasMany('App\NoneAppendPage');
    }

}
</code>```

Body:
So for my project model setAppends([]) works as below:

Project::find($projectId)->setAppends([])

but what if I want to set appends to empty array for a relation which I'm eager loading with with, like below:

$project = Project::with('pages')->find($projectId);

->setAppends([]) not working in above code, as it will set it to empty array for Project not for Page.

Can anyone guide how to achieve that ?

Update:

page.php Model has appends and hidden like this:

class Page extends Model {
    // I don't want to load this (`appends`) attributes when I call Project::find($projectId)
    protected $appends = ['thumbnail_url', 'total_annotations', 'total_tasks', 'total_done_tasks', 'image_url', 'edited_data_items_count'];
    protected $hidden = ['tasksCount', 'doneTasksCount', 'annotationsCount', 'xsl', 'xml', 'dataxml_version', 'sort_order', 'editedDataItemsCount', 'deletedDataItemsCount'];
}

Project.php model looks like this:

class Project extends Model {

    use SoftDeletes;

    protected $appends = ['total_tasks', 'total_done_tasks', 'total_pages', 'total_annotations', 'edited_dataitems_total_count'];
    protected $hidden = ['tasksCount', 'doneTasksCount', 'pagesCount', 'annotationsCount', 'folder_path', 'attachment_url', 'pages'];
}

Body:
On Project you may provide a static method, which allows you to iterate over the eagerly loaded pages and adjust their append-array.

    class Project
    {
        ...

        public static function eagerFindWithoutAppends($projectId)
        {
            $model = self::with('pages')->find($projectId);
            $model->setAppends([]);

            foreach ($model->pages as $page) {
                $page->setAppends([]);
            }

            return $model;
        }

        ...
    }

But if I understand correctly, the dynamic data in your Pages class does more than just providing convenient shortcuts based on the regularly loaded data (such as something like getFullName which would combine first_name and last_name).

What do your appends do?

I don't want to load this (appends) attributes

Another possible solution I could think of is to inherit NoneAppendPages from Pages and override $append and all the related get... methods.

Then in Project declare another relationship to NoneAppendPages next to Pages. You then eager load Project::::with('none_append_pages')->find($projectId);

class NoneAppendPages extends Pages
{

    protected $appends = [];

    getYourDynamicAttributeMethodName() { return null; } // for all your appends

}

class Project
{
    public function pages()
    {
       // I don't know what relationship you declared / assuming on to many
        return $this->hasMany('App\Page');
    }

    public function noneAppendPages()
    {
       // declare the same way you did with pages
        return $this->hasMany('App\NoneAppendPage');
    }

}


问:
Google pubsub: pull java sample client hanging
I am using google pubsub to pull messages from a subscribed topic asynchronously.

I am using the below sample code:

```<code>   public void startStreaming() {
        Subscriber subscriber = null;
        try {
            SubscriptionName subscription = SubscriptionName.of("topic-test",
                    "subscription-id-1234");
            ExecutorProvider executorProvider =
                    InstantiatingExecutorProvider.newBuilder()
                            .setExecutorThreadCount(1)
                            .build();

            MessageReceiver receiver =
                    new MessageReceiver() {
                        @Override
                        public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
                            try {
                                String msg = message.getData().toStringUtf8();
                                System.out.println(msg);
                            } catch (Exception e) {
                                throw new RuntimeException("Failed to pull messages from topic");
                            }
                            consumer.ack();
                        }
                    };
            subscriber = Subscriber
                    .newBuilder(subscription, receiver)
                    .setExecutorProvider(executorProvider)
                    .build();
            subscriber.addListener(
                    new Subscriber.Listener() {
                        @Override
                        public void failed(Subscriber.State from, Throwable failure) {
                            // Handle failure. This is called when the Subscriber encountered a fatal error and is shutting down.
                            logger.error("Subscriber is not able to hook on google pubsub topic", failure);
                        }
                    },
                    MoreExecutors.directExecutor());
            subscriber.startAsync().awaitRunning();
            // why should I put sleep here??
            Thread.sleep(60000);
        } catch (Exception e) {
        } finally {
            if (subscriber != null) {
                subscriber.stopAsync().awaitTerminated();
            }
        }
    }
</code>```

It works fine (ingest messages) for few minutes and get stuck with no more ingestion of messages, I am sure that there are messages as once I restarted the pulling client, it reads data normally.

```<code>Nov 12, 2017 7:33:17 PM com.google.cloud.pubsub.v1.StreamingSubscriberConnection sendAckOperations
WARNING: failed to send acks
java.lang.IllegalStateException: call was cancelled
    at com.google.common.base.Preconditions.checkState(Preconditions.java:444)
    at io.grpc.internal.ClientCallImpl.sendMessage(ClientCallImpl.java:405)
    at io.grpc.ForwardingClientCall.sendMessage(ForwardingClientCall.java:52)
    at io.grpc.ForwardingClientCall.sendMessage(ForwardingClientCall.java:52)
    at io.grpc.stub.ClientCalls$CallToStreamObserverAdapter.onNext(ClientCalls.java:286)
    at com.google.cloud.pubsub.v1.StreamingSubscriberConnection.sendAckOperations(StreamingSubscriberConnection.java:274)
    at com.google.cloud.pubsub.v1.MessageDispatcher.processOutstandingAckOperations(MessageDispatcher.java:602)
    at com.google.cloud.pubsub.v1.MessageDispatcher.access$2100(MessageDispatcher.java:56)
    at com.google.cloud.pubsub.v1.MessageDispatcher$AckDeadlineAlarm.run(MessageDispatcher.java:529)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

And when don't use ExecutorProvider executorProvider I got the below log

```<code>2017-11-12 19:08:43 [grpc-default-worker-ELG-2-3] DEBUG io.grpc.netty.NettyClientHandler [id: 0xdc0e7c4d, L:/10.8.17.4:47347 - R:pubsub.googleapis.com/1.1.1.1:111] OUTBOUND WINDOW_UPDATE: streamId=3 windowSizeIncrement=1048576
2017-11-12 19:08:43 [grpc-default-worker-ELG-2-4] DEBUG io.grpc.netty.NettyClientHandler [id: 0x330498ce, L:/10.8.17.4:47346 - R:pubsub.googleapis.com/1.1.1.1:111] OUTBOUND GO_AWAY: lastStreamId=0 errorCode=0 length=0 bytes=
2017-11-12 19:08:43 [grpc-default-worker-ELG-2-3] DEBUG io.grpc.netty.NettyClientHandler [id: 0xdc0e7c4d, L:/10.8.17.4:47347 - R:pubsub.googleapis.com/1.1.1.1:111] OUTBOUND GO_AWAY: lastStreamId=0 errorCode=0 length=0 bytes=
2017-11-12 19:08:44 [threadDeathWatcher-1-1] DEBUG io.netty.buffer.PoolThreadCache Freed 3 thread-local buffer(s) from thread: threadDeathWatcher-1-1
2017-11-12 19:08:44 [threadDeathWatcher-1-1] DEBUG io.netty.buffer.PoolThreadCache Freed 1 thread-local buffer(s) from thread: threadDeathWatcher-1-1
2017-11-12 19:08:44 [grpc-default-worker-ELG-2-3] DEBUG io.netty.buffer.PoolThreadCache Freed 153 thread-local buffer(s) from thread: grpc-default-worker-ELG-2-3
2017-11-12 19:08:44 [grpc-default-worker-ELG-2-4] DEBUG io.netty.buffer.PoolThreadCache Freed 131 thread-local buffer(s) from thread: grpc-default-worker-ELG-2-4
</code>```

Could you please help?

答:
It is now working fine, was to remove the below

```<code>lines,

//            if (subscriber != null) {
//                subscriber.stopAsync().awaitTerminated();
//            }
</code>```

The explanation, here is this github thread 1827

And it really make sense, what is missing is more documentation in Google-cloud docs give more details about like the comment provided in the github thread.

Edit:
Github ticket is created to add more documentation, and closed below:
2616

Body:
I am using google pubsub to pull messages from a subscribed topic asynchronously.

I am using the below sample code:

   public void startStreaming() {
        Subscriber subscriber = null;
        try {
            SubscriptionName subscription = SubscriptionName.of("topic-test",
                    "subscription-id-1234");
            ExecutorProvider executorProvider =
                    InstantiatingExecutorProvider.newBuilder()
                            .setExecutorThreadCount(1)
                            .build();

            MessageReceiver receiver =
                    new MessageReceiver() {
                        @Override
                        public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
                            try {
                                String msg = message.getData().toStringUtf8();
                                System.out.println(msg);
                            } catch (Exception e) {
                                throw new RuntimeException("Failed to pull messages from topic");
                            }
                            consumer.ack();
                        }
                    };
            subscriber = Subscriber
                    .newBuilder(subscription, receiver)
                    .setExecutorProvider(executorProvider)
                    .build();
            subscriber.addListener(
                    new Subscriber.Listener() {
                        @Override
                        public void failed(Subscriber.State from, Throwable failure) {
                            // Handle failure. This is called when the Subscriber encountered a fatal error and is shutting down.
                            logger.error("Subscriber is not able to hook on google pubsub topic", failure);
                        }
                    },
                    MoreExecutors.directExecutor());
            subscriber.startAsync().awaitRunning();
            // why should I put sleep here??
            Thread.sleep(60000);
        } catch (Exception e) {
        } finally {
            if (subscriber != null) {
                subscriber.stopAsync().awaitTerminated();
            }
        }
    }

It works fine (ingest messages) for few minutes and get stuck with no more ingestion of messages, I am sure that there are messages as once I restarted the pulling client, it reads data normally.

Nov 12, 2017 7:33:17 PM com.google.cloud.pubsub.v1.StreamingSubscriberConnection sendAckOperations
WARNING: failed to send acks
java.lang.IllegalStateException: call was cancelled
    at com.google.common.base.Preconditions.checkState(Preconditions.java:444)
    at io.grpc.internal.ClientCallImpl.sendMessage(ClientCallImpl.java:405)
    at io.grpc.ForwardingClientCall.sendMessage(ForwardingClientCall.java:52)
    at io.grpc.ForwardingClientCall.sendMessage(ForwardingClientCall.java:52)
    at io.grpc.stub.ClientCalls$CallToStreamObserverAdapter.onNext(ClientCalls.java:286)
    at com.google.cloud.pubsub.v1.StreamingSubscriberConnection.sendAckOperations(StreamingSubscriberConnection.java:274)
    at com.google.cloud.pubsub.v1.MessageDispatcher.processOutstandingAckOperations(MessageDispatcher.java:602)
    at com.google.cloud.pubsub.v1.MessageDispatcher.access$2100(MessageDispatcher.java:56)
    at com.google.cloud.pubsub.v1.MessageDispatcher$AckDeadlineAlarm.run(MessageDispatcher.java:529)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

And when don't use ExecutorProvider executorProvider I got the below log

2017-11-12 19:08:43 [grpc-default-worker-ELG-2-3] DEBUG io.grpc.netty.NettyClientHandler [id: 0xdc0e7c4d, L:/10.8.17.4:47347 - R:pubsub.googleapis.com/1.1.1.1:111] OUTBOUND WINDOW_UPDATE: streamId=3 windowSizeIncrement=1048576
2017-11-12 19:08:43 [grpc-default-worker-ELG-2-4] DEBUG io.grpc.netty.NettyClientHandler [id: 0x330498ce, L:/10.8.17.4:47346 - R:pubsub.googleapis.com/1.1.1.1:111] OUTBOUND GO_AWAY: lastStreamId=0 errorCode=0 length=0 bytes=
2017-11-12 19:08:43 [grpc-default-worker-ELG-2-3] DEBUG io.grpc.netty.NettyClientHandler [id: 0xdc0e7c4d, L:/10.8.17.4:47347 - R:pubsub.googleapis.com/1.1.1.1:111] OUTBOUND GO_AWAY: lastStreamId=0 errorCode=0 length=0 bytes=
2017-11-12 19:08:44 [threadDeathWatcher-1-1] DEBUG io.netty.buffer.PoolThreadCache Freed 3 thread-local buffer(s) from thread: threadDeathWatcher-1-1
2017-11-12 19:08:44 [threadDeathWatcher-1-1] DEBUG io.netty.buffer.PoolThreadCache Freed 1 thread-local buffer(s) from thread: threadDeathWatcher-1-1
2017-11-12 19:08:44 [grpc-default-worker-ELG-2-3] DEBUG io.netty.buffer.PoolThreadCache Freed 153 thread-local buffer(s) from thread: grpc-default-worker-ELG-2-3
2017-11-12 19:08:44 [grpc-default-worker-ELG-2-4] DEBUG io.netty.buffer.PoolThreadCache Freed 131 thread-local buffer(s) from thread: grpc-default-worker-ELG-2-4

Could you please help?

Body:
It is now working fine, was to remove the below

lines,

//            if (subscriber != null) {
//                subscriber.stopAsync().awaitTerminated();
//            }

The explanation, here is this github thread 1827

And it really make sense, what is missing is more documentation in Google-cloud docs give more details about like the comment provided in the github thread.

Edit:
Github ticket is created to add more documentation, and closed below:
2616


问:
recyclerView.setOnScrollChangeListener not working
this is my fragment code.
i m usimg this code for endless recycler view which is get the data from server when scroll the recycler view item. but the code is not working. in this code recyclerView.setOnScrollChangeListener() not working it shows error view cannot be applied to android.content .context.
how to use the setOnScrollChangeListener in fragment to load the data from server  when scroll the list.

```<code>    public class Fragment1 extends Fragment implements
    RecyclerView.OnScrollChangeListener{
    //Creating a List of superheroes
     private List<SuperHero> listSuperHeroes;

     //Creating Views
     private RecyclerView recyclerView;
     private RecyclerView.LayoutManager layoutManager;
     private RecyclerView.Adapter adapter;
     public ProgressBar progressBar;

     //Volley Request Queue
      private RequestQueue requestQueue;

       //The request counter to send ?page=1, ?page=2  requests
       private int requestCount = 1;

       public Fragment1() {}

       @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        }

      @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup
        container, Bundle savedInstanceState) {
         // Inflate the layout for this fragment
         View view= inflater.inflate(R.layout.activity_main, container,
       false);
       //Initializing Views
       recyclerView.setLayoutManager(layoutManager);

    //Initializing our superheroes list
    listSuperHeroes = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(getContext());

    //Calling method to get data to fetch data
    getData();

    //Adding an scroll change listener to recyclerview
    recyclerView.setOnScrollChangeListener(getActivity());

    //initializing our adapter
    adapter = new CardAdapter(listSuperHeroes, getActivity());

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);
 progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
    return view;
}

//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
    //Initializing ProgressBar

    //Displaying Progressbar
   // progressBar.setVisibility(View.VISIBLE);
    //setProgressBarIndeterminateVisibility(true);

    //JsonArrayRequest of volley
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    //Calling method parseData to parse the json response

                    Log.e("response",response.toString());
                    parseData(response);
                    //Hiding the progressbar
                    progressBar.setVisibility(View.GONE);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressBar.setVisibility(View.GONE);
                    //If an error occurs that means end of the list has reached
                    Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
                }
            });

    //Returning the request
    return jsonArrayRequest;
}

//This method will get data from the web api
private void getData() {
    //Adding the method to the queue by calling the method getDataFromServer
    requestQueue.add(getDataFromServer(requestCount));
    //Incrementing the request counter
    requestCount++;
}

//This method will parse json data
private void parseData(JSONArray array) {
    for (int i = 0; i < array.length(); i++) {
        //Creating the superhero object
        //int a= array.length();
        //String s=String.valueOf(a);
        //Log.e("array",s);
        SuperHero superHero = new SuperHero();
        JSONObject json = null;
        try {
            //Getting json
            json = array.getJSONObject(i);

            //Adding data to the superhero object
            superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
            //superHero.setName(json.getString(Config.TAG_NAME));
            //superHero.setPublisher(json.getString(Config.TAG_PUBLISHER));
            superHero.setMglId(json.getString(Config.TAG_MGLID));
            superHero.setAgeHeight(json.getString(Config.TAG_AGEHEIGHT));
            superHero.setCommunity(json.getString(Config.TAG_COMMUNITY));
            superHero.setOccupation(json.getString(Config.TAG_OCCUPATION));
            superHero.setIncome(json.getString(Config.TAG_INCOME));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Adding the superhero object to the list
        listSuperHeroes.add(superHero);
    }

    //Notifying the adapter that data has been added or changed
    adapter.notifyDataSetChanged();
}

//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
    if (recyclerView.getAdapter().getItemCount() != 0) {
        int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
        if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
            return true;
    }
    return false;
}

//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    //Ifscrolled at last then
    if (isLastItemDisplaying(recyclerView)) {
        //Calling the method getdata again
        getData();
    }
}
</code>```

}

答:
Use this

```<code>recyclerView.setOnScrollChangeListener(Fragment1.this);
</code>```

instead of this

```<code>recyclerView.setOnScrollChangeListener(getActivity());
</code>```

Edit

```<code>recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isLastItemDisplaying(recyclerView)) {
                  //Calling the method getdata again
                   getData();
                }
            }
        });
</code>```

Body:
this is my fragment code.
i m usimg this code for endless recycler view which is get the data from server when scroll the recycler view item. but the code is not working. in this code recyclerView.setOnScrollChangeListener() not working it shows error view cannot be applied to android.content .context.
how to use the setOnScrollChangeListener in fragment to load the data from server  when scroll the list.

    public class Fragment1 extends Fragment implements
    RecyclerView.OnScrollChangeListener{
    //Creating a List of superheroes
     private List<SuperHero> listSuperHeroes;

     //Creating Views
     private RecyclerView recyclerView;
     private RecyclerView.LayoutManager layoutManager;
     private RecyclerView.Adapter adapter;
     public ProgressBar progressBar;

     //Volley Request Queue
      private RequestQueue requestQueue;

       //The request counter to send ?page=1, ?page=2  requests
       private int requestCount = 1;

       public Fragment1() {}

       @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        }

      @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup
        container, Bundle savedInstanceState) {
         // Inflate the layout for this fragment
         View view= inflater.inflate(R.layout.activity_main, container,
       false);
       //Initializing Views
       recyclerView.setLayoutManager(layoutManager);

    //Initializing our superheroes list
    listSuperHeroes = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(getContext());

    //Calling method to get data to fetch data
    getData();

    //Adding an scroll change listener to recyclerview
    recyclerView.setOnScrollChangeListener(getActivity());

    //initializing our adapter
    adapter = new CardAdapter(listSuperHeroes, getActivity());

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);
 progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
    return view;
}

//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
    //Initializing ProgressBar

    //Displaying Progressbar
   // progressBar.setVisibility(View.VISIBLE);
    //setProgressBarIndeterminateVisibility(true);

    //JsonArrayRequest of volley
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    //Calling method parseData to parse the json response

                    Log.e("response",response.toString());
                    parseData(response);
                    //Hiding the progressbar
                    progressBar.setVisibility(View.GONE);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressBar.setVisibility(View.GONE);
                    //If an error occurs that means end of the list has reached
                    Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
                }
            });

    //Returning the request
    return jsonArrayRequest;
}

//This method will get data from the web api
private void getData() {
    //Adding the method to the queue by calling the method getDataFromServer
    requestQueue.add(getDataFromServer(requestCount));
    //Incrementing the request counter
    requestCount++;
}

//This method will parse json data
private void parseData(JSONArray array) {
    for (int i = 0; i < array.length(); i++) {
        //Creating the superhero object
        //int a= array.length();
        //String s=String.valueOf(a);
        //Log.e("array",s);
        SuperHero superHero = new SuperHero();
        JSONObject json = null;
        try {
            //Getting json
            json = array.getJSONObject(i);

            //Adding data to the superhero object
            superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
            //superHero.setName(json.getString(Config.TAG_NAME));
            //superHero.setPublisher(json.getString(Config.TAG_PUBLISHER));
            superHero.setMglId(json.getString(Config.TAG_MGLID));
            superHero.setAgeHeight(json.getString(Config.TAG_AGEHEIGHT));
            superHero.setCommunity(json.getString(Config.TAG_COMMUNITY));
            superHero.setOccupation(json.getString(Config.TAG_OCCUPATION));
            superHero.setIncome(json.getString(Config.TAG_INCOME));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Adding the superhero object to the list
        listSuperHeroes.add(superHero);
    }

    //Notifying the adapter that data has been added or changed
    adapter.notifyDataSetChanged();
}

//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
    if (recyclerView.getAdapter().getItemCount() != 0) {
        int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
        if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
            return true;
    }
    return false;
}

//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    //Ifscrolled at last then
    if (isLastItemDisplaying(recyclerView)) {
        //Calling the method getdata again
        getData();
    }
}

}

Body:
Use this

recyclerView.setOnScrollChangeListener(Fragment1.this);

instead of this

recyclerView.setOnScrollChangeListener(getActivity());

Edit

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isLastItemDisplaying(recyclerView)) {
                  //Calling the method getdata again
                   getData();
                }
            }
        });


问:
Python iterate over specific column in csv , and replacing values
First sorry for my english ;)

I have a problem regarding a csv file. The file contains a lot of col. with a lot of different features. I want to iterate over the col. host_location to get the entries of each row. For each String which contains ("London" or "london") i want to change the string into an binary. So if the string contains "London" or "london" the entry should be 1 , if not 0.

Im familiar with Java, but Python is new for me.

What i know so far with reference to this problem:

i cant change the csv file directly, i have to read it, change the value and write it back to a new file.

My method so far:

```<code>listings = io.read_csv('../data/playground/neu.csv')

def Change_into_Binaryy():
  listings.loc[listings["host_location"] == ( "London" or
  "london"),"host_location"] = 1
  listings.to_csv("../data/playground/neu1.csv",index =False)
</code>```

The code is from another question of stackoverflow, and im really not familiar with Python so far. The problem is that i can only use the equal operator and not something like contains in java.

As a result only the entries with the string "London" or "london" are changed to 1. But there are also entries like "London, Uk" that i want to change

In addition i don't know how i can change the remaining entries to 0 , because i don't know how i can combine the .loc with sth. like a if/else construct

I also tried another solution:

```<code>def Change_into_Binary():

for x in  listings['host_location']:
    if "London" or "london" in x:
        x = 1

    else:
        x = 0

listings.to_csv("../data/playground/neu1.csv",index =False)
</code>```

But also do not work. In this case the entries are not changed.

Thanks for you answers

答:
```<code>from csv import DictReader, DictWriter

with open('infile.csv', 'r') as infile, open('outfile.csv', 'w') as outfile:
    reader = DictReader(infile)
    writer = DictWriter(outfile, fieldnames=reader.fieldnames)
    writer.writeheader()
    for row in reader:
        if row['host_location'].capitalize() == 'London':
            row['host_location'] = 1
        else:
            row['host_location'] = 0
        writer.writerow(row)
</code>```

Body:
First sorry for my english ;)

I have a problem regarding a csv file. The file contains a lot of col. with a lot of different features. I want to iterate over the col. host_location to get the entries of each row. For each String which contains ("London" or "london") i want to change the string into an binary. So if the string contains "London" or "london" the entry should be 1 , if not 0.

Im familiar with Java, but Python is new for me.

What i know so far with reference to this problem:

i cant change the csv file directly, i have to read it, change the value and write it back to a new file.

My method so far:

listings = io.read_csv('../data/playground/neu.csv')

def Change_into_Binaryy():
  listings.loc[listings["host_location"] == ( "London" or
  "london"),"host_location"] = 1
  listings.to_csv("../data/playground/neu1.csv",index =False)

The code is from another question of stackoverflow, and im really not familiar with Python so far. The problem is that i can only use the equal operator and not something like contains in java.

As a result only the entries with the string "London" or "london" are changed to 1. But there are also entries like "London, Uk" that i want to change

In addition i don't know how i can change the remaining entries to 0 , because i don't know how i can combine the .loc with sth. like a if/else construct

I also tried another solution:

def Change_into_Binary():

for x in  listings['host_location']:
    if "London" or "london" in x:
        x = 1

    else:
        x = 0

listings.to_csv("../data/playground/neu1.csv",index =False)

But also do not work. In this case the entries are not changed.

Thanks for you answers


问:
SharedPrefenrences not storing boolean value
Am trying save boolean FAVOURITE data in sharedPreferences. when phone is rotated or closed .It is not working it is taking default value. I don't know whats wrong with this code. i am unable to figure out whats the problem is can someone show me the problem with the code</p>

```<code>//Context context =this;

 String FAVOURITE = "selected";

boolean favourite = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState!=null){
        favourite = savedInstanceState.getBoolean(FAVOURITE,false);
        Toast.makeText(this,""+favourite,Toast.LENGTH_SHORT).show();

    }

    final Bundle queryBundle = new Bundle();

    movieObject=(CardsClass)getIntent().getSerializableExtra("movieObject");

    setTitle(movieObject.getmTitle());

    setContentView(R.layout.activity_details);

    final ImageView fav = (ImageView)findViewById(R.id.fav);

    fav.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (favourite == false) {

                favourite = true;

                fav.setImageResource(R.drawable.fav_on);

                Toast.makeText(DetailsActivity.this, favourite + " is added to favourites", Toast.LENGTH_SHORT).show();

                queryBundle.putBoolean(FAVOURITE,favourite);

            }

            else if(favourite){

                favourite=false;

                fav.setImageResource(R.drawable.fav_off);

                queryBundle.putBoolean(FAVOURITE,favourite);

                Toast.makeText(DetailsActivity.this, movieObject.getmTitle() + " is removed from favourites", Toast.LENGTH_SHORT).show();

            }
        }
    });
</code>```

答:
To write or read in the SharedPreferences

Write:

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(FAVORITE, favorite);
editor.commit();
</code>```

Read:

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Boolean favorite = sharedPref.getBoolean(FAVORITE, true);
</code>```

Body:
Am trying save boolean FAVOURITE data in sharedPreferences. when phone is rotated or closed .It is not working it is taking default value. I don't know whats wrong with this code. i am unable to figure out whats the problem is can someone show me the problem with the code

//Context context =this;

 String FAVOURITE = "selected";

boolean favourite = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState!=null){
        favourite = savedInstanceState.getBoolean(FAVOURITE,false);
        Toast.makeText(this,""+favourite,Toast.LENGTH_SHORT).show();

    }

    final Bundle queryBundle = new Bundle();

    movieObject=(CardsClass)getIntent().getSerializableExtra("movieObject");

    setTitle(movieObject.getmTitle());

    setContentView(R.layout.activity_details);

    final ImageView fav = (ImageView)findViewById(R.id.fav);

    fav.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (favourite == false) {

                favourite = true;

                fav.setImageResource(R.drawable.fav_on);

                Toast.makeText(DetailsActivity.this, favourite + " is added to favourites", Toast.LENGTH_SHORT).show();

                queryBundle.putBoolean(FAVOURITE,favourite);

            }

            else if(favourite){

                favourite=false;

                fav.setImageResource(R.drawable.fav_off);

                queryBundle.putBoolean(FAVOURITE,favourite);

                Toast.makeText(DetailsActivity.this, movieObject.getmTitle() + " is removed from favourites", Toast.LENGTH_SHORT).show();

            }
        }
    });

Body:
To write or read in the SharedPreferences

Write:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(FAVORITE, favorite);
editor.commit();

Read:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Boolean favorite = sharedPref.getBoolean(FAVORITE, true);


问:
Binary operator '/' cannot be applied to two 'T' operands
```<code>struct PickerRange<T: Comparable> {
    var start: T
    var end: T
    var step: T

    var length: T {
        // Binary operator '/' cannot be applied to two 'T' operands.
        return max(start, end) - min(start,end) / step
    }
}
</code>```

Error is generated when creating computed properties. How to fix?

答:
Simply specify one of the Numeric protocols.

For floating point precision:

```<code>struct PickerRange<T:FloatingPoint> {
    var start: T
    var end: T
    var step: T

    var length: T {
        return max(start, end) -  (min(start,end) / step)
    }
}
</code>```

SignedInteger, UnsignedInteger or other Numeric protocols are also an option.

// Comparable

Neither of these require of you to specify Comparable additionally, so specifying one of these is suffice for the case.

EDIT:

How to make one structure for Int and Double?

Essentially, you can, by specifying SignedNumeric:

```<code>struct PickerRange<T:SignedNumeric & Comparable> {
    var start: T
    var end: T
    var step: T
}

// Treated as PickerRange<Double>
let a = PickerRange(start: 1.0, end: 5.0, step: 1)

// Treated as PickerRange<Int>
let b = PickerRange(start: 1, end: 5, step: 1)
</code>```

However, you have specialized length property, which includes / operator not supported by SignedNumeric. A workaround would consist in type-checking/force-casting to a type you have initialized your struct with:

```<code>struct PickerRange<T:SignedNumeric & Comparable> {
    var start: T
    var end: T
    var step: T

    var length: T {
        if T.self is Double.Type {
            return (max(start, end) as! Double) - ((min(start, end) as! Double) / (step as! Double)) as! T
        } else if T.self is Int.Type {
            return (max(start, end) as! Int) - ((min(start, end) as! Int) / (step as! Int)) as! T
        } else {
            return 0
        }
    }
}

let a = PickerRange(start: 1.0, end: 5.0, step: 1)
let b = PickerRange(start: 1, end: 10, step: 1)

print(a.length)
print(b.length)
</code>```

Body:
struct PickerRange<T: Comparable> {
    var start: T
    var end: T
    var step: T

    var length: T {
        // Binary operator '/' cannot be applied to two 'T' operands.
        return max(start, end) - min(start,end) / step
    }
}

Error is generated when creating computed properties. How to fix?

Body:
Simply specify one of the Numeric protocols.

For floating point precision:

struct PickerRange<T:FloatingPoint> {
    var start: T
    var end: T
    var step: T

    var length: T {
        return max(start, end) -  (min(start,end) / step)
    }
}

SignedInteger, UnsignedInteger or other Numeric protocols are also an option.

// Comparable

Neither of these require of you to specify Comparable additionally, so specifying one of these is suffice for the case.

EDIT:

How to make one structure for Int and Double?

Essentially, you can, by specifying SignedNumeric:

struct PickerRange<T:SignedNumeric & Comparable> {
    var start: T
    var end: T
    var step: T
}

// Treated as PickerRange<Double>
let a = PickerRange(start: 1.0, end: 5.0, step: 1)

// Treated as PickerRange<Int>
let b = PickerRange(start: 1, end: 5, step: 1)

However, you have specialized length property, which includes / operator not supported by SignedNumeric. A workaround would consist in type-checking/force-casting to a type you have initialized your struct with:

struct PickerRange<T:SignedNumeric & Comparable> {
    var start: T
    var end: T
    var step: T

    var length: T {
        if T.self is Double.Type {
            return (max(start, end) as! Double) - ((min(start, end) as! Double) / (step as! Double)) as! T
        } else if T.self is Int.Type {
            return (max(start, end) as! Int) - ((min(start, end) as! Int) / (step as! Int)) as! T
        } else {
            return 0
        }
    }
}

let a = PickerRange(start: 1.0, end: 5.0, step: 1)
let b = PickerRange(start: 1, end: 10, step: 1)

print(a.length)
print(b.length)


问:
looping the array of json object in reactjs
I am new in reactjs. I have problem while showing the result.Here is my code:

```<code>constructor (props) {
      super(props);
       this.state = {
         selectValue: '',
         yearsValue:'',
         months:''
       }
     this.setDataGroup = this.setDataGroup.bind(this);
   }

setDataGroup(e){
    var selectedType = e.target.value;
    if(selectedType == "quertly"){
       var quertlyData = [{
        data:"Jan-March",
        value:"1"
      },
      {
        data:"Apr-Jun",
        value:"2"
      },
      {
        data:"Jul-Sept",
        value:"3"
      },
      {
        data:"Oct-Dec",
        value:"4"
      }];
       this.setState({yearsValue:quertlyData});
</code>```

I am showing the data like:

```<code> render() {
 const data = JSON.stringify(this.state.yearsValue) || []
                  <div>
    {data.map((data, index) => {data})}
  </div>
}
</code>```

My json looks like:

[{"data":"Jan-March","value":"1"},{"data":"Apr-Jun","value":"2"},{"data":"Jul-Sept","value":"3"},{"data":"Oct-Dec","value":"4"}]

Getting error .map is not function

答:
yearsValue is a string and therefore using JSON.stringify won't help you.

Also, render method must return something:

```<code>constructor (props) {
  super(props);
  this.state = {
    selectValue: '',
    yearsValue: [],
    months:''
  }

  this.setDataGroup = this.setDataGroup.bind(this);
}
...
render() {
  const { yearsValue } = this.state

  return (
    <div>
      {yearsValue.map((item, index) =>
        <div key={index}>{item.data}:{item.value}</div>
      )}
    </div>
  }
}
</code>```

Body:
I am new in reactjs. I have problem while showing the result.Here is my code:

constructor (props) {
      super(props);
       this.state = {
         selectValue: '',
         yearsValue:'',
         months:''
       }
     this.setDataGroup = this.setDataGroup.bind(this);
   }

setDataGroup(e){
    var selectedType = e.target.value;
    if(selectedType == "quertly"){
       var quertlyData = [{
        data:"Jan-March",
        value:"1"
      },
      {
        data:"Apr-Jun",
        value:"2"
      },
      {
        data:"Jul-Sept",
        value:"3"
      },
      {
        data:"Oct-Dec",
        value:"4"
      }];
       this.setState({yearsValue:quertlyData});

I am showing the data like:

 render() {
 const data = JSON.stringify(this.state.yearsValue) || []

    {data.map((data, index) => {data})}

}

My json looks like:

[{"data":"Jan-March","value":"1"},{"data":"Apr-Jun","value":"2"},{"data":"Jul-Sept","value":"3"},{"data":"Oct-Dec","value":"4"}]

Getting error .map is not function

Body:
yearsValue is a string and therefore using JSON.stringify won't help you.

Also, render method must return something:

constructor (props) {
  super(props);
  this.state = {
    selectValue: '',
    yearsValue: [],
    months:''
  }

  this.setDataGroup = this.setDataGroup.bind(this);
}
...
render() {
  const { yearsValue } = this.state

  return (
    <div>
      {yearsValue.map((item, index) =>
        <div key={index}>{item.data}:{item.value}</div>
      )}
    </div>
  }
}


问:
git: what does "o" mean in front of a branch name?
when I type git branch -avv I get something like

```<code>git branch -avv
  some/branchname       9ff9335af Some nice description
o release/v3.0
  some/branchname       a12b3hg1f Some description
* release/v3.0          813f74adc Some detailed description
...
</code>```

So release/v3.0 occurs twice and one prefixed with o. I didn't find anything in the documentation - what does this mean?

Update:

My abbreviated listing above is misleading - should be something like

```<code>git branch -avv
  some/branchname       9ff9335af merged branch abc/def t
o release/v3.0
</code>```

.. where you could easily guess what went wrong.. (line break)

答:
This is not git standard behavior. I tracked the git branch command nine years back and neither then nor now was there anything other than ' ' and '*'.

My guess is that this comes from either the previous line or from some other tool that you have installed on top of git branch.

Body:
when I type git branch -avv I get something like

git branch -avv
  some/branchname       9ff9335af Some nice description
o release/v3.0
  some/branchname       a12b3hg1f Some description
* release/v3.0          813f74adc Some detailed description
...

So release/v3.0 occurs twice and one prefixed with o. I didn't find anything in the documentation - what does this mean?

Update:

My abbreviated listing above is misleading - should be something like

git branch -avv
  some/branchname       9ff9335af merged branch abc/def t
o release/v3.0

.. where you could easily guess what went wrong.. (line break)


问:
save data and file from form angularjs and laravel
i want save data from form AngularJS in database. I have form with fields. But I would like to additionally send the file with data. Data is sent without problems. But i dont know how send File with data. I must send two request? How can I send a file along with the data?

This is my input file.

```<code><div class="pure-control-group">
                    <label for="code">UID</label>
                    <input id="uid" ng-model="form.uid" type="text" placeholder="UID" required="" disabled="">
                </div>

            <div class="pure-control-group">
                <label for="code">Code</label>
                <input id="code" ng-model="form.code" type="text" placeholder="Code" required="">
            </div>

            <div class="pure-control-group">
                <label for="name">Name</label>
                <input id="name" ng-model="form.name" type="text" placeholder="Name" required="" autocomplete="new-password">
            </div>

            <div class="pure-control-group">
                <label for="town">Town</label>
                <input id="town" ng-model="form.town" type="text" placeholder="Town" required="" autocomplete="new-password">
            </div>

            <div class="pure-control-group">
                <label for="date_start">Date Start</label>
                <input id="date_start" ng-model="form.date_start" type="date" placeholder="Password" autocomplete="new-password">
            </div>

            <div class="pure-control-group">
                <label for="date_stop">Date Stop</label>
                <input id="date_stop" ng-model="form.date_stop" type="date" placeholder="Password" autocomplete="new-password">
            </div>

            <div class="pure-control-group">
                <label>Status</label>
                <select class="form-control select" ng-model="form.status">
                    <option ng-repeat="status in statuses" value="{{status.name}}">{{status.name}}</option>
                </select>
            </div>
<div class="pure-control-group">
                        <label for="logo">Logo</label>
                        <input id="logo" type="file" ng-model="form.logo" name="file" accept="image/*" ngf-max-size="5MB" required>
                    </div>
</code>```

Angularjs controller:

```<code>$scope.submit = function (data)
                {
                        $fetch.post('api/admin/places', data)
                                .then(function (response)
                                {
                                    if (response.success)
                                    {
                                        Notification.success(response.message);
                                        $state.go('app.admin.places');
                                    } else
                                    {
                                        var msg = response && response.message ? response.message : 'There was an error in data update. Please contact your administrator';
                                        Notification.error(msg);
                                    }
                                })
                                .finally(function () {
                                    $loader.hide();
                                });
                    }
                };
</code>```

Laravel Controller:

```<code>public function add(Request $request) {

        try {

            Place::create([
                'uid' => Uuid::generate()->string,
                'code' => $request->input('code'),
                'name' => $request->input('name'),
                'town' => $request->input('town'),
                'date_start' => $request->input('date_start'),
                'date_stop' => $request->input('date_stop'),
                'status' => $request->input('status'),
                'sort' => 1,
                'position' => $request->input('position'),
            ]);
        } catch (\Exception $ex) {

        }
        return ['success' => true, 'message' => 'Place was successfully added'];
    }
</code>```

So, How can I save the file along with the data?

答:
Use the below code to uplaod file to server via $post:-

```<code>myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);

        var info = {
            "text":"additional info"
        };
        fd.append('data', angular.toJson(info));

        $http.post(uploadUrl, fd, {
             transformRequest: angular.identity,
             headers: {'Content-Type': undefined}
        })

        .success(function(){
        })

        .error(function(){
        });
    }
}]);
</code>```

Hope you know the rest part.

Body:
i want save data from form AngularJS in database. I have form with fields. But I would like to additionally send the file with data. Data is sent without problems. But i dont know how send File with data. I must send two request? How can I send a file along with the data?

This is my input file.

                    UID
                    <input id="uid" ng-model="form.uid" type="text" placeholder="UID" required="" disabled="">

                Code
                <input id="code" ng-model="form.code" type="text" placeholder="Code" required="">

                Name
                <input id="name" ng-model="form.name" type="text" placeholder="Name" required="" autocomplete="new-password">

                Town
                <input id="town" ng-model="form.town" type="text" placeholder="Town" required="" autocomplete="new-password">

                Date Start
                <input id="date_start" ng-model="form.date_start" type="date" placeholder="Password" autocomplete="new-password">

                Date Stop
                <input id="date_stop" ng-model="form.date_stop" type="date" placeholder="Password" autocomplete="new-password">

                Status
                <select class="form-control select" ng-model="form.status">
                    <option ng-repeat="status in statuses" value="{{status.name}}">{{status.name}}</option>
                </select>

                        Logo
                        <input id="logo" type="file" ng-model="form.logo" name="file" accept="image/*" ngf-max-size="5MB" required>

Angularjs controller:

$scope.submit = function (data)
                {
                        $fetch.post('api/admin/places', data)
                                .then(function (response)
                                {
                                    if (response.success)
                                    {
                                        Notification.success(response.message);
                                        $state.go('app.admin.places');
                                    } else
                                    {
                                        var msg = response && response.message ? response.message : 'There was an error in data update. Please contact your administrator';
                                        Notification.error(msg);
                                    }
                                })
                                .finally(function () {
                                    $loader.hide();
                                });
                    }
                };

Laravel Controller:

public function add(Request $request) {

        try {

            Place::create([
                'uid' => Uuid::generate()->string,
                'code' => $request->input('code'),
                'name' => $request->input('name'),
                'town' => $request->input('town'),
                'date_start' => $request->input('date_start'),
                'date_stop' => $request->input('date_stop'),
                'status' => $request->input('status'),
                'sort' => 1,
                'position' => $request->input('position'),
            ]);
        } catch (\Exception $ex) {

        }
        return ['success' => true, 'message' => 'Place was successfully added'];
    }

So, How can I save the file along with the data?

Body:
Use the below code to uplaod file to server via $post:-

myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);

        var info = {
            "text":"additional info"
        };
        fd.append('data', angular.toJson(info));

        $http.post(uploadUrl, fd, {
             transformRequest: angular.identity,
             headers: {'Content-Type': undefined}
        })

        .success(function(){
        })

        .error(function(){
        });
    }
}]);

Hope you know the rest part.


问:
sqlcmd script with spaces in filename
I have a simple SQLCMD script that includes some lines like this:

```<code>/* Load data into Exampletable */
BULK INSERT dbo.Example
    /* NOTE: I've tried single AND double quotes here. */
    FROM "C:\Example Filepath\test.csv"
    WITH
    (
            /* skip the first row containing column names */
            FIRSTROW = 2,
            /* specify how fields are separated */
            FIELDTERMINATOR = '|',
            /* specify how lines end */
            ROWTERMINATOR = '\n'
    )
</code>```

When I run it on the command line, I get an error like this:

Sqlcmd: 'C:\Example': Invalid filename.

I think that having a space in the path is causing the path to be cut off, but I can't figure out a syntax that works. Does anybody have any experience with this?

答:
Surround the path with single quotes like:</p>

```<code>'C:\Example Filepath\test.csv'
</code>```

Title: sqlcmd script with spaces in filename

Body:
I have a simple SQLCMD script that includes some lines like this:

/* Load data into Exampletable */
BULK INSERT dbo.Example
    /* NOTE: I've tried single AND double quotes here. */
    FROM "C:\Example Filepath\test.csv"
    WITH
    (
            /* skip the first row containing column names */
            FIRSTROW = 2,
            /* specify how fields are separated */
            FIELDTERMINATOR = '|',
            /* specify how lines end */
            ROWTERMINATOR = '\n'
    )

When I run it on the command line, I get an error like this:

Sqlcmd: 'C:\Example': Invalid filename.

I think that having a space in the path is causing the path to be cut off, but I can't figure out a syntax that works. Does anybody have any experience with this?

Body:
Surround the path with single quotes like:

'C:\Example Filepath\test.csv'


问:
object doesn't support property or method 'findIndex' IE11 javascript issue
I have an AngularJS application that is giving me some issues in Internet Explorer 11 - In my administration area I am getting console log errors that seem to correlate with some problems I have noticed in the page with filtering data when using Internet Explorer (version 11 specifically) however fine in Chrome/Firefox etc.

```<code>Object doesn't support property or method 'findIndex'
at Anonymous function (http://myapp.local/js/controllers/admin/UsersController.js:363:9)
</code>```

When I navigate to this line in the code this is the section in question :-

```<code>[363]   var indexInOriginalSet = $scope.originalSet.findIndex(function(u) {
[364]        return u.id == userId;
[365]   });
</code>```

What is the best solution to fix this IE problem with the findIndex?

答:
For those who are getting this error in their Angular (>=2) application on IE, if you create the app using angular cli, you would find the file polyfills.ts in src directory or whatever is the root directory of source files created by Angular cli, find and uncomment the following import statements in polyfills.ts:</p>

```<code>/** IE9, IE10 and IE11 requires all of the following polyfills. **/
// import 'core-js/es6/symbol';
// import 'core-js/es6/object';
// import 'core-js/es6/function';
// import 'core-js/es6/parse-int';
// import 'core-js/es6/parse-float';
// import 'core-js/es6/number';
// import 'core-js/es6/math';
// import 'core-js/es6/string';
// import 'core-js/es6/date';
// import 'core-js/es6/array';
// import 'core-js/es6/regexp';
// import 'core-js/es6/map';
// import 'core-js/es6/weak-map';
// import 'core-js/es6/set';
</code>```

Body:
I have an AngularJS application that is giving me some issues in Internet Explorer 11 - In my administration area I am getting console log errors that seem to correlate with some problems I have noticed in the page with filtering data when using Internet Explorer (version 11 specifically) however fine in Chrome/Firefox etc.

Object doesn't support property or method 'findIndex'
at Anonymous function (http://myapp.local/js/controllers/admin/UsersController.js:363:9)

When I navigate to this line in the code this is the section in question :-

[363]   var indexInOriginalSet = $scope.originalSet.findIndex(function(u) {
[364]        return u.id == userId;
[365]   });

What is the best solution to fix this IE problem with the findIndex?

Body:
For those who are getting this error in their Angular (>=2) application on IE, if you create the app using angular cli, you would find the file polyfills.ts in src directory or whatever is the root directory of source files created by Angular cli, find and uncomment the following import statements in polyfills.ts:

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
// import 'core-js/es6/symbol';
// import 'core-js/es6/object';
// import 'core-js/es6/function';
// import 'core-js/es6/parse-int';
// import 'core-js/es6/parse-float';
// import 'core-js/es6/number';
// import 'core-js/es6/math';
// import 'core-js/es6/string';
// import 'core-js/es6/date';
// import 'core-js/es6/array';
// import 'core-js/es6/regexp';
// import 'core-js/es6/map';
// import 'core-js/es6/weak-map';
// import 'core-js/es6/set';


问:
Insert new SQL row only if there is same value from other table
Currently I'm having,

Table1:

```<code>ID  |   DEVICEID    |  STATUS  |
--------------------------------
1   |   SN001       |  ENROLL  |
2   |   SN002       |  ENROLL  |
</code>```

Table2:

```<code>ID  |   DEVICEID    |  STATUS  |
--------------------------------
1   |   SN001       |  ENROLL  |
2   |   SN002       |  ENROLL  |
3   |   SN003       |  ENROLL  |
4   |   SN004       |  ENROLL  |
</code>```

There is a form to fill up in order to insert new DEVICEID and STATUS in Table1 using AJAX POST to PHP. Before update the SQL, how do I create a condition where Table1 only can be updated if only there is same DEVICEID filled up in form with DEVICEID in Table2 else it will return error and will not update the Table1.

Here's what I have:

```<code>"SELECT deviceid
FROM table1
INNER JOIN table2 ON table1.deviceid=table2.deviceid
INSERT INTO table1(deviceId,status)
VALUES('$deviceid', '$status')
WHERE deviceid = deviceid";                 <--- Not sure what I'm doing here, trying to compare
</code>```

答:
Solved by this:

```<code>INSERT INTO table1 (deviceid, status)
SELECT DISTINCT '$deviceid','$status'
FROM table2
WHERE deviceid='$deviceid' AND status='$status'
</code>```

Thanks to: Insert Into table If similar value exists in another existing table (not a foreign key)

And everyone who helped me. :)

Body:
Currently I'm having,

Table1:

ID  |   DEVICEID    |  STATUS  |
--------------------------------
1   |   SN001       |  ENROLL  |
2   |   SN002       |  ENROLL  |

Table2:

ID  |   DEVICEID    |  STATUS  |
--------------------------------
1   |   SN001       |  ENROLL  |
2   |   SN002       |  ENROLL  |
3   |   SN003       |  ENROLL  |
4   |   SN004       |  ENROLL  |

There is a form to fill up in order to insert new DEVICEID and STATUS in Table1 using AJAX POST to PHP. Before update the SQL, how do I create a condition where Table1 only can be updated if only there is same DEVICEID filled up in form with DEVICEID in Table2 else it will return error and will not update the Table1.

Here's what I have:

"SELECT deviceid
FROM table1
INNER JOIN table2 ON table1.deviceid=table2.deviceid
INSERT INTO table1(deviceId,status)
VALUES('$deviceid', '$status')
WHERE deviceid = deviceid";                 <--- Not sure what I'm doing here, trying to compare

Body:
Solved by this:

INSERT INTO table1 (deviceid, status)
SELECT DISTINCT '$deviceid','$status'
FROM table2
WHERE deviceid='$deviceid' AND status='$status'

Thanks to: Insert Into table If similar value exists in another existing table (not a foreign key)

And everyone who helped me. :)


问:
Change field depending of other in SonataAdminBundle
In a Symfony3 project, i have a SonataAdminBundle form like this :

```<code>  protected function configureFormFields(FormMapper $formMapper) {

        $formMapper->add('rentalTime', 'choice', array(
            'label' => 'Durée de location',
            'multiple' => false,
            'choices' => array(
                '3H' => '3',
                '24H' => '24',
            )
        ));
        $formMapper->add('rentalTimeType', 'choice', array(
            'label' => 'Type de durée de location',
            'multiple' => false,
            'choices' => array(
                'Heure(s)' => 'H',
                'Plage de jours' => 'R'
            )
        ));
    .
    .
    .
</code>```

When i change the value of rentalTime i want to change the value of rentaltimeType.
Example: If i select 24H in rentalTime field and automatically the rentalTimeType change for 'Plage de jours'.

I've read a lot of topic with the use of $subject but it's not exactly what i need.

change row color in sonata admin bundle dependent on a value of a field

Correct way to use FormEvents to customise fields in SonataAdmin

Sonata User Admin - Custom field dependency

So is it possible to do what i need ?

答:
You can customize the form specific to the data that was submitted by the user.

Dynamic Generation for Submitted Forms

Body:
In a Symfony3 project, i have a SonataAdminBundle form like this :

  protected function configureFormFields(FormMapper $formMapper) {

        $formMapper->add('rentalTime', 'choice', array(
            'label' => 'Durée de location',
            'multiple' => false,
            'choices' => array(
                '3H' => '3',
                '24H' => '24',
            )
        ));
        $formMapper->add('rentalTimeType', 'choice', array(
            'label' => 'Type de durée de location',
            'multiple' => false,
            'choices' => array(
                'Heure(s)' => 'H',
                'Plage de jours' => 'R'
            )
        ));
    .
    .
    .

When i change the value of rentalTime i want to change the value of rentaltimeType.
Example: If i select 24H in rentalTime field and automatically the rentalTimeType change for 'Plage de jours'.

I've read a lot of topic with the use of $subject but it's not exactly what i need.

change row color in sonata admin bundle dependent on a value of a field

Correct way to use FormEvents to customise fields in SonataAdmin

Sonata User Admin - Custom field dependency

So is it possible to do what i need ?