问:
Selenium 3.4.0 with Firefox 55
yesterday my Firefox browser updated to 55. Since then my code wont work any more. Im using Selenium 3.4  geckodriver 18.0 and Firefox 55. In chrome it works. i got the following message:

```<code>> 1503585931231 geckodriver INFO    geckodriver 0.18.0
> 1503585931265 geckodriver INFO    Listening on 127.0.0.1:31895
> 1503585932805 geckodriver::marionette INFO    Starting browser C:\Program
> Files\Mozilla Firefox\firefox.exe with args ["-marionette"]
> 1503585936703 Marionette  INFO    Enabled via --marionette Unable to read
> VR Path Registry from
> C:\Users\Ja\AppData\Local\openvr\openvrpaths.vrpath [GPU 2512]
> WARNING: pipe error: 109: file
> c:/builds/moz2_slave/m-rel-w64-00000000000000000000/build/src/ipc/chromium/src/chrome/common/ipc_channel_win.cc,
> line 346 1503585942553    Marionette  INFO    Listening on port 49243
> 1503585943132 Marionette  INFO    Listening on port 49243
> 1503585943228 Marionette  DEBUG   loaded listener.js Aug 24, 2017 4:45:43
> PM org.openqa.selenium.remote.ProtocolHandshake createSession
> INFORMATION: Detected dialect: W3C
> 1503585944268 Marionette  DEBUG   Received DOM event "beforeunload" for
> "about:blank" 1503585945049   Marionette  DEBUG   Received DOM event
> "pagehide" for "about:blank" 1503585945051    Marionette  DEBUG   Received
> DOM event "unload" for "about:blank"
> 1503585945102 Marionette  DEBUG   Received DOM event "DOMContentLoaded"
> for "http://www.phptravels.net/"
> 1503585945208 Marionette  DEBUG   Received DOM event "pageshow" for
> "http://www.phptravels.net/" 1503585970177    Marionette  INFO    New
> connections will no longer be accepted Aug 24, 2017 4:46:13 PM
> org.openqa.selenium.os.UnixProcess destroy SCHWERWIEGEND: Unable to
> kill process with PID 11736
</code>```

Has somebody the same problem and maybe a solution? or should I just downgrade Firefox?

Forget to say that iam working with Selenium WebDriver.

Thanks for answering.

答:
Katalon is a very good choice. If you want more alternatives, as said in Top 3 Selenium IDE alternatives for Firefox & Chrome, look into those:

Katalon Recorder with Firefox addon or Chrome addon

Protractor, you can use protractor recorder npm package

Robot Framework (only supporting Chrome addon by now)

Title: Selenium 3.4.0 with Firefox 55

Body:
yesterday my Firefox browser updated to 55. Since then my code wont work any more. Im using Selenium 3.4  geckodriver 18.0 and Firefox 55. In chrome it works. i got the following message:

> 1503585931231 geckodriver INFO    geckodriver 0.18.0
> 1503585931265 geckodriver INFO    Listening on 127.0.0.1:31895
> 1503585932805 geckodriver::marionette INFO    Starting browser C:\Program
> Files\Mozilla Firefox\firefox.exe with args ["-marionette"]
> 1503585936703 Marionette  INFO    Enabled via --marionette Unable to read
> VR Path Registry from
> C:\Users\Ja\AppData\Local\openvr\openvrpaths.vrpath [GPU 2512]
> WARNING: pipe error: 109: file
> c:/builds/moz2_slave/m-rel-w64-00000000000000000000/build/src/ipc/chromium/src/chrome/common/ipc_channel_win.cc,
> line 346 1503585942553    Marionette  INFO    Listening on port 49243
> 1503585943132 Marionette  INFO    Listening on port 49243
> 1503585943228 Marionette  DEBUG   loaded listener.js Aug 24, 2017 4:45:43
> PM org.openqa.selenium.remote.ProtocolHandshake createSession
> INFORMATION: Detected dialect: W3C
> 1503585944268 Marionette  DEBUG   Received DOM event "beforeunload" for
> "about:blank" 1503585945049   Marionette  DEBUG   Received DOM event
> "pagehide" for "about:blank" 1503585945051    Marionette  DEBUG   Received
> DOM event "unload" for "about:blank"
> 1503585945102 Marionette  DEBUG   Received DOM event "DOMContentLoaded"
> for "http://www.phptravels.net/"
> 1503585945208 Marionette  DEBUG   Received DOM event "pageshow" for
> "http://www.phptravels.net/" 1503585970177    Marionette  INFO    New
> connections will no longer be accepted Aug 24, 2017 4:46:13 PM
> org.openqa.selenium.os.UnixProcess destroy SCHWERWIEGEND: Unable to
> kill process with PID 11736

Has somebody the same problem and maybe a solution? or should I just downgrade Firefox?

Forget to say that iam working with Selenium WebDriver.

Thanks for answering.


来源: stackexchange

问:
How to find minimum of BigDecimal field in collection with java streams?
I want to use java streams to iterate a list and find the BigDecimal minimum price. The following illustrates, but does not work (because min() cannot accept BigDecimal.

```<code>class Product {
    public BigDecimal price;
}

List<Product> products;
products.stream().min((Product) p -> p.price);
</code>```

答:
You don't need a stream to find the minimum. Use Collections.min:

```<code>Collections.min(products, Comparator.comparing(p -> p.price));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to use java streams to iterate a list and find the BigDecimal minimum price. The following illustrates, but does not work (because min() cannot accept BigDecimal.

class Product {
    public BigDecimal price;
}

List<Product> products;
products.stream().min((Product) p -> p.price);

Body:
You don't need a stream to find the minimum. Use Collections.min:

Collections.min(products, Comparator.comparing(p -> p.price));


问:
ReyclerView isn't working
I'm trying to show list of my model on recyclerview. but for some reason it doesnt show anything. I'm getting my list items from FirebaseDatabase and save all the data on "videoList". Then i want to presents the data that i have received, but it doesnt show anything.

Please tell me what i'm doing wrong.

```<code>  public class MyPlayListFragment extends Fragment {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    refToVideos.getReference(Params.VIDEOS).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    adapter = new VideoViewAdapter(getContext(),videosList);
    rvVideos.setLayoutManager(new LinearLayoutManager(getContext()));
    rvVideos.setAdapter(adapter);

}

public class VideoViewAdapter extends RecyclerView.Adapter<VideoViewHolder>{
  private LayoutInflater inflater;
  private Context context;
  private ArrayList<Video> data;

  public VideoViewAdapter( Context context, ArrayList<Video> data) {
      this.context = context;
      this.inflater = LayoutInflater.from(context);
      this.data = data;
  }

  @Override
  public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
      View v = inflater.inflate(R.layout.video_item,parent,false);
      return new VideoViewHolder(v);
  }

  @Override
  public void onBindViewHolder(VideoViewHolder holder, int position) {
      Video video = data.get(position);
      holder.tvTitleVideo.setText(video.getVideoName());
      holder.tvLikes.setText(String.valueOf(video.getLikes()));
      holder.tvViews.setText(String.valueOf(video.getViews()));
      Uri uri = Uri.parse(video.getVideoURL());
      holder.videoViewUser.setVideoURI(uri);
      holder.videoViewUser.start();

  }

  @Override
  public int getItemCount() {
      return 0;
  }
}

public  class VideoViewHolder extends RecyclerView.ViewHolder{
    private TextView tvTitleVideo,tvLikes,tvViews;
    private VideoView videoViewUser;

    public VideoViewHolder(View itemView) {
        super(itemView);
        tvTitleVideo = (TextView) itemView.findViewById(R.id.videoTitle);
        tvLikes = (TextView)itemView.findViewById(R.id.tvLikes);
        tvViews = (TextView)itemView.findViewById(R.id.tvViews);
        videoViewUser = (VideoView)itemView.findViewById(R.id.videoViewUser);

      }
    }

 }
</code>```

答:
You should return the size of your data ArrayList in getItemCount()

Use this:

```<code>@Override
public int getItemCount() {
    return data.size();
}
</code>```

Instead of this:

```<code>@Override
public int getItemCount() {
    return 0;
}
</code>```

Title: ReyclerView isn't working

Body:
I'm trying to show list of my model on recyclerview. but for some reason it doesnt show anything. I'm getting my list items from FirebaseDatabase and save all the data on "videoList". Then i want to presents the data that i have received, but it doesnt show anything.

Please tell me what i'm doing wrong.

  public class MyPlayListFragment extends Fragment {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    refToVideos.getReference(Params.VIDEOS).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    adapter = new VideoViewAdapter(getContext(),videosList);
    rvVideos.setLayoutManager(new LinearLayoutManager(getContext()));
    rvVideos.setAdapter(adapter);

}

public class VideoViewAdapter extends RecyclerView.Adapter<VideoViewHolder>{
  private LayoutInflater inflater;
  private Context context;
  private ArrayList<Video> data;

  public VideoViewAdapter( Context context, ArrayList<Video> data) {
      this.context = context;
      this.inflater = LayoutInflater.from(context);
      this.data = data;
  }

  @Override
  public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
      View v = inflater.inflate(R.layout.video_item,parent,false);
      return new VideoViewHolder(v);
  }

  @Override
  public void onBindViewHolder(VideoViewHolder holder, int position) {
      Video video = data.get(position);
      holder.tvTitleVideo.setText(video.getVideoName());
      holder.tvLikes.setText(String.valueOf(video.getLikes()));
      holder.tvViews.setText(String.valueOf(video.getViews()));
      Uri uri = Uri.parse(video.getVideoURL());
      holder.videoViewUser.setVideoURI(uri);
      holder.videoViewUser.start();

  }

  @Override
  public int getItemCount() {
      return 0;
  }
}

public  class VideoViewHolder extends RecyclerView.ViewHolder{
    private TextView tvTitleVideo,tvLikes,tvViews;
    private VideoView videoViewUser;

    public VideoViewHolder(View itemView) {
        super(itemView);
        tvTitleVideo = (TextView) itemView.findViewById(R.id.videoTitle);
        tvLikes = (TextView)itemView.findViewById(R.id.tvLikes);
        tvViews = (TextView)itemView.findViewById(R.id.tvViews);
        videoViewUser = (VideoView)itemView.findViewById(R.id.videoViewUser);

      }
    }

 }

Body:
You should return the size of your data ArrayList in getItemCount()

Use this:

@Override
public int getItemCount() {
    return data.size();
}

Instead of this:

@Override
public int getItemCount() {
    return 0;
}


问:
How to use Application Helpers in Ruby on Rails
I'm attempting to post a random testimonial on each page of a site.

I started off by using an application helper like this:

```<code>module ApplicationHelper

  def random_testimonial
    @random_testimonial = Testimonial.find(:first, :offset => rand(Testimonial.count))
  end

end
</code>```

In my view I can reference the method but it's being called on each reference, which makes sense.

I'd like this to be called once on each page view exposing a Testimonial object I can use within the view.

What should I be looking for to do this?

答:
If I understand you correctly, you want a method that returns the same object every time it is referenced in one request/response cycle. If this is true, you can achieve it with a minor change to your helper:

```<code> def random_testimonial
    @random_testimonial ||= Testimonial.find(:first, :offset => rand(Testimonial.count))
 end
</code>```

Notice the "||=" part. That's a Ruby idiom which says: assign a value to @random_testimonial, unless it already has a value.

Hope that answers your question.

OwnerDisplayName: Chris Stewart

Body:
I'm attempting to post a random testimonial on each page of a site.

I started off by using an application helper like this:

module ApplicationHelper

  def random_testimonial
    @random_testimonial = Testimonial.find(:first, :offset => rand(Testimonial.count))
  end

end

In my view I can reference the method but it's being called on each reference, which makes sense.

I'd like this to be called once on each page view exposing a Testimonial object I can use within the view.

What should I be looking for to do this?

Body:
If I understand you correctly, you want a method that returns the same object every time it is referenced in one request/response cycle. If this is true, you can achieve it with a minor change to your helper:

 def random_testimonial
    @random_testimonial ||= Testimonial.find(:first, :offset => rand(Testimonial.count))
 end

Notice the "||=" part. That's a Ruby idiom which says: assign a value to @random_testimonial, unless it already has a value.

Hope that answers your question.

OwnerDisplayName: Milan Novota

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Milan Novota


问:
Nuke viewer LUT settings while working on alpha channel
As per my knowledge, LUT is meant to be applied on color channels (RGB) since we are doing colorspace conversion. But Nuke's viewer LUT settings affect alpha channel too. I am aware that viewer LUT doesn't alter original pixel values but only displays them as per the LUT settings set, but shouldn't we turn off viewer LUT while working on alpha channel? Like for instance pulling a key or doing roto ?

Shouldn't we be viewing alpha in linear color space? Am I missing something here?

答:
You're right, NUKE Viewer's LookUp Table doesn't change alpha at all but it affects it. You need to use Viewer's f/8 (multiplier) slider and y (gamma) slider for changing appearance of your alpha when you're keying. NUKE's working color space is LINEAR but default LUT settings for monitor, 8-bit and 16-bit files are superRGB corrected:

Read an article about NUKE colorspaces and color transformations: HERE.

To compensate sRGB gamma for getting linear working color space NUKE uses mirrored gamma:

You can change any default LUT settings or turn off alpha channel (or rgb, or any channel you want) for your convenience at any time.

Execute this code and then create new Viewer node with ctrl-i shortcut (cmd-i on a Mac):

```<code>import nuke

# to change Viewers' properties globally
nuke.knobDefault('Viewer.channels', 'rgb')
nuke.knobDefault('Viewer.viewerProcess', 'rec709')  # use rec709, for instance
</code>```

You'll get this:

Or simply execute the code for Viewer1, changing viewerProcess for None (linear color space):

```<code>nuke.toNode('Viewer1').knob('channels').setValue('alpha')
nuke.toNode('Viewer1').knob('viewerProcess').setValue('None')

# then add these 3 lines to menu.py file (they'll work after restart)

nuke.knobDefault("Root.monitorLut", "linear")  # monitor LUT
nuke.knobDefault("Root.int8Lut", "linear")     # 8-bit files LUT
nuke.knobDefault("Root.int16Lut", "linear")    # 16-bit files LUT
</code>```

Additionally, to physically transform you current LUT, you can use OpenColorIO LUT and 3D LUT nodes from Color Toolbar's menu.

And a few words about Pixel Analyzer panel:

Current, Min, Max, Average and Median operations in Pixel Analyzer panel are applied to any channels from dropdown menu. If you need only alpha value or only rgb values just choose it from the menu.

But. There's no mistake if you'll be using rgba mode. Check it. Apply Keyer node to the image and you'll see RGB values are the same with or without alpha (but only if rgba isn't premultiplied).

And it's sad but there still isn't access to API via Python for the Pixel Analyzer panel.

Body:
You're right, NUKE Viewer's LookUp Table doesn't change alpha at all but it affects it. You need to use Viewer's f/8 (multiplier) slider and y (gamma) slider for changing appearance of your alpha when you're keying. NUKE's working color space is LINEAR but default LUT settings for monitor, 8-bit and 16-bit files are superRGB corrected:

Read an article about NUKE colorspaces and color transformations: HERE.

To compensate sRGB gamma for getting linear working color space NUKE uses mirrored gamma:

You can change any default LUT settings or turn off alpha channel (or rgb, or any channel you want) for your convenience at any time.

Execute this code and then create new Viewer node with ctrl-i shortcut (cmd-i on a Mac):

import nuke

# to change Viewers' properties globally
nuke.knobDefault('Viewer.channels', 'rgb')
nuke.knobDefault('Viewer.viewerProcess', 'rec709')  # use rec709, for instance

You'll get this:

Or simply execute the code for Viewer1, changing viewerProcess for None (linear color space):

nuke.toNode('Viewer1').knob('channels').setValue('alpha')
nuke.toNode('Viewer1').knob('viewerProcess').setValue('None')

# then add these 3 lines to menu.py file (they'll work after restart)

nuke.knobDefault("Root.monitorLut", "linear")  # monitor LUT
nuke.knobDefault("Root.int8Lut", "linear")     # 8-bit files LUT
nuke.knobDefault("Root.int16Lut", "linear")    # 16-bit files LUT

Additionally, to physically transform you current LUT, you can use OpenColorIO LUT and 3D LUT nodes from Color Toolbar's menu.

And a few words about Pixel Analyzer panel:

Current, Min, Max, Average and Median operations in Pixel Analyzer panel are applied to any channels from dropdown menu. If you need only alpha value or only rgb values just choose it from the menu.

But. There's no mistake if you'll be using rgba mode. Check it. Apply Keyer node to the image and you'll see RGB values are the same with or without alpha (but only if rgba isn't premultiplied).

And it's sad but there still isn't access to API via Python for the Pixel Analyzer panel.


问:
Assigning instance of a derived class to a variable of base class
Hello I am newbie to C# and I'm trying to figure out the "implicit conversion" operation. I have a question about it:

```<code>    class Animal { }
    class Monkey : Animal { }

    Monkey m = new Monkey();
    Animal a = m;
    m.GetType()
    [Submission#165+Monkey]
    a.GetType()
    [Submission#165+Monkey]
</code>```

Monkey m2 = a;// this calls - Compiler Error CS0266.
  Cannot implicitly convert type 'Animal' to 'Monkey'. An explicit

conversion exists (are you missing a cast?)

I don't understand - if last code line throws an error CS0266, why does GetType method returns that "a" variable has a type "Monkey". If "a" variable is Animal how to find it out? By what method?

答:
GetType() is evaluated at runtime. The error you are getting is at compile time, which is before the program ever runs.

The compiler needs to ensure type safety with the information it has at compile time. Ensuring means making sure nothing can go wrong. Assigning an Animal to a Monkey is, in general, not safe, because a Tiger is also an animal, so you could theoretically end up assigning a tiger to a monkey typed variable.

You can tell the compiler that although the assignment isn't safe, you know what you are doing. You do this with an explicit cast:

```<code>Monkey m2 = (Monkey)a;
</code>```

Here you are telling the compiler; "Hey, I know this isn't generally safe, but trust me, I know a is a Monkey".

The compiler will accept your promise but won't trust you fully, so a type check will be performed at runtime just to make sure, and if your promise is a lie, you'll get a runtime error.

Body:
Hello I am newbie to C# and I'm trying to figure out the "implicit conversion" operation. I have a question about it:

    class Animal { }
    class Monkey : Animal { }

    Monkey m = new Monkey();
    Animal a = m;
    m.GetType()
    [Submission#165+Monkey]
    a.GetType()
    [Submission#165+Monkey]

Monkey m2 = a;// this calls - Compiler Error CS0266.
  Cannot implicitly convert type 'Animal' to 'Monkey'. An explicit

conversion exists (are you missing a cast?)

I don't understand - if last code line throws an error CS0266, why does GetType method returns that "a" variable has a type "Monkey". If "a" variable is Animal how to find it out? By what method?

Body:
GetType() is evaluated at runtime. The error you are getting is at compile time, which is before the program ever runs.

The compiler needs to ensure type safety with the information it has at compile time. Ensuring means making sure nothing can go wrong. Assigning an Animal to a Monkey is, in general, not safe, because a Tiger is also an animal, so you could theoretically end up assigning a tiger to a monkey typed variable.

You can tell the compiler that although the assignment isn't safe, you know what you are doing. You do this with an explicit cast:

Monkey m2 = (Monkey)a;

Here you are telling the compiler; "Hey, I know this isn't generally safe, but trust me, I know a is a Monkey".

The compiler will accept your promise but won't trust you fully, so a type check will be performed at runtime just to make sure, and if your promise is a lie, you'll get a runtime error.


答:
Try this</p>

```<code>@Override
  public int getItemCount() {
      return data.size();
  }
</code>```

Title: ReyclerView isn't working

Body:
Try this

@Override
  public int getItemCount() {
      return data.size();
  }


问:
Python - Use %s in value of config file
I use a config file (type .ini) to save my SQL queries, then i get  a query by its key. All work fine, until creating a query with parameters, example :

```<code>;the ini file

product_by_cat = select * from products where cat =%s
</code>```

I use :

```<code>config = configparser.ConfigParser()
args= ('cat1')
config.read(path_to_ini_file)
query= config.get(section_where_are_stored_thequeries,key_of_the_query)
complete_query= query%args
</code>```

I get the error :

TypeError: not all arguments converted during string formatting

So it try to format the string at retrieving the value from the ini file.
Any proposition of my problem.

答:
You can use format function like this

ini file

```<code>  product_by_cat = select * from products where cat ={}
</code>```

python:

```<code> complete_query= query.format(args)
</code>```

Title: Python - Use %s in value of config file

Body:
I use a config file (type .ini) to save my SQL queries, then i get  a query by its key. All work fine, until creating a query with parameters, example :

;the ini file

product_by_cat = select * from products where cat =%s

I use :

config = configparser.ConfigParser()
args= ('cat1')
config.read(path_to_ini_file)
query= config.get(section_where_are_stored_thequeries,key_of_the_query)
complete_query= query%args

I get the error :

TypeError: not all arguments converted during string formatting

So it try to format the string at retrieving the value from the ini file.
Any proposition of my problem.

Body:
You can use format function like this

ini file

  product_by_cat = select * from products where cat ={}

python:

 complete_query= query.format(args)


问:
Make image fill whole container of stacklayout

Hi I have this Xamarin Forms app where I have the following layout:

```<code> <ContentPage Title="Live" Icon="tv_show-32.png">
        <ScrollView>
            <Grid Margin="10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <StackLayout Grid.Row="0" Grid.Column="0" Spacing="50,20,50,30">
                    <Image Source="http://kanal10.se/images/logga/kanal10.png" HorizontalOptions="FillAndExpand"></Image>
                </StackLayout>

                <StackLayout Grid.Column="0" Grid.Row="1" Style="{StaticResource StackBG}">
                    <Label Text="Sverige/Sweden"></Label>
                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="Fill"></Image>
                    <Button x:Name="Sweden" Text="Watch Live" Clicked="Sweden_OnClicked" HorizontalOptions="FillAndExpand" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
                <StackLayout Grid.Column="0" Grid.Row="2" Style="{StaticResource StackBG}">
                    <Label Text="Norge/Norway"></Label>
                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="FillAndExpand"></Image>
                    <Button x:Name="Norway" Text="Watch Live" Clicked="Norway_OnClicked" HorizontalOptions="FillAndExpand" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
                <StackLayout Grid.Column="0" Grid.Row="3" Style="{StaticResource StackBG}">
                    <Label Text="Asien/Asia"></Label>
                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="FillAndExpand"></Image>
                    <Button x:Name="Asia" Text="Watch Live" Clicked="Asia_OnClicked" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
            </Grid>
        </ScrollView>
    </ContentPage>
</code>```

The problem is that I can't get the image called tvbild.png, to fill the whole  container in the iOS app.

I would like the image to have the same width size as the button (see attached image).

How can I accomplish this?

Thanks for help!

Peter

答:
Hi and thanks for answer,

Well what I want is to fill the whole conatiners width for both the button and the image.

Peter

Body:
Hi I have this Xamarin Forms app where I have the following layout:

 <ContentPage Title="Live" Icon="tv_show-32.png">
        <ScrollView>
            <Grid Margin="10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <StackLayout Grid.Row="0" Grid.Column="0" Spacing="50,20,50,30">
                    <Image Source="http://kanal10.se/images/logga/kanal10.png" HorizontalOptions="FillAndExpand"></Image>
                </StackLayout>

                <StackLayout Grid.Column="0" Grid.Row="1" Style="{StaticResource StackBG}">

                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="Fill"></Image>
                    <Button x:Name="Sweden" Text="Watch Live" Clicked="Sweden_OnClicked" HorizontalOptions="FillAndExpand" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
                <StackLayout Grid.Column="0" Grid.Row="2" Style="{StaticResource StackBG}">

                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="FillAndExpand"></Image>
                    <Button x:Name="Norway" Text="Watch Live" Clicked="Norway_OnClicked" HorizontalOptions="FillAndExpand" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
                <StackLayout Grid.Column="0" Grid.Row="3" Style="{StaticResource StackBG}">

                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="FillAndExpand"></Image>
                    <Button x:Name="Asia" Text="Watch Live" Clicked="Asia_OnClicked" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
            </Grid>
        </ScrollView>
    </ContentPage>

The problem is that I can't get the image called tvbild.png, to fill the whole  container in the iOS app.

I would like the image to have the same width size as the button (see attached image).

How can I accomplish this?

Thanks for help!

Peter


问:
Stopping execution in refactored php code?
I have just refactored a php page to make it slightly easier to extend and maintain in the future and gotten stuck on quite a simple problem.

I have broken one method up into 3.

largemethod() has become something like this:

```<code>nowsmallmethod(){
  doSomeChecks();
  assignProduct();
  giveFeedbacktoUser();
}
</code>```

This is all good and well, the problem I am having is with doSomeChecks();

```<code>doSomeChecks(){
 if(something that shouldnt be true is true){
    return Controller->redirectBk();
 }
}
</code>```

The crux of the problem is that Controller-redirectBk first redirects when nowsmallmethod() has been completed. This means that the user is assigned a product even if a test fails. I am using a php framework called Silverstripe so I cant really change the behavior of Controller->redirectBk(). If I didnt have the checks in their own method then everything would work fine because the "return Controller->redirectBk();" would stop execution and redirect back. Whats the best way to stop execution in nowsmallmethod() when a test fails? I realise i could return a status code for an error and then stop execution but it seems an ugly way. Is there not a more elegant way? Another option would be if i could return something like this in doSomeChecks(), "return (return $controller->redirectBk())" but this is not valid php syntax and not particularly easy to read. Any help would be hugely appreciated.

Enjoy your weekend!
Cheers
Nick

答:
```<code>nowsmallmethod() {
  if (doSomeChecks()) {
    assignProduct();
    giveFeedbacktoUser();
  }
}
</code>```

And doSomeChecks either returns true or false, based on whether the redirect will happen or not.

Alternatively, you could die or throw, but I assume a normal condition is more suitable in your case.

Body:
I have just refactored a php page to make it slightly easier to extend and maintain in the future and gotten stuck on quite a simple problem.

I have broken one method up into 3.

largemethod() has become something like this:

nowsmallmethod(){
  doSomeChecks();
  assignProduct();
  giveFeedbacktoUser();
}

This is all good and well, the problem I am having is with doSomeChecks();

doSomeChecks(){
 if(something that shouldnt be true is true){
    return Controller->redirectBk();
 }
}

The crux of the problem is that Controller-redirectBk first redirects when nowsmallmethod() has been completed. This means that the user is assigned a product even if a test fails. I am using a php framework called Silverstripe so I cant really change the behavior of Controller->redirectBk(). If I didnt have the checks in their own method then everything would work fine because the "return Controller->redirectBk();" would stop execution and redirect back. Whats the best way to stop execution in nowsmallmethod() when a test fails? I realise i could return a status code for an error and then stop execution but it seems an ugly way. Is there not a more elegant way? Another option would be if i could return something like this in doSomeChecks(), "return (return $controller->redirectBk())" but this is not valid php syntax and not particularly easy to read. Any help would be hugely appreciated.

Enjoy your weekend!
Cheers
Nick

Body:
nowsmallmethod() {
  if (doSomeChecks()) {
    assignProduct();
    giveFeedbacktoUser();
  }
}

And doSomeChecks either returns true or false, based on whether the redirect will happen or not.

Alternatively, you could die or throw, but I assume a normal condition is more suitable in your case.


问:
Get elements to align
I'm currently working on some black boards on my website and sometimes the content isn't the same size in each black board.

so what I've currently got is as following:

Achieved this by using the following code:

```<code>var biggestHeight = 0;
$('.board .content').each(function(){
    if(biggestHeight === 0) biggestHeight = $(this).height();
    if(biggestHeight < $(this).height()) bigghestHeight = $(this).height();
});
biggestHeight = biggestHeight + 15;
$('.board .content').css({
    "height" : biggestHeight + "px",
});
</code>```

I want the boards to be like this: but I want the boards to be different sizes depending on the content size, however I want the boards to be aligned at the bottom behind the grass like the first picture.

Simple example to reproduce the problem (Not exactly reproduced):

.board{
  display: inline-block;
  background: gray;
  width: 30%;
  float: left;
  margin-left: 5px;
}
#boards-container{
  position: relative;
  width: 400px;
}
#boards-container .boards{
  position: absolute
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="boards-container">
  <div class="boards">
      <div class="board">
        <p>1st Event</p>
        <p>2nd Event</p>
        <p>3rd Event 3rd Event 3rd Event 3rd Event 3rd Event</p>
      </div>
      <div class="board">
        (This should align at bottom)
        <p>1st News</p>
      </div>
      <div class="board">
        (This should align at bottom)
        <p>1st Gallery</p>
        <p>2nd Gallery</p>
        <p>3rd Gallery</p>
      </div>
  </div>
</div></code>```

NEED ANSWER TO WORK IN IE9+ aswell

答:
To align you can use flex with flex-end to align at the bottom of the container. More about flex align

.boards {
  display: flex;
  align-items: flex-end;
}

.board {
  display: inline-block;
  background: gray;
  width: 30%;
  float: left;
  margin-left: 5px;
}

#boards-container {
  position: relative;
  width: 400px;
}

#boards-container .boards {
  position: absolute
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="boards-container">
  <div class="boards">
    <div class="board">
      <p>1st Event</p>
      <p>2nd Event</p>
      <p>3rd Event 3rd Event 3rd Event 3rd Event 3rd Event</p>
    </div>
    <div class="board">
      (This should align at bottom)
      <p>1st News</p>
    </div>
    <div class="board">
      (This should align at bottom)
      <p>1st Gallery</p>
      <p>2nd Gallery</p>
      <p>3rd Gallery</p>
    </div>
  </div>
</div></code>```

Title: Get elements to align

Body:
I'm currently working on some black boards on my website and sometimes the content isn't the same size in each black board.

so what I've currently got is as following:

Achieved this by using the following code:

var biggestHeight = 0;
$('.board .content').each(function(){
    if(biggestHeight === 0) biggestHeight = $(this).height();
    if(biggestHeight < $(this).height()) bigghestHeight = $(this).height();
});
biggestHeight = biggestHeight + 15;
$('.board .content').css({
    "height" : biggestHeight + "px",
});

I want the boards to be like this: but I want the boards to be different sizes depending on the content size, however I want the boards to be aligned at the bottom behind the grass like the first picture.

Simple example to reproduce the problem (Not exactly reproduced):

.board{
  display: inline-block;
  background: gray;
  width: 30%;
  float: left;
  margin-left: 5px;
}
#boards-container{
  position: relative;
  width: 400px;
}
#boards-container .boards{
  position: absolute
}

1st Event

2nd Event

3rd Event 3rd Event 3rd Event 3rd Event 3rd Event

        (This should align at bottom)

1st News

        (This should align at bottom)

1st Gallery

2nd Gallery

3rd Gallery

NEED ANSWER TO WORK IN IE9+ aswell

Body:
To align you can use flex with flex-end to align at the bottom of the container. More about flex align

.boards {
  display: flex;
  align-items: flex-end;
}

.board {
  display: inline-block;
  background: gray;
  width: 30%;
  float: left;
  margin-left: 5px;
}

#boards-container {
  position: relative;
  width: 400px;
}

#boards-container .boards {
  position: absolute
}

<div id="boards-container">
  <div class="boards">
    <div class="board">
      <p>1st Event</p>
      <p>2nd Event</p>
      <p>3rd Event 3rd Event 3rd Event 3rd Event 3rd Event</p>
    </div>
    <div class="board">
      (This should align at bottom)
      <p>1st News</p>
    </div>
    <div class="board">
      (This should align at bottom)
      <p>1st Gallery</p>
      <p>2nd Gallery</p>
      <p>3rd Gallery</p>
    </div>
  </div>
</div>


答:
Your problem will be solved.

Use this code in your adapter:

```<code>@Override
public int getItemCount() {
    return data.size();
}
</code>```

Title: ReyclerView isn't working

Body:
Your problem will be solved.

Use this code in your adapter:

@Override
public int getItemCount() {
    return data.size();
}


问:
how to fix the error displayed by the PHP code?
this question is the continues of this last question with different error
I've got a PHP code that selects a PDF file and converts it to a text file.

I'm using an external library pdf-to-text with the composer.

Following is the system display error:

Fatal error: Uncaught Spatie\PdfToText\Exceptions\CouldNotExtractText:
  The command "/usr/bin/pdftotext "pdf.pdf" -" failed. Exit Code:
  1(General error) Working directory: C:\xampp\htdocs\testcomposer
  Output: ================ Error Output: ================ The system
  cannot find the path specified. in
  C:\xampp\htdocs\testcomposer\src\Pdf.php:37 Stack trace: #0
  C:\xampp\htdocs\testcomposer\test2.php(8):
  Spatie\PdfToText\Pdf->text() #1 {main} thrown in
  C:\xampp\htdocs\testcomposer\src\Pdf.php on line 37

Project Structure :

testcomposer

src

```<code>  -Exceptions
       -CouldNotExtractText.php
       -PdfNotFound.php
  -pdf.php
</code>```

vendor

```<code>-composer
-autoload.php
</code>```

composer.json

test2.php

pdf.php

codes

pdf.php

```<code><?php

namespace Spatie\pdftotext\src;

use Spatie\pdftotext\src\Exceptions;
use Symfony\process;

class Pdf
{
    protected $pdf;

    protected $binPath;

    public function __construct(string $binPath = null)
    {
        $this->binPath = $binPath ?? '/usr/bin/pdftotext';
    }

    public function setPdf(string $pdf) : Pdf
    {
        if (!file_exists($pdf)) {
            throw new PdfNotFound("could not find pdf {$pdf}");
        }

        $this->pdf = $pdf;

        return $this;
    }

    public function text() : string
    {
        $process = new Process("{$this->binPath} " . escapeshellarg($this->pdf) . " -");
        $process->run();

        if (!$process->isSuccessful()) {
            throw new CouldNotExtractText($process);
        }

        return trim($process->getOutput(), " \t\n\r\0\x0B\x0C");
    }

    public static function getText(string $pdf, string $binPath = null) : string
    {
        return (new static($binPath))
            ->setPdf($pdf)
            ->text();
    }
}
</code>```

composer.json

```<code>{
    "name": "spatie/pdf-to-text",
    "description": "Extract text from a pdf",
    "keywords": [
        "spatie",
        "pdftotext"
    ],
    "homepage": "https://github.com/spatie/pdf-to-text",
    "license": "MIT",
    "authors": [
        {
            "name": "Freek Van der Herten",
            "email": "freek@spatie.be",
            "homepage": "https://spatie.be",
            "role": "Developer"
        }
    ],
    "require": {
        "php" : "^7.0",
        "symfony/process": "^3.0"
    },
    "require-dev": {
        "phpunit/phpunit" : "^6.4"
    },
    "autoload": {
        "psr-4": {
            "src\\": "app/Spatie/pdftotext/src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Spatie\\pdftotext\\Test\\": "tests"
        }
    },
    "scripts": {
        "test": "phpunit"
    }
}
</code>```

test2.php

```<code>    <?php
require 'vendor/autoload.php';

use Spatie\PdfToText\Pdf;

$text = (new Pdf())
    ->setPdf('pdf.pdf')
    ->text();

print_r($text);
?>
</code>```

答:
I create test project for get content from pdf file
check this git

https://github.com/akkapong/test-pdf

the package pdf-to-text you use is required pdftotext command so you need to install first.

after you install the command will tell you about path of command
you can replace the path in file test.php on line 6

================== run test.php =================
$ php test.php

hope this help

Body:
this question is the continues of this last question with different error
I've got a PHP code that selects a PDF file and converts it to a text file.

I'm using an external library pdf-to-text with the composer.

Following is the system display error:

Fatal error: Uncaught Spatie\PdfToText\Exceptions\CouldNotExtractText:
  The command "/usr/bin/pdftotext "pdf.pdf" -" failed. Exit Code:
  1(General error) Working directory: C:\xampp\htdocs\testcomposer
  Output: ================ Error Output: ================ The system
  cannot find the path specified. in
  C:\xampp\htdocs\testcomposer\src\Pdf.php:37 Stack trace: #0
  C:\xampp\htdocs\testcomposer\test2.php(8):
  Spatie\PdfToText\Pdf->text() #1 {main} thrown in
  C:\xampp\htdocs\testcomposer\src\Pdf.php on line 37

Project Structure :

testcomposer

src

  -Exceptions
       -CouldNotExtractText.php
       -PdfNotFound.php
  -pdf.php

vendor

-composer
-autoload.php

composer.json

test2.php

pdf.php

codes

pdf.php

<?php

namespace Spatie\pdftotext\src;

use Spatie\pdftotext\src\Exceptions;
use Symfony\process;

class Pdf
{
    protected $pdf;

    protected $binPath;

    public function __construct(string $binPath = null)
    {
        $this->binPath = $binPath ?? '/usr/bin/pdftotext';
    }

    public function setPdf(string $pdf) : Pdf
    {
        if (!file_exists($pdf)) {
            throw new PdfNotFound("could not find pdf {$pdf}");
        }

        $this->pdf = $pdf;

        return $this;
    }

    public function text() : string
    {
        $process = new Process("{$this->binPath} " . escapeshellarg($this->pdf) . " -");
        $process->run();

        if (!$process->isSuccessful()) {
            throw new CouldNotExtractText($process);
        }

        return trim($process->getOutput(), " \t\n\r\0\x0B\x0C");
    }

    public static function getText(string $pdf, string $binPath = null) : string
    {
        return (new static($binPath))
            ->setPdf($pdf)
            ->text();
    }
}

composer.json

{
    "name": "spatie/pdf-to-text",
    "description": "Extract text from a pdf",
    "keywords": [
        "spatie",
        "pdftotext"
    ],
    "homepage": "https://github.com/spatie/pdf-to-text",
    "license": "MIT",
    "authors": [
        {
            "name": "Freek Van der Herten",
            "email": "freek@spatie.be",
            "homepage": "https://spatie.be",
            "role": "Developer"
        }
    ],
    "require": {
        "php" : "^7.0",
        "symfony/process": "^3.0"
    },
    "require-dev": {
        "phpunit/phpunit" : "^6.4"
    },
    "autoload": {
        "psr-4": {
            "src\\": "app/Spatie/pdftotext/src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Spatie\\pdftotext\\Test\\": "tests"
        }
    },
    "scripts": {
        "test": "phpunit"
    }
}

test2.php

    <?php
require 'vendor/autoload.php';

use Spatie\PdfToText\Pdf;

$text = (new Pdf())
    ->setPdf('pdf.pdf')
    ->text();

print_r($text);
?>


答: The type of the variable is Animal, the compiler will not allow you to assign this to a Monkey because an Animal is not necessarily a Monkey. You could assign the other way around because a Monkey is always an Animal. GetType() returns the runtime type of the object the variable points to which the compiler does not, and cannot, know anything about.

Title: Assigning instance of a derived class to a variable of base class


问:
PacketTrace Default Gateway
I've set up the default gateway of the router I am configurating as serial2/0 as they call it on packet trace with the address of 172.16.68.1. When I try and ping the gateway from the pc with the address 172.16.16.1 I just get an error saying request timed out.

Have I done the default gateway correctly and if I have can anyone suggest what is causing the time out?

答:
The subnet 172.16.16.1/21 which includes the PC does not contain the IP of its default gateway (172.16.68.1). That means that the PC cannot access its own default gateway with its current routing table.

You need to either setup a router/gateway within the PC's current subnet, or change the subnet settings to include the gateway. Keep in mind that the last alternative might not be applicable in your network.

Title: PacketTrace Default Gateway


问:
Can't connect to Tarantool container inside Docker through Nodejs
I want to connect to the tarantool cotainer using this code:

```<code>import TarantoolConnection from 'tarantool-driver'
let connection = new TarantoolConnection('192.168.99.100:3301');
connection.ping().then((res) => {
   console.log(res);
});
</code>```

Before that i started container:

```<code>docker run -p 3301:3301 -d tarantool/tarantool:1.6
</code>```

But in result i get nothing.

If i try to create space or\and index for this space:

```<code>connection.eval("box.schema.space.create('myspace', {if_not_exists=true, temporary=true})").then((res) => {
    console.log(res);
});
</code>```

I get this error:

UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): Error: This socket is closed

or:

UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 2): Error: connection will be destroyed or
  already destroyed, create another one

As i see from the error, the needed socket is already closed, but i don't understand why.

Version of tarantool driver:

```<code>"tarantool-driver": "2.0.5",
</code>```

How can i fix it?

答:
You have two problems here:

You should connect to localhost:3301 instead of 192.168.99.100:3301

You have to use connection.connect() before connection.ping() or connection.eval()

Here is the working code:

```<code>const TarantoolConnection = require('tarantool-driver');

let connection = new TarantoolConnection({port: 3301});

connection.connect().then((res) => {
    console.log("Connected: " + res);

    connection.ping().then((res) => {
        console.log("Pong: " + res);
    });

    connection.eval("box.schema.space.create('myspace', {if_not_exists=true, temporary=true})").then((res) => {
        console.log("Space created");
    });
});
</code>```

Just in case, I've used the following command to start tarantool docker instance:

```<code>$ docker run --rm -p 3301:3301 -t -i tarantool/tarantool:1.6
</code>```

Body:
I want to connect to the tarantool cotainer using this code:

import TarantoolConnection from 'tarantool-driver'
let connection = new TarantoolConnection('192.168.99.100:3301');
connection.ping().then((res) => {
   console.log(res);
});

Before that i started container:

docker run -p 3301:3301 -d tarantool/tarantool:1.6

But in result i get nothing.

If i try to create space or\and index for this space:

connection.eval("box.schema.space.create('myspace', {if_not_exists=true, temporary=true})").then((res) => {
    console.log(res);
});

I get this error:

UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): Error: This socket is closed

or:

UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 2): Error: connection will be destroyed or
  already destroyed, create another one

As i see from the error, the needed socket is already closed, but i don't understand why.

Version of tarantool driver:

"tarantool-driver": "2.0.5",

How can i fix it?

Body:
You have two problems here:

You should connect to localhost:3301 instead of 192.168.99.100:3301

You have to use connection.connect() before connection.ping() or connection.eval()

Here is the working code:

const TarantoolConnection = require('tarantool-driver');

let connection = new TarantoolConnection({port: 3301});

connection.connect().then((res) => {
    console.log("Connected: " + res);

    connection.ping().then((res) => {
        console.log("Pong: " + res);
    });

    connection.eval("box.schema.space.create('myspace', {if_not_exists=true, temporary=true})").then((res) => {
        console.log("Space created");
    });
});

Just in case, I've used the following command to start tarantool docker instance:

$ docker run --rm -p 3301:3301 -t -i tarantool/tarantool:1.6


问:
Scrollview inside constraint layout does not scroll to the bottom of the parent constraint
I have a form which has around 12/13 fields. I used a Scrollview inside a constraint layout. Below is the hierarchy of the XML layout. The problem is, it doesn't scroll to the bottom instead scrolls only to the first initial 10 views. The last 3 fields gets hidden as the view does not scroll any further.

PARENT LAYOUT

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_register"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true"
android:orientation="vertical">

<!-- Textview and a button -->

  <ScrollView
    android:id="@+id/scrollView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp"
    android:orientation="vertical"
    android:overScrollMode="never"
    android:scrollbars="none"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/view"
    tools:layout_constraintBottom_creator="1"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintTop_creator="1"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="0dp">

  <android.support.constraint.ConstraintLayout
        android:id="@+id/constraintLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

                <!-- Child Views (12/13 views of the fields)-->

  </android.support.constraint.ConstraintLayout>

</ScrollView>

</android.support.constraint.ConstraintLayout>
</code>```

答:
Try adding bottom constraint to scrollview (eg: app:layout_constraintBottom_toBottomOf="parent")
and change  android:layout_height="wrap_content" to  android:layout_height="0dp"

Body:
I have a form which has around 12/13 fields. I used a Scrollview inside a constraint layout. Below is the hierarchy of the XML layout. The problem is, it doesn't scroll to the bottom instead scrolls only to the first initial 10 views. The last 3 fields gets hidden as the view does not scroll any further.

PARENT LAYOUT

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_register"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true"
android:orientation="vertical">

  <ScrollView
    android:id="@+id/scrollView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp"
    android:orientation="vertical"
    android:overScrollMode="never"
    android:scrollbars="none"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/view"
    tools:layout_constraintBottom_creator="1"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintTop_creator="1"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="0dp">

  <android.support.constraint.ConstraintLayout
        android:id="@+id/constraintLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

  </android.support.constraint.ConstraintLayout>

</ScrollView>

</android.support.constraint.ConstraintLayout>


问:
SQL - how to update a column with each row value incremented by 1?
For the selected rows in a column, how to update each row sequentially from the beginning to the end, with each row value incremented by 1 (or certain number). I know this can be done in excel in few seconds but I could figure out how to achieve in SQL server. For instance:

customer id is NULL now
update customer id with every row incremented by 1 (i.e. first row = 1, second row = 2, .....nth row = n)

```<code>ship-to party   customer id
0002018092      NULL
0002008127      NULL
0002000129      NULL
0002031592      NULL
0002034232      NULL
</code>```

desired output

```<code>ship-to party   customer id
0002018092      1
0002008127      2
0002000129      3
0002031592      4
0002034232      5
</code>```

Also, for the selected rows in a column, how to update each row with the row number? I know there is a row_number() function but didn't succeed in producing the desired result. for instance

column A is NULL now
update Column A with every row incremented by 1 (i.e. first row = row number 1, second row = row number 2, .....nth row = row number n)

Any demonstration would be very helpful.thkans

答:
To update each row with row number </p>

<p>Try below </p>

```<code>CREATE TABLE tmp(Id INT IDENTITY(1,1), Value INT)

INSERT INTO tmp(value) VALUES(1),(2),(3),(4),(5)

UPDATE T
SET
T.Value = B.RowNo
FROM tmp AS T
INNER JOIN (SELECT Id, ROW_NUMBER()OVER(ORDER BY Id) AS RowNo FROM tmp)AS B
ON T.Id = B.Id
</code>```

Body:
For the selected rows in a column, how to update each row sequentially from the beginning to the end, with each row value incremented by 1 (or certain number). I know this can be done in excel in few seconds but I could figure out how to achieve in SQL server. For instance:

customer id is NULL now
update customer id with every row incremented by 1 (i.e. first row = 1, second row = 2, .....nth row = n)

ship-to party   customer id
0002018092      NULL
0002008127      NULL
0002000129      NULL
0002031592      NULL
0002034232      NULL

desired output

ship-to party   customer id
0002018092      1
0002008127      2
0002000129      3
0002031592      4
0002034232      5

Also, for the selected rows in a column, how to update each row with the row number? I know there is a row_number() function but didn't succeed in producing the desired result. for instance

column A is NULL now
update Column A with every row incremented by 1 (i.e. first row = row number 1, second row = row number 2, .....nth row = row number n)

Any demonstration would be very helpful.thkans

Body:
To update each row with row number

Try below

CREATE TABLE tmp(Id INT IDENTITY(1,1), Value INT)

INSERT INTO tmp(value) VALUES(1),(2),(3),(4),(5)

UPDATE T
SET
T.Value = B.RowNo
FROM tmp AS T
INNER JOIN (SELECT Id, ROW_NUMBER()OVER(ORDER BY Id) AS RowNo FROM tmp)AS B
ON T.Id = B.Id


问:
org.w3c.dom.Node with Android version less than 2.2
getTextContent() is not a recognized function.  getNodeValue() works fine for strings, but anytime I try to parse a number using getNodeValue(), it returns null!

How can I parse a Long from XML using this class?

答:
If as you say "getNodeValue() works fine for strings", then nothing should prevent from doing the:

```<code>Long l = Long.getLong(node.getNodeValue());
</code>```

Note, getNodeValue() will always return a String that should be then manually converted to a numerical type.

Also - are you sure you are parsing a right node (the one that holds the needed long value)?

Body:
If as you say "getNodeValue() works fine for strings", then nothing should prevent from doing the:

Long l = Long.getLong(node.getNodeValue());

Note, getNodeValue() will always return a String that should be then manually converted to a numerical type.

Also - are you sure you are parsing a right node (the one that holds the needed long value)?


问:
Ignore certain lines in files when running git diff
Let's say I want to compare two log files for differences (not my real use-case but good to point out the problem), but because they have timestamps at the beginning, and those will obviously differ, they'll show every line as different.

Let's consider this (silly) example:

```<code>00:00:05 something1     00:00:06 something1
00:00:06 something2     00:00:07 something2
00:00:07 something__3   00:00:08 something__4
00:00:08 something5     00:00:09 something5
</code>```

Here we have 2 logs side by side, and the timespamps differ in every line, but only line 3 differs in content - something3 vs something4.

What I do now is that I use Notepad++ to erase the timestamps before diff-ing them, but that's a lot of manual work, esp. for many files. I'd rather if I could just tell git diff to first apply a filter to the files before diff-ing them.

Is that possible? I saw this question here - https://unix.stackexchange.com/questions/17040/how-to-diff-files-ignoring-comments-lines-starting-with, where they talk about diff -u -I '#.*' test{1,2} but git diff doesn't recognize an -I flag.

答:
Suppose the two revisions are commit1 and commit2, the file path in the repository is foo/bar.log.

```<code>git diff -U0 \
$(git cat-file -p commit1:foo/bar.log | awk '{$1=""}1' | awk '{$1=$1}1' | git hash-object --stdin -w) \
$(git cat-file -p commit2:foo/bar.log | awk '{$1=""}1' | awk '{$1=$1}1' | git hash-object --stdin -w)
</code>```

git cat-file -p commit1:foo/bar.log prints the content of the file of one revision. awk removes the first field, the timestamp. git hash-object --stdin -w creates a blob. git diff compares the two blobs. -U0 removes the context from the output.

The two blobs are dangling. You could run git gc --prune=now to remove them. You could also leave them alone as they will be wiped out in a few days.

A sample function in ~/.bashrc:

```<code>function difflog() {
    local left=$1
    local right=$2
    local path=$3
    git diff -U0 \
        $(git cat-file -p ${left}:${path} | awk '{$1=""}1' | awk '{$1=$1}1' | git hash-object --stdin -w) \
        $(git cat-file -p ${right}:${path} | awk '{$1=""}1' | awk '{$1=$1}1' | git hash-object --stdin -w)
    git gc --prune=now --quiet
}
</code>```

To call the function, difflog HEAD HEAD~1 foo/bar.

Body:
Let's say I want to compare two log files for differences (not my real use-case but good to point out the problem), but because they have timestamps at the beginning, and those will obviously differ, they'll show every line as different.

Let's consider this (silly) example:

00:00:05 something1     00:00:06 something1
00:00:06 something2     00:00:07 something2
00:00:07 something__3   00:00:08 something__4
00:00:08 something5     00:00:09 something5

Here we have 2 logs side by side, and the timespamps differ in every line, but only line 3 differs in content - something3 vs something4.

What I do now is that I use Notepad++ to erase the timestamps before diff-ing them, but that's a lot of manual work, esp. for many files. I'd rather if I could just tell git diff to first apply a filter to the files before diff-ing them.

Is that possible? I saw this question here - https://unix.stackexchange.com/questions/17040/how-to-diff-files-ignoring-comments-lines-starting-with, where they talk about diff -u -I '#.*' test{1,2} but git diff doesn't recognize an -I flag.

Body:
Suppose the two revisions are commit1 and commit2, the file path in the repository is foo/bar.log.

git diff -U0 \
$(git cat-file -p commit1:foo/bar.log | awk '{$1=""}1' | awk '{$1=$1}1' | git hash-object --stdin -w) \
$(git cat-file -p commit2:foo/bar.log | awk '{$1=""}1' | awk '{$1=$1}1' | git hash-object --stdin -w)

git cat-file -p commit1:foo/bar.log prints the content of the file of one revision. awk removes the first field, the timestamp. git hash-object --stdin -w creates a blob. git diff compares the two blobs. -U0 removes the context from the output.

The two blobs are dangling. You could run git gc --prune=now to remove them. You could also leave them alone as they will be wiped out in a few days.

A sample function in ~/.bashrc:

function difflog() {
    local left=$1
    local right=$2
    local path=$3
    git diff -U0 \
        $(git cat-file -p ${left}:${path} | awk '{$1=""}1' | awk '{$1=$1}1' | git hash-object --stdin -w) \
        $(git cat-file -p ${right}:${path} | awk '{$1=""}1' | awk '{$1=$1}1' | git hash-object --stdin -w)
    git gc --prune=now --quiet
}

To call the function, difflog HEAD HEAD~1 foo/bar.


问:
open("/dev/mem", O_RDWR) returns -1
I am trying to port https://github.com/jazzycamel/ws28128-rpi to android things using a native app.

At runtime, the library fails here.  It appears we need super user access, is there another way to achieve this?

答: Seems port of WS2812 RGB LED library to Android Things platform is impossible now, even if you fix runtime error, because max frequency of RPI GPIO with Android Things is about 3kHz (for details see this answer) but data transfer frequency for WS2812 RGB LED (according datasheet) is about 800kHz (TH+TL = 1.25us). There is no possibility now to create pulse with 0.32us duration on Android Things RPI even with native C code.</p>

Title: open("/dev/mem", O_RDWR) returns -1


问:
F#'s DescriptiveStatistics unknown?
I am currently converting a project in F# to Python, I am a relative amateur in F#, please...what on earth does this line do...

```<code>       let stats = new DescriptiveStatistics(list)
</code>```

I cant find a good definition of DescriptiveStatistics anywhere! Please help!
Many thanks

答:
https://numerics.mathdotnet.com/DescriptiveStatistics.html
"...in case you need to gather a whole set of statistical characteristics in one pass, is provided by the DescriptiveStatistics class:..." Thanks for your help guys</p>

Title: F#'s DescriptiveStatistics unknown?

Body:
I am currently converting a project in F# to Python, I am a relative amateur in F#, please...what on earth does this line do...

       let stats = new DescriptiveStatistics(list)

I cant find a good definition of DescriptiveStatistics anywhere! Please help!
Many thanks


问:
How to rewrite all url's to index.php with .htaccess
In an application I want all users to start at index.php. So I want to redirect all direct URLs to other pages to this file.

When I use the following syntax, only the non-existing files are rewritten, but I want to redirect the existing URLs too.

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
</code>```

答:
RewriteCond %{REQUEST_FILENAME} !-f means: if this file does not exist, apply the RewriteRule.

RewriteCond %{REQUEST_FILENAME} !-d means: if this directory does not exist, apply the RewriteRule.

Use:

```<code>RewriteEngine on
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
</code>```

EDIT:

If you want to redirect only when the URL does not start with /index.php yet, use this extra condition:

```<code>RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule ^(.*)$ /index.php/?path=$1 [NC,L,QSA]
</code>```

Body:
In an application I want all users to start at index.php. So I want to redirect all direct URLs to other pages to this file.

When I use the following syntax, only the non-existing files are rewritten, but I want to redirect the existing URLs too.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]

Body:
RewriteCond %{REQUEST_FILENAME} !-f means: if this file does not exist, apply the RewriteRule.

RewriteCond %{REQUEST_FILENAME} !-d means: if this directory does not exist, apply the RewriteRule.

Use:

RewriteEngine on
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]

EDIT:

If you want to redirect only when the URL does not start with /index.php yet, use this extra condition:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule ^(.*)$ /index.php/?path=$1 [NC,L,QSA]


问:
Visual Studio 2017 can not connected to MAC Agent
i try to connect vs2017 (Xamarin 4.3) to MAC Agent(El Capitan) in Virtual Machine (VMWare). I have see every link in internet and not working anything

https://developer.xamarin.com/guides/ios/getting_started/installation/windows/connecting-to-mac/troubleshooting/#knownissues

https://developer.xamarin.com/guides/ios/getting_started/installation/windows/connecting-to-mac/troubleshooting/

The log show me the next

```<code>--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   en Xamarin.Messaging.Ssh.MessagingService.<StartBrokerAsync>d__87.MoveNext()
--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   en Xamarin.Messaging.Ssh.MessagingService.<ConnectAsync>d__67.MoveNext()
Xamarin.VisualStudio.Remote.State.DisconnectedState|Error|0|No se pudo conectar con Mac-Admin.local.. Vuelva a intentarlo.
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Transición de estado del servidor de SshConnectingState a DisconnectedState en Mac-Admin.local. (10.10.0.82)
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Desconectado del equipo Mac Mac-Admin.local. (10.10.0.82)
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Transición de estado del servidor de DisconnectedState a SshConnectingState en Mac-Admin.local. (10.10.0.82)
Xamarin.Messaging.Ssh.MessagingService|Information|0|Iniciando la conexión con Mac 10.10.0.82...
Xamarin.Messaging.Ssh.MessagingService|Information|0|Iniciando el agente 4.3.0.784 en el puerto 50656...
Xamarin.Messaging.Ssh.SshCommands|Error|0|No se encuentra una instalación Mono en el equipo Mac
Xamarin.Messaging.Ssh.SshCommands|Error|0|Ubicaciones sondeadas para Mono en el equipo Mac: /usr/bin/mono64, /Library/Frameworks/Mono.framework/Versions/Current/bin/mono64
Xamarin.VisualStudio.Remote.State.DisconnectedState|Error|0|La inicialización del agente intermediario superó el tiempo de espera de 60000 milisegundos sin recibir confirmación del agente intermediario.
System.TimeoutException: La inicialización del agente intermediario superó el tiempo de espera de 60000 milisegundos sin recibir confirmación del agente intermediario.
   en Xamarin.Messaging.Ssh.BrokerCommands.<StartBrokerAsync>d__9.MoveNext()
--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   en Xamarin.Messaging.Ssh.MessagingService.<StartBrokerAsync>d__87.MoveNext()
--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   en Xamarin.Messaging.Ssh.MessagingService.<ConnectAsync>d__67.MoveNext()
Xamarin.VisualStudio.Remote.State.DisconnectedState|Error|0|No se pudo conectar con Mac-Admin.local.. Vuelva a intentarlo.
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Transición de estado del servidor de SshConnectingState a DisconnectedState en Mac-Admin.local. (10.10.0.82)
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Desconectado del equipo Mac Mac-Admin.local. (10.10.0.82)
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Transición de estado del servidor de DisconnectedState a SshConnectingState en Mac-Admin.local. (10.10.0.82)
Xamarin.Messaging.Ssh.SshCommandRunner|Warning|0|No se pudo ejecutar "grep "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCs6D+43Z2dxNsvYZ+NfM73iQxye9C/sn30tjOlDDl1Z/tIzTG8Du4X6gYCad8M+CGQCGdsW1zBD+Cqx9yhEa0D1VZKoRXcJhYWcsv2pS8wmwkc/+7zRcUhFDIxrgxd+2lWu8CUN+70KAuroctEas9/Thasoo3N0lAOCQHu6YqCHRw6iJ7tDOgdYSMKrByZTErd2yo3CJ3i7F07brkT5EMU18VUJcQnfkMRxf5k0pVs0wtlMYF/m720MFRCTQGrsx+4ZGiwRZIyfRp7gmZTv+KZiM1KSfnkaFSxUBZp6iFbW7lJVUOfAXjovorKqE/YQJa04vNcijUtaAsJgZsiQ5i3 admin@mac-admin.segurmatica.cu" /Users/admin/.ssh/authorized_keys": ExitStatus = 1
Xamarin.Messaging.Ssh.MessagingService|Information|0|Iniciando la conexión con Mac 10.10.0.82...
Xamarin.Messaging.Ssh.MessagingService|Information|0|Iniciando el agente 4.3.0.784 en el puerto 56425...
Xamarin.Messaging.Ssh.SshCommands|Error|0|No se encuentra una instalación Mono en el equipo Mac
Xamarin.Messaging.Ssh.SshCommands|Error|0|Ubicaciones sondeadas para Mono en el equipo Mac: /usr/bin/mono64, /Library/Frameworks/Mono.framework/Versions/Current/bin/mono64
Xamarin.VisualStudio.Remote.State.DisconnectedState|Error|0|La inicialización del agente intermediario superó el tiempo de espera de 60000 milisegundos sin recibir confirmación del agente intermediario.
System.TimeoutException: La inicialización del agente intermediario superó el tiempo de espera de 60000 milisegundos sin recibir confirmación del agente intermediario.
   en Xamarin.Messaging.Ssh.BrokerCommands.<StartBrokerAsync>d__9.MoveNext()
--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   en X
</code>```

答:
In my case the problem was in the connection between host and agent. I tried to set network adaptor as "bridge" but issue wasn't resolved. Try this few steps:

Open mac os, install latest xcode, ios sdk, xamarin and enable remote login on mac os;

Open windows, Go to VMWare Workstation settings -> Network Adapter -> Custom: Specific virtual network -> Select VMnet8(NAT);

Reboot vm;

When reboot will have finished go to Visual Studio 2017 -> Tools -> Options -> Xamarin -> iOS Settings -> Find Xamarin Mac Agent. Here you will find _ssh connection. Open it and write mac os user credentials.

After that connection was successfully established

Body:
i try to connect vs2017 (Xamarin 4.3) to MAC Agent(El Capitan) in Virtual Machine (VMWare). I have see every link in internet and not working anything

https://developer.xamarin.com/guides/ios/getting_started/installation/windows/connecting-to-mac/troubleshooting/#knownissues

https://developer.xamarin.com/guides/ios/getting_started/installation/windows/connecting-to-mac/troubleshooting/

The log show me the next

--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   en Xamarin.Messaging.Ssh.MessagingService.<StartBrokerAsync>d__87.MoveNext()
--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   en Xamarin.Messaging.Ssh.MessagingService.<ConnectAsync>d__67.MoveNext()
Xamarin.VisualStudio.Remote.State.DisconnectedState|Error|0|No se pudo conectar con Mac-Admin.local.. Vuelva a intentarlo.
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Transición de estado del servidor de SshConnectingState a DisconnectedState en Mac-Admin.local. (10.10.0.82)
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Desconectado del equipo Mac Mac-Admin.local. (10.10.0.82)
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Transición de estado del servidor de DisconnectedState a SshConnectingState en Mac-Admin.local. (10.10.0.82)
Xamarin.Messaging.Ssh.MessagingService|Information|0|Iniciando la conexión con Mac 10.10.0.82...
Xamarin.Messaging.Ssh.MessagingService|Information|0|Iniciando el agente 4.3.0.784 en el puerto 50656...
Xamarin.Messaging.Ssh.SshCommands|Error|0|No se encuentra una instalación Mono en el equipo Mac
Xamarin.Messaging.Ssh.SshCommands|Error|0|Ubicaciones sondeadas para Mono en el equipo Mac: /usr/bin/mono64, /Library/Frameworks/Mono.framework/Versions/Current/bin/mono64
Xamarin.VisualStudio.Remote.State.DisconnectedState|Error|0|La inicialización del agente intermediario superó el tiempo de espera de 60000 milisegundos sin recibir confirmación del agente intermediario.
System.TimeoutException: La inicialización del agente intermediario superó el tiempo de espera de 60000 milisegundos sin recibir confirmación del agente intermediario.
   en Xamarin.Messaging.Ssh.BrokerCommands.<StartBrokerAsync>d__9.MoveNext()
--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   en Xamarin.Messaging.Ssh.MessagingService.<StartBrokerAsync>d__87.MoveNext()
--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   en Xamarin.Messaging.Ssh.MessagingService.<ConnectAsync>d__67.MoveNext()
Xamarin.VisualStudio.Remote.State.DisconnectedState|Error|0|No se pudo conectar con Mac-Admin.local.. Vuelva a intentarlo.
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Transición de estado del servidor de SshConnectingState a DisconnectedState en Mac-Admin.local. (10.10.0.82)
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Desconectado del equipo Mac Mac-Admin.local. (10.10.0.82)
Xamarin.VisualStudio.Remote.State.ServerStateContext|Information|0|Transición de estado del servidor de DisconnectedState a SshConnectingState en Mac-Admin.local. (10.10.0.82)
Xamarin.Messaging.Ssh.SshCommandRunner|Warning|0|No se pudo ejecutar "grep "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCs6D+43Z2dxNsvYZ+NfM73iQxye9C/sn30tjOlDDl1Z/tIzTG8Du4X6gYCad8M+CGQCGdsW1zBD+Cqx9yhEa0D1VZKoRXcJhYWcsv2pS8wmwkc/+7zRcUhFDIxrgxd+2lWu8CUN+70KAuroctEas9/Thasoo3N0lAOCQHu6YqCHRw6iJ7tDOgdYSMKrByZTErd2yo3CJ3i7F07brkT5EMU18VUJcQnfkMRxf5k0pVs0wtlMYF/m720MFRCTQGrsx+4ZGiwRZIyfRp7gmZTv+KZiM1KSfnkaFSxUBZp6iFbW7lJVUOfAXjovorKqE/YQJa04vNcijUtaAsJgZsiQ5i3 admin@mac-admin.segurmatica.cu" /Users/admin/.ssh/authorized_keys": ExitStatus = 1
Xamarin.Messaging.Ssh.MessagingService|Information|0|Iniciando la conexión con Mac 10.10.0.82...
Xamarin.Messaging.Ssh.MessagingService|Information|0|Iniciando el agente 4.3.0.784 en el puerto 56425...
Xamarin.Messaging.Ssh.SshCommands|Error|0|No se encuentra una instalación Mono en el equipo Mac
Xamarin.Messaging.Ssh.SshCommands|Error|0|Ubicaciones sondeadas para Mono en el equipo Mac: /usr/bin/mono64, /Library/Frameworks/Mono.framework/Versions/Current/bin/mono64
Xamarin.VisualStudio.Remote.State.DisconnectedState|Error|0|La inicialización del agente intermediario superó el tiempo de espera de 60000 milisegundos sin recibir confirmación del agente intermediario.
System.TimeoutException: La inicialización del agente intermediario superó el tiempo de espera de 60000 milisegundos sin recibir confirmación del agente intermediario.
   en Xamarin.Messaging.Ssh.BrokerCommands.<StartBrokerAsync>d__9.MoveNext()
--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   en X


问:
How to change the color of an element of a recyclerview?
I want to change color of my cardview in Recyclerview if a string matches a string from QR code. I am able to display a toast if string matches, but I also want to change color of that particular element in Recyclerview.

here is the code of selecting an item for scanning

```<code>recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                   tempString = passengerDataModelList.get(position).getPnr();
                   tempClickPosi = position;
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    startActivityForResult(intent, 0);

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

Now on ActivityResult I will get the result:

```<code>    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
            if (requestCode == 0) {
                if (resultCode == RESULT_OK) {
                    String contents = intent.getStringExtra("SCAN_RESULT");
                    String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

                    if(contents.equalsIgnoreCase(tempString)){
                        Toast.makeText(this, "String MATCHED", Toast.LENGTH_SHORT).show();
///// Here I want to change the color of that item in recycler view
                    }else if(!contents.equalsIgnoreCase(tempString)){
                        Toast.makeText(this, "String NOT MATCHED", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(this, "Error in scanning", Toast.LENGTH_SHORT).show();
                    }

                }
            }

        }
</code>```

So please help me to change the color of that particular item from activity. If need more info kindly comment.
Thank You

答: Create separate flag for color and then once string is matched update flag for particular item and then notify your adapter</p>

Body:
I want to change color of my cardview in Recyclerview if a string matches a string from QR code. I am able to display a toast if string matches, but I also want to change color of that particular element in Recyclerview.

here is the code of selecting an item for scanning

recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                   tempString = passengerDataModelList.get(position).getPnr();
                   tempClickPosi = position;
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    startActivityForResult(intent, 0);

                }
            }));

Now on ActivityResult I will get the result:

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
            if (requestCode == 0) {
                if (resultCode == RESULT_OK) {
                    String contents = intent.getStringExtra("SCAN_RESULT");
                    String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

                    if(contents.equalsIgnoreCase(tempString)){
                        Toast.makeText(this, "String MATCHED", Toast.LENGTH_SHORT).show();
///// Here I want to change the color of that item in recycler view
                    }else if(!contents.equalsIgnoreCase(tempString)){
                        Toast.makeText(this, "String NOT MATCHED", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(this, "Error in scanning", Toast.LENGTH_SHORT).show();
                    }

                }
            }

        }

So please help me to change the color of that particular item from activity. If need more info kindly comment.
Thank You


问:
Drag and Drop in NSCollectionView example
I need drag and drop in NSCollectionView.

So I looked at Apples code-sample:
https://developer.apple.com/library/mac/#samplecode/IconCollection/Introduction/Intro.html

There is a method for dragging. But it's not working.

I added the following method  without result:

```<code>-(BOOL) collectionView:(NSCollectionView *)collectionView canDragItemsAtIndexes:(NSIndexSet *)indexes withEvent:(NSEvent *)event {
    return YES;
}
</code>```

The Delegate is set.

Does anybody know a solution?

答:
It is already working.

You will have to click, wait up to one sec. After the sec. clicking it is dragged...

-.-

Body:
I need drag and drop in NSCollectionView.

So I looked at Apples code-sample:
https://developer.apple.com/library/mac/#samplecode/IconCollection/Introduction/Intro.html

There is a method for dragging. But it's not working.

I added the following method  without result:

-(BOOL) collectionView:(NSCollectionView *)collectionView canDragItemsAtIndexes:(NSIndexSet *)indexes withEvent:(NSEvent *)event {
    return YES;
}

The Delegate is set.

Does anybody know a solution?


问:
in select command multiple where clause indentation error
```<code>cur.execute("SELECT name FROM developers_info WHERE field = 'runtime' AND experience = 3 ")
  data2 = cur.fetchall()
</code>```

File "project_part2.py", line 55     cur.execute("SELECT name FROM >developers_info WHERE field = 'runtime' AND experience = 3 ")       ^

IndentationError: expected an indented block

答:
This line is not indented properly.
Either not indented at same level as the previous line
OR
previous line has a : and this line should be indented further.

Body:
cur.execute("SELECT name FROM developers_info WHERE field = 'runtime' AND experience = 3 ")
  data2 = cur.fetchall()

File "project_part2.py", line 55     cur.execute("SELECT name FROM >developers_info WHERE field = 'runtime' AND experience = 3 ")       ^

IndentationError: expected an indented block


问:
how to call function in div tag without using *ngIf In Angular 2
In I want to filter JSON in nested loop I have filters in child loop, but ngFor but I also want that filter at parent level also angular 2 I am using nglf To call the function it working but I want another method because it calls contentiously</p>

```<code><div *ngFor="let partyAddress of addressDataShow?.data" >
    <div class="row bg-greybg"  *ngIf="companyFilter(partyAddress) || selectedaddress === 'ALL' || isAddressAvailabale > 0">
 <div *ngFor="let partyAddressDetails of partyAddress?.company_address">
          <div *ngIf="selectedaddress === 'ALL' || partyAddressDetails.address_type.indexOf(selectedaddress) > -1">
            <p>Filter data</p>
          </div>
        </div>
<div>
</div>
</code>```

答:
*ngIf is not the worst choice in this case. What's your reason for avoiding *ngIf?

Basically there's two other options coming into my mind:

Switch case
Example:

```<code><div [ngSwitch]="yourExpression">
    <div *ngSwitchCase="match_expression_1">Show it when condition 1 applies</div>
    <div *ngSwitchCase="match_expression_2">Show it when condition 2 applies</div></div>
</code>```

[hidden] directive

_

```<code><div [hidden]="yourExpressionHere"></div>
</code>```

Please let me know if that solves your problem.

ContentLicense: CC BY-SA 4.0

Body:
In I want to filter JSON in nested loop I have filters in child loop, but ngFor but I also want that filter at parent level also angular 2 I am using nglf To call the function it working but I want another method because it calls contentiously

 0">

 -1">

Filter data

Body:
*ngIf is not the worst choice in this case. What's your reason for avoiding *ngIf?

Basically there's two other options coming into my mind:

Switch case
Example:

<div [ngSwitch]="yourExpression">
    <div *ngSwitchCase="match_expression_1">Show it when condition 1 applies</div>
    <div *ngSwitchCase="match_expression_2">Show it when condition 2 applies</div></div>

[hidden] directive

_

<div [hidden]="yourExpressionHere"></div>

Please let me know if that solves your problem.


问:
Adding sorted and unsorted integer to list box in C#
Within my system I have a text box and button that allows the user to input an integer to the list box. However, I want to include two radio buttons - sorted and unsorted, so that the user has to select whether they want the integer to be sorted or unsorted when added.

This is the code I have so far for the add button;

```<code>private void buttonAdd_Click(object sender, EventArgs e)
{
    listBoxAddedIntegers.Items.Add(textBoxInsert.Text);
    textBoxInsert.Text = string.Empty;
    //MessageBox.Show(listBoxAddedIntegers.SelectedIndex.ToString());
    MessageBox.Show(listBoxAddedIntegers.Items.Count.ToString());
}
</code>```

this is the code for the radio button 'sorted;

```<code>private void radioButtonSorted_CheckedChanged(object sender, EventArgs e)
{
   radioButtonSorted.Checked = true;
}
</code>```

and this is the code for the 'unsorted' radio button -

```<code>private void radioButtonUnsorted_CheckedChanged(object sender, EventArgs e)
{
   radioButtonSorted.Checked = false;
}
</code>```

Does anyone have any suggestions on how to add an integer to the list, so that when the user selects the radio button 'sorted' and then clicks add integer, the integer is then added to the sorted list? Thank you.

答:
Use your radio buttons to toggle the Sorted property of the listbox. According to documentation, it also ensures that

[as] items are added to a sorted ListBox, the items are moved to the appropriate location in the sorted list

So, you could write

```<code>private void radioButtonSorted_CheckedChanged(object sender, EventArgs e)
{
    if((sender as RadioButton).Checked) listBoxAddedIntegers.Sorted = true;
}

private void radioButtonUnsorted_CheckedChanged(object sender, EventArgs e)
{
    if((sender as RadioButton).Checked) listBoxAddedIntegers.Sorted = false;
}
</code>```

You used the CheckedChanged event. It will fire not only when a radio button is selected, it will fire also for the other one that was unselected. Therefore it is necessary to query the actual check state in the handler.

There is a shortcoming though: Sorted is limited to alphabetical order. If you get 1, 10, 2, 3 but expect 1, 2, 3, 10 then you can left-pad your integers with zeroes to get 0001, 0002, 0003, 0010; or apply a solution like this which pre-sorts the data and then refreshes the entire listbox.

Body:
Within my system I have a text box and button that allows the user to input an integer to the list box. However, I want to include two radio buttons - sorted and unsorted, so that the user has to select whether they want the integer to be sorted or unsorted when added.

This is the code I have so far for the add button;

private void buttonAdd_Click(object sender, EventArgs e)
{
    listBoxAddedIntegers.Items.Add(textBoxInsert.Text);
    textBoxInsert.Text = string.Empty;
    //MessageBox.Show(listBoxAddedIntegers.SelectedIndex.ToString());
    MessageBox.Show(listBoxAddedIntegers.Items.Count.ToString());
}

this is the code for the radio button 'sorted;

private void radioButtonSorted_CheckedChanged(object sender, EventArgs e)
{
   radioButtonSorted.Checked = true;
}

and this is the code for the 'unsorted' radio button -

private void radioButtonUnsorted_CheckedChanged(object sender, EventArgs e)
{
   radioButtonSorted.Checked = false;
}

Does anyone have any suggestions on how to add an integer to the list, so that when the user selects the radio button 'sorted' and then clicks add integer, the integer is then added to the sorted list? Thank you.

Body:
Use your radio buttons to toggle the Sorted property of the listbox. According to documentation, it also ensures that

[as] items are added to a sorted ListBox, the items are moved to the appropriate location in the sorted list

So, you could write

private void radioButtonSorted_CheckedChanged(object sender, EventArgs e)
{
    if((sender as RadioButton).Checked) listBoxAddedIntegers.Sorted = true;
}

private void radioButtonUnsorted_CheckedChanged(object sender, EventArgs e)
{
    if((sender as RadioButton).Checked) listBoxAddedIntegers.Sorted = false;
}

You used the CheckedChanged event. It will fire not only when a radio button is selected, it will fire also for the other one that was unselected. Therefore it is necessary to query the actual check state in the handler.

There is a shortcoming though: Sorted is limited to alphabetical order. If you get 1, 10, 2, 3 but expect 1, 2, 3, 10 then you can left-pad your integers with zeroes to get 0001, 0002, 0003, 0010; or apply a solution like this which pre-sorts the data and then refreshes the entire listbox.


问:
Show div on click
I'm trying to make a div appear and disappear using javascript, but it's not working.I've included the javascript file(where the function is),but I don't understand why it's not working.

When I press the button, nothing happens.

HTML code:

```<code><script type="text/javascript" src="show_on_click.js"></script>

<div id="myDiv" style="display:none" class="answer_list">Button Test</div>
<input type="button" name="answer" onclick="ShowDiv()" value="Test"/>
</code>```

JavaScript code:

```<code>function ShowDiv(){
    document.getElementById("myDiv").style.display = 'block';
}
</code>```

答:
Another problem will be: you are only set display to block, not to none again.

Try this:

```<code>function ShowDiv() {
    var element = document.getElementById("myDiv");
    if (element.style.display === 'none') {
        element.style.display = 'block';
    } else {
        element.style.display = 'none';
    }
}
</code>```

Title: Show div on click

Body:
I'm trying to make a div appear and disappear using javascript, but it's not working.I've included the javascript file(where the function is),but I don't understand why it's not working.

When I press the button, nothing happens.

HTML code:

Button Test

<input type="button" name="answer" onclick="ShowDiv()" value="Test"/>

JavaScript code:

function ShowDiv(){
    document.getElementById("myDiv").style.display = 'block';
}

Body:
Another problem will be: you are only set display to block, not to none again.

Try this:

function ShowDiv() {
    var element = document.getElementById("myDiv");
    if (element.style.display === 'none') {
        element.style.display = 'block';
    } else {
        element.style.display = 'none';
    }
}


答:
For suppose you have a model

```<code>public class PassengerData{

  //add this property
  private boolean isMatched = false;

  void setMatched(boolean matched){
        this.isMatched = matched;
  }

  boolean isMatched(){
       return isMatched;
  }

}
</code>```

Then in recyclerview's bindview just verify the boolean,

```<code>boolean matched = passengerDataModelList.get(position).isMatched();
cardview.setBackgroundColor(matched ? R.color.matched_color : R.color.unmatched_color);
</code>```

Then in Activity

```<code>    if(contents.equalsIgnoreCase(tempString)){
                            Toast.makeText(this, "String MATCHED", Toast.LENGTH_SHORT).show();
    ///// Here I want to change the color of that item in recycler view
              // modify `isMatched` value for that item and call `notifyDataSetChanged`();
     }
</code>```

Title: How to change the color of an element of a recyclerview?

Body:
For suppose you have a model

public class PassengerData{

  //add this property
  private boolean isMatched = false;

  void setMatched(boolean matched){
        this.isMatched = matched;
  }

  boolean isMatched(){
       return isMatched;
  }

}

Then in recyclerview's bindview just verify the boolean,

boolean matched = passengerDataModelList.get(position).isMatched();
cardview.setBackgroundColor(matched ? R.color.matched_color : R.color.unmatched_color);

Then in Activity

    if(contents.equalsIgnoreCase(tempString)){
                            Toast.makeText(this, "String MATCHED", Toast.LENGTH_SHORT).show();
    ///// Here I want to change the color of that item in recycler view
              // modify `isMatched` value for that item and call `notifyDataSetChanged`();
     }