问:
How to enable and use SPI on the BeagleBoneBlack
I have a BeagleBoneBlack Wireless and I would like to use SPI (and I2C). I am finding it very difficult to get definitive instructions on how to set up and use SPI on the BBB. Firstly, it is not clear to me what the default configuration of the BBB is. I appear to have two SPI devices:

```<code>$ ls /dev/spi*
/dev/spidev1.0  /dev/spidev1.1  /dev/spidev2.0  /dev/spidev2.1
</code>```

I also appear to have I2C:

```<code>$ ls /dev/i2c*
/dev/i2c-0  /dev/i2c-1  /dev/i2c-2
</code>```

It is not clear to me whether these buses are actually multiplexed to the pins or whether they are not really available. If they are connected to the pins, exactly which bus is which?

I tried to check this using the pin multiplexing information (from here) which told me that for SPI1 chip select 0 I should be using a pin with offset 0x19C, so I queried the mode on that pin:

```<code>$ sudo cat /sys/kernel/debug/pinctrl/44e10800.pinmux/pins | grep 44e1099c
pin 103 (44e1099c.0) 00000002 pinctrl-single
</code>```

which comes back as mode 2, which is not very useful to me (it's not SPI). I tried to follow instructions on setting up an overlay for this (from here) but this needed a bit of adapting for my kernel and didn't seem to help even then.

Please could someone point me to some instructions which make this a bit clearer and, ideally, match the kernel version I am using (4.4.30)?

答:
After much digging around I found that the latest versions of the BBB (certainly the Wireless one I have) use a universal cape device tree overlay and it seems that adding/removing overlays is now not the preferred way to handle pin configuration.

Pin configuration can now be done using the config-pin utility, and this did work for me.  For example, to make SPI0 accessible (the device driver is already present):

```<code>config-pin P9.17 spi
config-pin P9.18 spi
config-pin P9.21 spi
config-pin P9.22 spi
</code>```

This is not persistent across boots, so I added it to my .profile. I suspect there is a neater way, which probably returns to device tree overlays, but this was what I needed to get started.

Documentation on this newer approach to pin configuration was very difficult to find.

Body:
I have a BeagleBoneBlack Wireless and I would like to use SPI (and I2C). I am finding it very difficult to get definitive instructions on how to set up and use SPI on the BBB. Firstly, it is not clear to me what the default configuration of the BBB is. I appear to have two SPI devices:

$ ls /dev/spi*
/dev/spidev1.0  /dev/spidev1.1  /dev/spidev2.0  /dev/spidev2.1

I also appear to have I2C:

$ ls /dev/i2c*
/dev/i2c-0  /dev/i2c-1  /dev/i2c-2

It is not clear to me whether these buses are actually multiplexed to the pins or whether they are not really available. If they are connected to the pins, exactly which bus is which?

I tried to check this using the pin multiplexing information (from here) which told me that for SPI1 chip select 0 I should be using a pin with offset 0x19C, so I queried the mode on that pin:

$ sudo cat /sys/kernel/debug/pinctrl/44e10800.pinmux/pins | grep 44e1099c
pin 103 (44e1099c.0) 00000002 pinctrl-single

which comes back as mode 2, which is not very useful to me (it's not SPI). I tried to follow instructions on setting up an overlay for this (from here) but this needed a bit of adapting for my kernel and didn't seem to help even then.

Please could someone point me to some instructions which make this a bit clearer and, ideally, match the kernel version I am using (4.4.30)?

Body:
After much digging around I found that the latest versions of the BBB (certainly the Wireless one I have) use a universal cape device tree overlay and it seems that adding/removing overlays is now not the preferred way to handle pin configuration.

Pin configuration can now be done using the config-pin utility, and this did work for me.  For example, to make SPI0 accessible (the device driver is already present):

config-pin P9.17 spi
config-pin P9.18 spi
config-pin P9.21 spi
config-pin P9.22 spi

This is not persistent across boots, so I added it to my .profile. I suspect there is a neater way, which probably returns to device tree overlays, but this was what I needed to get started.

Documentation on this newer approach to pin configuration was very difficult to find.


来源: stackexchange

问:
Does Android Studio support Code completion for C/C++?
The code completion is fine on Android Studio java project. But I want to use Android Studio to edit some existing C file(.cpp).

for example, if i have declared some function, then i type the function in other section. But the android studio doesn't show up the code suggestion or some debugging.

Can Android Studio support Code completion for C/C++ like this:?

答:
If your project uses Android.mk to build, it will be a bug of Android Studio. I have been reported.

Android.mk project cannot show code completion for cpp.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
how to download in python
I am writing a script which will run on my server. Its purpose is to download the document. If any person hit the particular url he/she should be able to download the document. I am using urllib.urlretrieve but it download document on the server side not on the client. How to download in python at client side?</p>

答:
If the script runs on your server, its purpose is to serve a document, not to download it (the latter would be the urllib solution).

Depending on your needs you can:

Set up static file serving with e.g. Apache

Make the script execute on a certain URL (e.g. with mod_wsgi), then the script should set the Content-Type (provides document type such as "text/plain") and Content-Disposition (provides download filename) headers and send the document data

As your question is not more specific, this answer can't be either.

ContentLicense: CC BY-SA 2.5

Title: how to download in python


问:
python watchdog observer not working on ubuntu 16.04
I  this script not working on vagrant which have Ubuntu 16.04

This code working fine on mac

 import sys
 import time
 import logging
 from watchdog.observers import Observer
 from watchdog.events import LoggingEventHandler

 if __name__ == "__main__":
 logging.basicConfig(level=logging.INFO,
                  format='%(asctime)s - %(message)s',
                  datefmt='%Y-%m-%d %H:%M:%S')
  path = sys.argv[1] if len(sys.argv) > 1 else '.'
  event_handler = LoggingEventHandler()
  observer = Observer()
  observer.schedule(event_handler, path, recursive=True)
  observer.start()
  try:
      while True:
        time.sleep(1)
  except KeyboardInterrupt:
      observer.stop()
      observer.join()
```

答: its solved, watchdog event not firing because I have added new file from outside of vagrant :)</p>


问:
How to inflate view in list view for odd and even position
How to inflate view in list view for odd and even position.I want to show left align xml in even position and right align xml to odd position.

```<code>This is my code:

 public View getView(final int position, View view, ViewGroup parent)
{
    LayoutInflater inflator = context.getLayoutInflater();
    if ((position % 2) == 0) {

         rowView = inflator.inflate(R.layout.chatbubble, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView.findViewById(R.id.message_text);
        txtv_msg.setText(""+menus[position]);
    }
    else {
        rowView1 = inflator.inflate(R.layout.chatbubble1, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView1.findViewById(R.id.message_text);
        txtv_msg.setText(""+menus[position]);

    }

    return rowView;
}
</code>```

but for all position my data items are left align .

```<code>This is my xml  :
for left :
     <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout   xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/bubble_layout_parent"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
      android:layout_margin="10dp"
       android:padding="5dp">

    <LinearLayout
     android:id="@+id/bubble_layout"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="@drawable/bubble1">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxEms="12"
        android:layout_gravity="center"
        android:text="Hi! new message"
        android:textColor="@android:color/primary_text_light" />
   </LinearLayout>

  </LinearLayout>

  for right :
      <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/bubble_layout_parent"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_margin="10dp"
      android:padding="5dp"
      android:layout_gravity="right">

    <LinearLayout
     android:id="@+id/bubble_layout"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="@drawable/bubble1">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxEms="12"
        android:layout_gravity="center"
        android:text="Hi! new message"
        android:textColor="@android:color/primary_text_light" />
       </LinearLayout>

       </LinearLayout>
</code>```

I am new to android development please help.

答:
The problem is in your adapter's getView() method. It always returns rowView which is left aligned XML.

Solution:

Rename adapter's getView() parameter view as rowView.

In your else condition inflate layout R.layout.chatbubble1 to rowView instead of rowView1 and also change rowView1.findViewById() to rowView.findViewById().

Here is the complete working code:

```<code>public View getView(final int position, View rowView, ViewGroup parent)
{
    LayoutInflater inflator = context.getLayoutInflater();
    if ((position % 2) == 0) {
        rowView = inflator.inflate(R.layout.chatbubble, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView.findViewById(R.id.message_text);
        txtv_msg.setText("" + menus[position]);
    }
    else {
        rowView = inflator.inflate(R.layout.chatbubble1, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView.findViewById(R.id.message_text);
        txtv_msg.setText("" + menus[position]);

    }

    return rowView;
}
</code>```

Hope this will help~

Body:
How to inflate view in list view for odd and even position.I want to show left align xml in even position and right align xml to odd position.

This is my code:

 public View getView(final int position, View view, ViewGroup parent)
{
    LayoutInflater inflator = context.getLayoutInflater();
    if ((position % 2) == 0) {

         rowView = inflator.inflate(R.layout.chatbubble, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView.findViewById(R.id.message_text);
        txtv_msg.setText(""+menus[position]);
    }
    else {
        rowView1 = inflator.inflate(R.layout.chatbubble1, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView1.findViewById(R.id.message_text);
        txtv_msg.setText(""+menus[position]);

    }

    return rowView;
}

but for all position my data items are left align .

This is my xml  :
for left :
     <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout   xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/bubble_layout_parent"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
      android:layout_margin="10dp"
       android:padding="5dp">

    <LinearLayout
     android:id="@+id/bubble_layout"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="@drawable/bubble1">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxEms="12"
        android:layout_gravity="center"
        android:text="Hi! new message"
        android:textColor="@android:color/primary_text_light" />
   </LinearLayout>

  </LinearLayout>

  for right :
      <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/bubble_layout_parent"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_margin="10dp"
      android:padding="5dp"
      android:layout_gravity="right">

    <LinearLayout
     android:id="@+id/bubble_layout"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="@drawable/bubble1">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxEms="12"
        android:layout_gravity="center"
        android:text="Hi! new message"
        android:textColor="@android:color/primary_text_light" />
       </LinearLayout>

       </LinearLayout>

I am new to android development please help.

Body:
The problem is in your adapter's getView() method. It always returns rowView which is left aligned XML.

Solution:

Rename adapter's getView() parameter view as rowView.

In your else condition inflate layout R.layout.chatbubble1 to rowView instead of rowView1 and also change rowView1.findViewById() to rowView.findViewById().

Here is the complete working code:

public View getView(final int position, View rowView, ViewGroup parent)
{
    LayoutInflater inflator = context.getLayoutInflater();
    if ((position % 2) == 0) {
        rowView = inflator.inflate(R.layout.chatbubble, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView.findViewById(R.id.message_text);
        txtv_msg.setText("" + menus[position]);
    }
    else {
        rowView = inflator.inflate(R.layout.chatbubble1, null, true);

        TextView txtv_msg;
        txtv_msg = (TextView) rowView.findViewById(R.id.message_text);
        txtv_msg.setText("" + menus[position]);

    }

    return rowView;
}

Hope this will help~


问:
Issue with description from php to csv
I use php to generate a csv file like this:

```<code><?php
function myfunction() {
    header('Content-Encoding: UTF-8');
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=filename.csv');

    $output = fopen('php://output', 'w');
    fputs( $output, "\xEF\xBB\xBF" );

    foreach (rows as $row) {
      $description=$this->FixDescription($row['Description']);
      $id = $row['id'];
      $myrow .= $id . ',' . $description ."\n";
}

      fputcsv($output, mb_convert_encoding($myrow, 'UCS-2LE', 'UTF-8'));
      fclose($output);
}
   public function FixDescription($descr){
    $d = html_entity_decode($descr, ENT_QUOTES, 'UTF-8');
    $d = htmlspecialchars_decode($d);
    $d = str_replace(' ', ' ', $d);
    $d = strip_tags($d);
    $d = str_replace('&','_',$d);
    return $d;
  }
?>
</code>```

When i download the generated file i get some rows correctly but for some rows description breaks and leaves blank rows and then prints and generally create a mess in my csv file. Any ideas of how not to break the content inside description field?

答:
In my FixDescription function it was added the following line before return:

```<code>$d = preg_replace('/\r\n/','',$d);
</code>```

This way ENTER is replaced and description is in one line

Title: Issue with description from php to csv

Body:
I use php to generate a csv file like this:

<?php
function myfunction() {
    header('Content-Encoding: UTF-8');
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=filename.csv');

    $output = fopen('php://output', 'w');
    fputs( $output, "\xEF\xBB\xBF" );

    foreach (rows as $row) {
      $description=$this->FixDescription($row['Description']);
      $id = $row['id'];
      $myrow .= $id . ',' . $description ."\n";
}

      fputcsv($output, mb_convert_encoding($myrow, 'UCS-2LE', 'UTF-8'));
      fclose($output);
}
   public function FixDescription($descr){
    $d = html_entity_decode($descr, ENT_QUOTES, 'UTF-8');
    $d = htmlspecialchars_decode($d);
    $d = str_replace(' ', ' ', $d);
    $d = strip_tags($d);
    $d = str_replace('&','_',$d);
    return $d;
  }
?>

When i download the generated file i get some rows correctly but for some rows description breaks and leaves blank rows and then prints and generally create a mess in my csv file. Any ideas of how not to break the content inside description field?

Body:
In my FixDescription function it was added the following line before return:

$d = preg_replace('/\r\n/','',$d);

This way ENTER is replaced and description is in one line


问:
Xamarin Android HybridWebView , how to change url dynamically
This is the rendering script</p>

```<code>using Android.Webkit;
using CustomRenderer;
using CustomRenderer.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer (typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace CustomRenderer.Droid
{
    public class HybridWebViewRenderer : ViewRenderer<HybridWebView, Android.Webkit.WebView>
    {
        const string JavaScriptFunction = "function invokeCSharpAction(data){jsBridge.invokeAction(data);}";

        const string JavaScriptFunction1 = "function invokeCSharpAction1(data){jsBridge.invokeAction1(data);}";

        protected override void OnElementChanged (ElementChangedEventArgs<HybridWebView> e)
        {
            base.OnElementChanged (e);

            if (Control == null) {
                var webView = new Android.Webkit.WebView (Forms.Context);
                webView.Settings.JavaScriptEnabled = true;
                SetNativeControl (webView);
            }
            if (e.OldElement != null) {
                Control.RemoveJavascriptInterface ("jsBridge");
                var hybridWebView = e.OldElement as HybridWebView;
                hybridWebView.Cleanup ();
            }
            if (e.NewElement != null) {
                Control.AddJavascriptInterface (new JSBridge (this), "jsBridge");
                Control.LoadUrl ("http://192.168.2.105:64518/login/index");

                InjectJS (JavaScriptFunction);
                InjectJS(JavaScriptFunction1);
            }
        }

        void InjectJS (string script)
        {
            if (Control != null) {
                Control.LoadUrl (string.Format ("javascript: {0}", script));
            }
        }
    }
}
</code>```

答:
You have to override OnElementPropertyChanged and apply your logic for changing urls there. For example following renderer snippet reacts to Source property change in Element:</p>

```<code>protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
        var element = sender as HybridWebView;
        if (e.PropertyName.Equals(HybridWebView.SourceProperty.PropertyName) && element != null)
        {
            Control?.StopLoading();
            var source = element.Source as UrlWebViewSource;
            Control?.Load((source?.Url ?? "").EndsWith("about:blank") ? "about:blank" : source?.Url, null);
        }
    }
</code>```

Body:
This is the rendering script

using Android.Webkit;
using CustomRenderer;
using CustomRenderer.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer (typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace CustomRenderer.Droid
{
    public class HybridWebViewRenderer : ViewRenderer<HybridWebView, Android.Webkit.WebView>
    {
        const string JavaScriptFunction = "function invokeCSharpAction(data){jsBridge.invokeAction(data);}";

        const string JavaScriptFunction1 = "function invokeCSharpAction1(data){jsBridge.invokeAction1(data);}";

        protected override void OnElementChanged (ElementChangedEventArgs<HybridWebView> e)
        {
            base.OnElementChanged (e);

            if (Control == null) {
                var webView = new Android.Webkit.WebView (Forms.Context);
                webView.Settings.JavaScriptEnabled = true;
                SetNativeControl (webView);
            }
            if (e.OldElement != null) {
                Control.RemoveJavascriptInterface ("jsBridge");
                var hybridWebView = e.OldElement as HybridWebView;
                hybridWebView.Cleanup ();
            }
            if (e.NewElement != null) {
                Control.AddJavascriptInterface (new JSBridge (this), "jsBridge");
                Control.LoadUrl ("http://192.168.2.105:64518/login/index");

                InjectJS (JavaScriptFunction);
                InjectJS(JavaScriptFunction1);
            }
        }

        void InjectJS (string script)
        {
            if (Control != null) {
                Control.LoadUrl (string.Format ("javascript: {0}", script));
            }
        }
    }
}

Body:
You have to override OnElementPropertyChanged and apply your logic for changing urls there. For example following renderer snippet reacts to Source property change in Element:

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
        var element = sender as HybridWebView;
        if (e.PropertyName.Equals(HybridWebView.SourceProperty.PropertyName) && element != null)
        {
            Control?.StopLoading();
            var source = element.Source as UrlWebViewSource;
            Control?.Load((source?.Url ?? "").EndsWith("about:blank") ? "about:blank" : source?.Url, null);
        }
    }


问:
Code Coverage with MSpec
Can anyone recommend a free code coverage tool for use with MSpec on VS2010/.NET4? Can TD.NET do this?</p>

答: TD.Net supports code coverage with MSpec (Test with -> Coverage or NCover). You can also use JetBrains dotCover, which also supports MSpec.</p>

Title: Code Coverage with MSpec


问:
Dagger 2: Cannot be provided without an @Provides-annotated method
I just started learning dagger2 and faced a strange issue that looks like a bug to me. Here's the module:

```<code>@Module
public class SimpleModule {

    @Provides
    Cooker providerCooker() {

        return new Cooker("tom", "natie");
    }
}
</code>```

Component:

```<code>@Component(modules = SimpleModule.class)
public interface SimpleComponent {

    void inject(DaggerTestActivity activity);

}
</code>```

Interface:

```<code>public interface CoffeeMaker {

    String makeCoffee();
}
</code>```

Implementation:

```<code>  public class SimpleMaker implements CoffeeMaker {

        Cooker mCooker;

        @Inject
        public SimpleMaker(Cooker cooker) {

            this.mCooker = cooker;

        }

        @Override
        public String makeCoffee() {

            return mCooker.makeCoffee();
        }
    }
</code>```

Cooker :

```<code>public class Cooker {

    String name;
    String coffeeKind;

    public Cooker(String name, String coffeeKind) {
        this.name = name;
        this.coffeeKind = coffeeKind;
    }

   public  String  makeCoffee() {

        return name + "make" + coffeeKind;
    }

}
</code>```

Coffee machine:

```<code>public class CoffeeMachine {

    CoffeeMaker mMaker;

    @Inject
    public CoffeeMachine(CoffeeMaker coffeeMaker) {

        this.mMaker = coffeeMaker;
    }

    public String makeCoffee() {

        return mMaker.makeCoffee();
    }
}
</code>```

Just it. I use it in the activity. Faced strange issue here:

```<code>    @Inject
    CoffeeMachine mCoffeeMachine;
</code>```

The error I'm getting from the Dagger 2 compiler is the following:

```<code>Error:(14, 10) com.wyyc.daggertest.CoffeeMaker cannot be provided without an @Provides-annotated method.
com.wyyc.zqqworkproject.DaggerTestActivity.mCoffeeMachine
[injected field of type: com.wyyc.daggertest.CoffeeMachine mCoffeeMachine]
com.wyyc.daggertest.CoffeeMachine.<init>(com.wyyc.daggertest.CoffeeMaker coffeeMaker)
</code>```

All this situation looks very strange, and I'd like to hear some input from more experienced Dagger 2 users.

答:
Your CoffeeMachine needs CoffeeMaker. And you have declared that Dagger will take care of providing that dependency to the CoffeeMachine by annotating the constructor with @Inject. But Dagger says:

CoffeeMaker cannot be provided without an @Provides-annotated method

Because you haven't specified anywhere how CoffeeMaker object should be created. @Injecting SimpleMaker is not enough, because SimpleMaker != CoffeeMaker. So, you have to specify explicitly, that when Dagger wants CoffeeMaker then provide him SimpleMaker.

Change your module to this:

```<code>@Module
public class SimpleModule {

    @Provides
    Cooker providerCooker() {
        return new Cooker("tom", "natie");
    }

    @Provides
    CoffeeMaker provideCoffeeMaker(Cooker cooker) {
        return new SimpleMaker(cooker);
    }

}
</code>```

Body:
I just started learning dagger2 and faced a strange issue that looks like a bug to me. Here's the module:

@Module
public class SimpleModule {

    @Provides
    Cooker providerCooker() {

        return new Cooker("tom", "natie");
    }
}

Component:

@Component(modules = SimpleModule.class)
public interface SimpleComponent {

    void inject(DaggerTestActivity activity);

}

Interface:

public interface CoffeeMaker {

    String makeCoffee();
}

Implementation:

  public class SimpleMaker implements CoffeeMaker {

        Cooker mCooker;

        @Inject
        public SimpleMaker(Cooker cooker) {

            this.mCooker = cooker;

        }

        @Override
        public String makeCoffee() {

            return mCooker.makeCoffee();
        }
    }

Cooker :

public class Cooker {

    String name;
    String coffeeKind;

    public Cooker(String name, String coffeeKind) {
        this.name = name;
        this.coffeeKind = coffeeKind;
    }

   public  String  makeCoffee() {

        return name + "make" + coffeeKind;
    }

}

Coffee machine:

public class CoffeeMachine {

    CoffeeMaker mMaker;

    @Inject
    public CoffeeMachine(CoffeeMaker coffeeMaker) {

        this.mMaker = coffeeMaker;
    }

    public String makeCoffee() {

        return mMaker.makeCoffee();
    }
}

Just it. I use it in the activity. Faced strange issue here:

    @Inject
    CoffeeMachine mCoffeeMachine;

The error I'm getting from the Dagger 2 compiler is the following:

Error:(14, 10) com.wyyc.daggertest.CoffeeMaker cannot be provided without an @Provides-annotated method.
com.wyyc.zqqworkproject.DaggerTestActivity.mCoffeeMachine
[injected field of type: com.wyyc.daggertest.CoffeeMachine mCoffeeMachine]
com.wyyc.daggertest.CoffeeMachine.<init>(com.wyyc.daggertest.CoffeeMaker coffeeMaker)

All this situation looks very strange, and I'd like to hear some input from more experienced Dagger 2 users.

Body:
Your CoffeeMachine needs CoffeeMaker. And you have declared that Dagger will take care of providing that dependency to the CoffeeMachine by annotating the constructor with @Inject. But Dagger says:

CoffeeMaker cannot be provided without an @Provides-annotated method

Because you haven't specified anywhere how CoffeeMaker object should be created. @Injecting SimpleMaker is not enough, because SimpleMaker != CoffeeMaker. So, you have to specify explicitly, that when Dagger wants CoffeeMaker then provide him SimpleMaker.

Change your module to this:

@Module
public class SimpleModule {

    @Provides
    Cooker providerCooker() {
        return new Cooker("tom", "natie");
    }

    @Provides
    CoffeeMaker provideCoffeeMaker(Cooker cooker) {
        return new SimpleMaker(cooker);
    }

}


问:
Find tuples with certain keywords
I have a tuple with 3grams that looks like this:

```<code>from nltk import ngrams
test_data = ["this is all test data", "this not"]

three_gram_list = []
for data in test_data:
 three_grams = ngrams(data.split(" "), 3)
 for gram in three_grams:
  three_gram_list.append(gram)
</code>```

What I would like to do is to create a function that checks for each 3-gram whether words are used in the same tuple. Therefore I did the following:

```<code>def create_specific_trigram(three_grams, parameters1, parameters2):

 condition1 = False
 condition2 = False

 for three in three_grams:
     for num in range(1, 3):
         if three[num] in parameters1:
            condition1 = True

      for num in range(1, 3):
          if three[num] in parameters2:
              condition2 = True

      if condition1 and condition2:
          print(three)
</code>```

However I run it now with some parameters:

```<code>parameters1 = ("test", "testing")
parameters2 = ("data", "datas")

for sentence in test_data:
  create_specific_trigram(three_grams, paramaters1, parameters2)
</code>```

I get the following output.

```<code>('all', 'test', 'data')
('all', 'test', 'data')
</code>```

However I am only looking for one output per sentence. So in this case:

```<code>('all', 'test', 'data')
</code>```

Any thoughts on what changes I should apply?

答:
When launching the function create_specific_trigram, you launch it for the same value of three_grams, independent from sentence.

Try this:

```<code>test_data = ["this is all test data", "this not"]
parameters1 = ("test", "testing")
parameters2 = ("data", "datas")

#============================================
#implementation of create_specific_trigram
# ...
#============================================

for sentence in test_data:
  three_grams = ngrams(sentence.split(" "), 3)
  create_specific_trigram(three_grams, paramaters1, parameters2)
</code>```

Title: Find tuples with certain keywords

Body:
I have a tuple with 3grams that looks like this:

from nltk import ngrams
test_data = ["this is all test data", "this not"]

three_gram_list = []
for data in test_data:
 three_grams = ngrams(data.split(" "), 3)
 for gram in three_grams:
  three_gram_list.append(gram)

What I would like to do is to create a function that checks for each 3-gram whether words are used in the same tuple. Therefore I did the following:

def create_specific_trigram(three_grams, parameters1, parameters2):

 condition1 = False
 condition2 = False

 for three in three_grams:
     for num in range(1, 3):
         if three[num] in parameters1:
            condition1 = True

      for num in range(1, 3):
          if three[num] in parameters2:
              condition2 = True

      if condition1 and condition2:
          print(three)

However I run it now with some parameters:

parameters1 = ("test", "testing")
parameters2 = ("data", "datas")

for sentence in test_data:
  create_specific_trigram(three_grams, paramaters1, parameters2)

I get the following output.

('all', 'test', 'data')
('all', 'test', 'data')

However I am only looking for one output per sentence. So in this case:

('all', 'test', 'data')

Any thoughts on what changes I should apply?

Body:
When launching the function create_specific_trigram, you launch it for the same value of three_grams, independent from sentence.

Try this:

test_data = ["this is all test data", "this not"]
parameters1 = ("test", "testing")
parameters2 = ("data", "datas")

#============================================
#implementation of create_specific_trigram
# ...
#============================================

for sentence in test_data:
  three_grams = ngrams(sentence.split(" "), 3)
  create_specific_trigram(three_grams, paramaters1, parameters2)


问:
Remove html tags except
 or
 tags with javascript
I want to remove all the html tags except
 or
 tags from a string using javascript.
I have seen many questions like this but their answers will remove all the html tags including
 and
 tags.

Does anyone knows a regex to do this?

答:
To expand h2ooooooo Answer to include leading spaces and be case insenctive you could use</p>

```<code>/<(?!\s*br\s*\/?)[^>]+>/gi
</code>```

Body:
To expand h2ooooooo Answer to include leading spaces and be case insenctive you could use

/<(?!\s*br\s*\/?)[^>]+>/gi


问:
Draw a map of a specific country with leaflet
I would like to use the package leaflet with R to draw a map of a specific countries such as Italy, Spain, etc.

I checked the basic examples with the function setView() and I tried to give a vector of two values for the arg of latitude and longitutde :

```<code>m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  setView(lng=c(46.00,48.00), lat=c(2.00,6.00), zoom = 4)
m  # Print the map (map is not centered on a country, it's just a test)
</code>```

But I will never be able to have a specific country on my screen such as the result of this function :

```<code>library(maps)
map('italy', fill = TRUE, col = 1:10)
</code>```

In the end, I just want to draw some points by geographically locating them on my maps (with latitude and longtitude)

Is it possible or is the package maps is adequate for this task (even though I didn't find a way to zoom in) ?

答:
You can just use the polygons retreived from maps. Of course one can use any other suitable source, just like @JanLauGe mentioned it.

After you have the polygons of the specific country you can feed them to Leafet after converting them to SpatialPolygonsDataFrame. You can also create a mask, if you want to display just the area of interest.

Naturally, after that you can easily add any point or marker with the standard Leaflet methods, like addCircleMarkers( lng, lat ).

```<code>library(ggmap)
library(leaflet)
library(magrittr)
library(maps)
library(maptools)
library(raster)
library(rgeos)
library(sp)

country   <- 'italy';
zoomLevel <- 6;

# Get the map ( class is map )
ita.map <- map( country, fill = TRUE, col = 1, plot = F );

# Get the geo center for lazyness
ita.center <- geocode( "italy" );

# Extract the names from ita.map.
# e.g. "Trapani:I. Le Egadi:I. Marettimo" -> "Trapani"
# note: any other solution is fine, because we don't really need them, but they
# can be useful later
ita.map.ids <- sapply( strsplit( ita.map$names, ':' ), function(x) x[1] );
# Convert our map object to SpatialPolygons
ita.sp <- map2SpatialPolygons( ita.map, IDs=ita.map.ids,
    proj4string=CRS("+proj=longlat +datum=WGS84"))

# Note: if you only need a unified polygon, it can be achieved by fortify
# ita.sp.df <- fortify( ita.sp );

# Finally convert our SpatialPolygons to SpatialPolygonsDataFrame
tmp.id.df <- data.frame( ID = names(ita.sp) );
rownames( tmp.id.df ) <- names( ita.sp );
ita.spdf <- SpatialPolygonsDataFrame( ita.sp, tmp.id.df );

# Visualize
l.ita.map <- leaflet( ita.spdf ) %>%
    setView(lng = ita.center$lon, lat = ita.center$lat, zoom = zoomLevel ) %>%
    addTiles() %>%
    addPolygons( data = ita.spdf, weight = 1, fillColor = "blue", fillOpacity = 0.5 );

l.ita.map
</code>```

```<code>####### Alternatively if a mask if needed #######

# Get a plane of the world
wld.sp <- rasterToPolygons( raster(ncol = 1, nrow = 1, crs = proj4string(ita.sp) ) );
# Cut our country polygon from the plane to get our target mask
ita.sp.mask <- gDifference( wld.sp, ita.sp );

# Convert our ita.sp.mask (SpatialPolygons) to SpatialPolygonsDataFrame
tmp.id.df <- data.frame( ID = "1" );
rownames( tmp.id.df ) <- names( ita.sp.mask );
ita.mask.spdf <- SpatialPolygonsDataFrame( ita.sp.mask, tmp.id.df );

# Coordinates of Rome
ita.rome.center <- geocode( "Rome, italy" );

# Visualize
l.ita.mask.map <- leaflet( ita.mask.spdf ) %>%
    setView( lng = ita.center$lon, lat = ita.center$lat, zoom = zoomLevel ) %>%
    addTiles() %>%
    addPolygons( data = ita.mask.spdf, fillColor = "white", fillOpacity = 1.0, color = "black", weight = 1 ) %>%
addCircleMarkers(lng = ita.rome.center$lon, lat = ita.rome.center$lat );

l.ita.mask.map;
</code>```

Thanks for @fdetsch for his suggestion!

Body:
I would like to use the package leaflet with R to draw a map of a specific countries such as Italy, Spain, etc.

I checked the basic examples with the function setView() and I tried to give a vector of two values for the arg of latitude and longitutde :

m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  setView(lng=c(46.00,48.00), lat=c(2.00,6.00), zoom = 4)
m  # Print the map (map is not centered on a country, it's just a test)

But I will never be able to have a specific country on my screen such as the result of this function :

library(maps)
map('italy', fill = TRUE, col = 1:10)

In the end, I just want to draw some points by geographically locating them on my maps (with latitude and longtitude)

Is it possible or is the package maps is adequate for this task (even though I didn't find a way to zoom in) ?

Body:
You can just use the polygons retreived from maps. Of course one can use any other suitable source, just like @JanLauGe mentioned it.

After you have the polygons of the specific country you can feed them to Leafet after converting them to SpatialPolygonsDataFrame. You can also create a mask, if you want to display just the area of interest.

Naturally, after that you can easily add any point or marker with the standard Leaflet methods, like addCircleMarkers( lng, lat ).

library(ggmap)
library(leaflet)
library(magrittr)
library(maps)
library(maptools)
library(raster)
library(rgeos)
library(sp)

country   <- 'italy';
zoomLevel <- 6;

# Get the map ( class is map )
ita.map <- map( country, fill = TRUE, col = 1, plot = F );

# Get the geo center for lazyness
ita.center <- geocode( "italy" );

# Extract the names from ita.map.
# e.g. "Trapani:I. Le Egadi:I. Marettimo" -> "Trapani"
# note: any other solution is fine, because we don't really need them, but they
# can be useful later
ita.map.ids <- sapply( strsplit( ita.map$names, ':' ), function(x) x[1] );
# Convert our map object to SpatialPolygons
ita.sp <- map2SpatialPolygons( ita.map, IDs=ita.map.ids,
    proj4string=CRS("+proj=longlat +datum=WGS84"))

# Note: if you only need a unified polygon, it can be achieved by fortify
# ita.sp.df <- fortify( ita.sp );

# Finally convert our SpatialPolygons to SpatialPolygonsDataFrame
tmp.id.df <- data.frame( ID = names(ita.sp) );
rownames( tmp.id.df ) <- names( ita.sp );
ita.spdf <- SpatialPolygonsDataFrame( ita.sp, tmp.id.df );

# Visualize
l.ita.map <- leaflet( ita.spdf ) %>%
    setView(lng = ita.center$lon, lat = ita.center$lat, zoom = zoomLevel ) %>%
    addTiles() %>%
    addPolygons( data = ita.spdf, weight = 1, fillColor = "blue", fillOpacity = 0.5 );

l.ita.map

####### Alternatively if a mask if needed #######

# Get a plane of the world
wld.sp <- rasterToPolygons( raster(ncol = 1, nrow = 1, crs = proj4string(ita.sp) ) );
# Cut our country polygon from the plane to get our target mask
ita.sp.mask <- gDifference( wld.sp, ita.sp );

# Convert our ita.sp.mask (SpatialPolygons) to SpatialPolygonsDataFrame
tmp.id.df <- data.frame( ID = "1" );
rownames( tmp.id.df ) <- names( ita.sp.mask );
ita.mask.spdf <- SpatialPolygonsDataFrame( ita.sp.mask, tmp.id.df );

# Coordinates of Rome
ita.rome.center <- geocode( "Rome, italy" );

# Visualize
l.ita.mask.map <- leaflet( ita.mask.spdf ) %>%
    setView( lng = ita.center$lon, lat = ita.center$lat, zoom = zoomLevel ) %>%
    addTiles() %>%
    addPolygons( data = ita.mask.spdf, fillColor = "white", fillOpacity = 1.0, color = "black", weight = 1 ) %>%
addCircleMarkers(lng = ita.rome.center$lon, lat = ita.rome.center$lat );

l.ita.mask.map;

Thanks for @fdetsch for his suggestion!


问:
Heavy computations in analytic functions and linear algebra
For non-standard computations in optical wavefront propagation I need to deal with very large matrices (about 10^6*10^6 entries) which are not sparse or in any way "reducible".

The code roughly reads as follows:

```<code>import numpy as np

x = np.linspace(-Nx / 2, Nx / 2 - 1, Nx) * deltax
q = np.linspace(-Nq / 2, Nq / 2 - 1, Nq) * deltaq
xg, qg =np.meshgrid(x, q)

kernel = np.exp(1j * 2 * np.pi * qg * xig)

u = np.dot(kernel, u0)
</code>```

Here, Nx, Nq are large numbers, deltax, deltaq are scaling factors, and u0 is a suitable vector. In fact, the kernel is not of the above Fourier type, but more complicated.

Of course, the matrix is too large for RAM, so the whole procedure has to be divided into smaller blocks. In fact, I compute blocks of rows of the kernel and then do the corresponding dot-product which gives blocks of u. However, I didn't include this procedure in the code above in order to keep the focus on the main problem.

There are two time consuming operations here:

Computation of the kernel

Matrix vector multiplication

So far, I use numexpr to speed up the kernel computation. Hence, this part makes use of the multi-core architecture (current machine: AMD FX 8320, 8 cores, 16 GB RAM). However, the matrix vector multiplication does not. Also, I didn't compile numpy to adjust it to my machine. This way, one go (involving several hundreds of such operations) takes several days!

I guess, further parallelisation is a possibility to reduce computation time. However, I'm a complete beginner in parallelisation. Googling this topic leads to a whole zoo of possibilites and (as a beginner) it's hard to judge which route to follow.

Could you please recommend some speedup procedures (in particular, involving parallelisation) that are accessible for a BEGINNER?

答:
Can you do something like this?

```<code>x = np.linspace(-Nx / 2, Nx / 2 - 1, Nx) * deltax
q = np.linspace(-Nq / 2, Nq / 2 - 1, Nq) * deltaq
u = np.empty_like(u0)
for i in np.arange(Nx).flat:
    u[i] = np.dot(np.exp(1j * 2 * np.pi * q * x[i]), u0)
</code>```

It will be slower than a vectorized (since you're computing your kernel line by line) but shouldn't overflow your memory

Body:
For non-standard computations in optical wavefront propagation I need to deal with very large matrices (about 10^6*10^6 entries) which are not sparse or in any way "reducible".

The code roughly reads as follows:

import numpy as np

x = np.linspace(-Nx / 2, Nx / 2 - 1, Nx) * deltax
q = np.linspace(-Nq / 2, Nq / 2 - 1, Nq) * deltaq
xg, qg =np.meshgrid(x, q)

kernel = np.exp(1j * 2 * np.pi * qg * xig)

u = np.dot(kernel, u0)

Here, Nx, Nq are large numbers, deltax, deltaq are scaling factors, and u0 is a suitable vector. In fact, the kernel is not of the above Fourier type, but more complicated.

Of course, the matrix is too large for RAM, so the whole procedure has to be divided into smaller blocks. In fact, I compute blocks of rows of the kernel and then do the corresponding dot-product which gives blocks of u. However, I didn't include this procedure in the code above in order to keep the focus on the main problem.

There are two time consuming operations here:

Computation of the kernel

Matrix vector multiplication

So far, I use numexpr to speed up the kernel computation. Hence, this part makes use of the multi-core architecture (current machine: AMD FX 8320, 8 cores, 16 GB RAM). However, the matrix vector multiplication does not. Also, I didn't compile numpy to adjust it to my machine. This way, one go (involving several hundreds of such operations) takes several days!

I guess, further parallelisation is a possibility to reduce computation time. However, I'm a complete beginner in parallelisation. Googling this topic leads to a whole zoo of possibilites and (as a beginner) it's hard to judge which route to follow.

Could you please recommend some speedup procedures (in particular, involving parallelisation) that are accessible for a BEGINNER?

Body:
Can you do something like this?

x = np.linspace(-Nx / 2, Nx / 2 - 1, Nx) * deltax
q = np.linspace(-Nq / 2, Nq / 2 - 1, Nq) * deltaq
u = np.empty_like(u0)
for i in np.arange(Nx).flat:
    u[i] = np.dot(np.exp(1j * 2 * np.pi * q * x[i]), u0)

It will be slower than a vectorized (since you're computing your kernel line by line) but shouldn't overflow your memory


问:
Jenkins Active Choices Plugin input text box don't return anything. Why?
This is my actual configuration

When I type the desired domain there is nothing in domain's variable. Any idea what's going on? I'm totally newbie with groovy script.

Thanks.

BTW, my little and totally useless groovy script:

```<code>if (Environment.equals("pro")){
  inputBox="<input type='text'>"
  return inputBox
}
</code>```

答:
So I was struggling with the same thing just now and came upon this question so might as well post the solution that worked for me :)

My paramater name in jenkins is "Partner"

My groovy script:

```<code>inputBox = "<input name='value' class='setting-input' type='text'>"
return inputBox
</code>```

It seems that the value inputed is stored in a variable that has the paramater name;
Soo... if you wana use the Value inputed just use the variable like this ${Partner} or %Partner% (depending on where you want to use it);

Hope it helps someone :)

Body:
This is my actual configuration

When I type the desired domain there is nothing in domain's variable. Any idea what's going on? I'm totally newbie with groovy script.

Thanks.

BTW, my little and totally useless groovy script:

if (Environment.equals("pro")){
  inputBox="<input type='text'>"
  return inputBox
}

Body:
So I was struggling with the same thing just now and came upon this question so might as well post the solution that worked for me :)

My paramater name in jenkins is "Partner"

My groovy script:

inputBox = "<input name='value' class='setting-input' type='text'>"
return inputBox

It seems that the value inputed is stored in a variable that has the paramater name;
Soo... if you wana use the Value inputed just use the variable like this ${Partner} or %Partner% (depending on where you want to use it);

Hope it helps someone :)


问:
MediaCapture.FramesSources and MediaFrameSourceGroup.FindAllAsync() Broken
I have a UWP application which uses the MediaCapture API but since updating to the latest Windows mobile build (slow ring and fast ring), the API is no longer working. This has also been reported by multiple customers.

The CameraFrames UWP sample also crashes showing the error is not in the application code.

Specifically:

MediaFrameSourceGroup.FindAllAsync() does not return any groups.

Also, _mediaCapture.FramesSources has no items.

Any ideas?

EDIT: This is not reproducible on the latest SDK emulator, but on a later build on multiple physical devices (e.g. Lumia 950XL)

答:
This is a bug in the latest Creators Update builds.

Now raised as an internal bug with Microsoft.

https://github.com/Microsoft/Windows-universal-samples/issues/612


问:
Javascript module with requirejs with local path
I am building a JavaScript module. Can load the first file in the module no problem. From there I want to load other files, but requirejs follows the path from the index. I want the functions in the module to be available in global scope. The structure is like this:

index.html:

```<code><script src="scripts/app.js"></script>
</code>```

app.js:

```<code>requirejs([ "../../modules/foo" ], function(util) {
});
</code>```

modules/foo.js:

```<code>requirejs([ "bar" ], function(util) {
});
</code>```

That gives the error: ERR_FILE_NOT_FOUND, well, yes, if you look from app.js you will not find it. How to force requirejs to load from the module?

These posts are probably related, but I can't wrap my head around it:

RequireJS relative paths

Using require with relative paths

答: This is the way I found around this: Create a minified && uglified && required file, where all other files are loaded into. Also know as the RequireJS Optimizer.</p>

Body:
I am building a JavaScript module. Can load the first file in the module no problem. From there I want to load other files, but requirejs follows the path from the index. I want the functions in the module to be available in global scope. The structure is like this:

index.html:

app.js:

requirejs([ "../../modules/foo" ], function(util) {
});

modules/foo.js:

requirejs([ "bar" ], function(util) {
});

That gives the error: ERR_FILE_NOT_FOUND, well, yes, if you look from app.js you will not find it. How to force requirejs to load from the module?

These posts are probably related, but I can't wrap my head around it:

RequireJS relative paths

Using require with relative paths


问:
printing with java in linux
Does anyone know any good tutorial or howto how to print with java application in linux? In search but i can not find any good tutorial.

Thx

答: Have you tried / seen http://download.oracle.com/javase/1.4.2/docs/api/javax/print/package-summary.html</p>

Title: printing with java in linux


问:
Java concurrent access of ArrayList
After the following code

```<code>ArrayList<String> foo, bar, test;
foo = new ArrayList<String>(Arrays.asList("foo"));
bar = new ArrayList<String>(Arrays.asList("bar"));
test = new ArrayList<String>(Arrays.asList("test"));
</code>```

Thread 1 runs:

```<code>foo = new ArrayList<String>(bar);
</code>```

Thread 2 runs:

```<code>bar = new ArrayList<String>(test);
</code>```

Can this cause an exception if Thread 2 changes value of bar while it is being used by Thread 1?

答:
You won't get a concurrent modification exception, since the list instances are never mutated. Only references are exchanged.

However you still have a data race:

Either the assignment in Thread1 runs first. Thread1 will capture the initial bar object and create a new `foo´ which is the copy of that.

Or the assignment in Thread2 will run first, which means it creates a new list which is stored in the bar reference, and when Thread1 runs later on it will end up with a copy of that one, which itself is a copy of the test list.

Title: Java concurrent access of ArrayList

Body:
After the following code

ArrayList<String> foo, bar, test;
foo = new ArrayList<String>(Arrays.asList("foo"));
bar = new ArrayList<String>(Arrays.asList("bar"));
test = new ArrayList<String>(Arrays.asList("test"));

Thread 1 runs:

foo = new ArrayList<String>(bar);

Thread 2 runs:

bar = new ArrayList<String>(test);

Can this cause an exception if Thread 2 changes value of bar while it is being used by Thread 1?


问:
Background image not showing in browser
I have a question. I am pretty new to coding and I am trying to make my own website. I want to add a background image to my website but the image is not showing up. I have tried several things but without luck. I have added code of what I have done in my html file. I hope someone can help me with this and point me in the right direction.

This is what my html file looks like:

<!DOCTYPE html>

     <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
     <title>Lusofly Virtual</title>

Lusofly Virtual

HOME

COMMUNITY

CONTACT

PILOT AREA

```

Thanks in advance

答:
Give your background Image in your body tag

Here is an example below:

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
  <title>Lusofly Virtual</title>

Lusofly Virtual

HOME

COMMUNITY

CONTACT

PILOT AREA

```

Title: Background image not showing in browser

Body:
I have a question. I am pretty new to coding and I am trying to make my own website. I want to add a background image to my website but the image is not showing up. I have tried several things but without luck. I have added code of what I have done in my html file. I hope someone can help me with this and point me in the right direction.

This is what my html file looks like:

<!DOCTYPE html>

     <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
     <title>Lusofly Virtual</title>

Lusofly Virtual

HOME

COMMUNITY

CONTACT

PILOT AREA

Thanks in advance

Body:
Give your background Image in your body tag

Here is an example below:

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
  <title>Lusofly Virtual</title>
  <style type="text/css">
    body {
      background-color: gray;

      background-image: url('http://placehold.it/600x200.jpg');
      background-repeat: no-repeat;
      background-size: contain;

    }
    .header{ height:1000px} /* Demo height*/
  </style>
</head>

<body>

  <div class="header">

    <div class="container">

      <div class="logo">
        <h1><a href="#">Lusofly Virtual</a></h1>
      </div>

      <div class="nav">
        <ul>
          <li><a href="#">HOME</a></li>
          <li><a href="#">COMMUNITY</a></li>
          <li><a href="#">CONTACT</a></li>
          <li><a href="#">PILOT AREA</a></li>
        </ul>
      </div>
    </div>
  </div>
</body>

</html>


问:
Filter a two dimensional array in table view for searching in Swift
I have a two dimensional array

```<code>fileprivate var Food : [[FoodModel]] = [[]]

Food = [["Apple","Mango"],["Chocolate","Biscuit"]]
</code>```

and two sections

```<code>let section = ["Fruits","Dry Food"]
</code>```

for a table view. It's displaying the value nicely. Now I added a search bar for searching value from Food. My problem is that I can't filter Food by my searching keyword.

```<code>Food.filter({}) //what to write here?
self.tableView.reloadData()
</code>```

答:
Try this </p>

```<code>let searchString = "Choco"

var result = Food.filter { (dataArray:[FoodModel]) -> Bool in
    return dataArray.filter({ (FoodModel) -> Bool in
        return FoodModel.containsString(searchString)
    }).count > 0
}
</code>```

Body:
I have a two dimensional array

fileprivate var Food : [[FoodModel]] = [[]]

Food = [["Apple","Mango"],["Chocolate","Biscuit"]]

and two sections

let section = ["Fruits","Dry Food"]

for a table view. It's displaying the value nicely. Now I added a search bar for searching value from Food. My problem is that I can't filter Food by my searching keyword.

Food.filter({}) //what to write here?
self.tableView.reloadData()

Body:
Try this

let searchString = "Choco"

var result = Food.filter { (dataArray:[FoodModel]) -> Bool in
    return dataArray.filter({ (FoodModel) -> Bool in
        return FoodModel.containsString(searchString)
    }).count > 0
}


问:
Excel VBA - SUM cells in column before blank cell
I have Excel Offer Sheet with positions and macro which transfer rows from this sheet to second sheet when value in B column is different than 0. It also add empty row after word "SUMA".

```<code>Option Explicit
Dim MyWorkbook As Workbook
Dim MyWorksheet As Worksheet
Dim MyOutputWorksheet As Worksheet

Sub PullData()
Set MyWorkbook = Workbooks(ActiveWorkbook.Name)
Set MyWorksheet = MyWorkbook.Sheets("Roboczy")
Set MyOutputWorksheet = MyWorkbook.Sheets("Oferta")

    Dim myValue As Long
    Dim RowPointer As Long

    For RowPointer = 1 To MyWorksheet.Cells(Rows.Count, "B").End(xlUp).Row
        If MyWorksheet.Range("B" & RowPointer).Value > 0 And MyWorksheet.Range("B" & RowPointer).Value <> "" Then
            If MyOutputWorksheet.Cells(Rows.Count, "B").End(xlUp).Row > 155 Then
                Exit Sub
            End If
            MyWorksheet.Range(("A" & RowPointer) & ":D" & RowPointer).Copy Destination:=MyOutputWorksheet.Range("A" & MyOutputWorksheet.Cells(Rows.Count, "B").End(xlUp).Row + 1)
        End If
    Next RowPointer

     Dim b As Range
For Each b In MyOutputWorksheet.Range("A1:A200")
 If b.Value Like "*SUMA*" Then
 b.Offset(1, 0).EntireRow.Insert
 End If
Next b

End Sub
</code>```

I miss some code which would clear #ADR! and sum up all cells in each section.
More details -> Image of Excel sheet

答:
This is a pure guess, as I can't see the Roboczy sheet, but I think you're getting what I would call a #REF! error. Likely caused by the source sheet containing a formula referencing a range that is not valid when translated to the destination sheet. Simplest solution I can think of is to Paste/Special Values instead of a general Paste to remove the formulae:
Replace your one paste line with: </p>

```<code>MyWorksheet.Range(("A" & RowPointer) & ":D" & RowPointer).Copy
MyOutputWorksheet.Range("A" & Cells(MyOutputWorksheet.Rows.Count, "B").End(xlUp).Row + 1).PasteSpecial xlPasteValues
</code>```

Body:
I have Excel Offer Sheet with positions and macro which transfer rows from this sheet to second sheet when value in B column is different than 0. It also add empty row after word "SUMA".

Option Explicit
Dim MyWorkbook As Workbook
Dim MyWorksheet As Worksheet
Dim MyOutputWorksheet As Worksheet

Sub PullData()
Set MyWorkbook = Workbooks(ActiveWorkbook.Name)
Set MyWorksheet = MyWorkbook.Sheets("Roboczy")
Set MyOutputWorksheet = MyWorkbook.Sheets("Oferta")

    Dim myValue As Long
    Dim RowPointer As Long

    For RowPointer = 1 To MyWorksheet.Cells(Rows.Count, "B").End(xlUp).Row
        If MyWorksheet.Range("B" & RowPointer).Value > 0 And MyWorksheet.Range("B" & RowPointer).Value <> "" Then
            If MyOutputWorksheet.Cells(Rows.Count, "B").End(xlUp).Row > 155 Then
                Exit Sub
            End If
            MyWorksheet.Range(("A" & RowPointer) & ":D" & RowPointer).Copy Destination:=MyOutputWorksheet.Range("A" & MyOutputWorksheet.Cells(Rows.Count, "B").End(xlUp).Row + 1)
        End If
    Next RowPointer

     Dim b As Range
For Each b In MyOutputWorksheet.Range("A1:A200")
 If b.Value Like "*SUMA*" Then
 b.Offset(1, 0).EntireRow.Insert
 End If
Next b

End Sub

I miss some code which would clear #ADR! and sum up all cells in each section.
More details -> Image of Excel sheet

Body:
This is a pure guess, as I can't see the Roboczy sheet, but I think you're getting what I would call a #REF! error. Likely caused by the source sheet containing a formula referencing a range that is not valid when translated to the destination sheet. Simplest solution I can think of is to Paste/Special Values instead of a general Paste to remove the formulae:
Replace your one paste line with:

MyWorksheet.Range(("A" & RowPointer) & ":D" & RowPointer).Copy
MyOutputWorksheet.Range("A" & Cells(MyOutputWorksheet.Rows.Count, "B").End(xlUp).Row + 1).PasteSpecial xlPasteValues


问:
How to select the last inserted records by date, time, minutes and seconds
I have 4 records with the same CID# 201. I'm trying to get the last updated records by the second.  The issue it is returning all 4 of the records. I would like to return the last updated records by CID# 201. Here is my code.

```<code> SELECT CID, to_char( max( UPDATED_DATE ), 'yyyy-mm-dd hh24:mi:ss' )
 FROM mytable
 WHERE CID = 201;
</code>```

This is the return records. NOT DESIRED

```<code>**`CID#`|   `UPDATED_DATE`**
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:29:36`
 `201` | `03/30/2017 7:29:36`
</code>```

This is what I want returned. YES DESIRED

```<code>**`CID`|   `UPDATED_DATE`**
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:30:22`
</code>```

What am I missing here?

答:
If you're using newer Oracle versions, you can use FETCH FIRST WITH TIES!

```<code>SELECT CID, to_char(UPDATED_DATE, 'yyyy-mm-dd hh24:mi:ss') chardate
FROM mytable
WHERE CID = 201
order by chardate desc
fetch first 1 row with ties
</code>```

Body:
I have 4 records with the same CID# 201. I'm trying to get the last updated records by the second.  The issue it is returning all 4 of the records. I would like to return the last updated records by CID# 201. Here is my code.

 SELECT CID, to_char( max( UPDATED_DATE ), 'yyyy-mm-dd hh24:mi:ss' )
 FROM mytable
 WHERE CID = 201;

This is the return records. NOT DESIRED

**`CID#`|   `UPDATED_DATE`**
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:29:36`
 `201` | `03/30/2017 7:29:36`

This is what I want returned. YES DESIRED

**`CID`|   `UPDATED_DATE`**
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:30:22`

What am I missing here?

Body:
If you're using newer Oracle versions, you can use FETCH FIRST WITH TIES!

SELECT CID, to_char(UPDATED_DATE, 'yyyy-mm-dd hh24:mi:ss') chardate
FROM mytable
WHERE CID = 201
order by chardate desc
fetch first 1 row with ties


问:
is it possible to make nant run a publish on web application project
is it possible to make nant run a publish on mvc project or a good old web application project

and after the publish make nant FTP the files to the web server

UPDATE: found the solution to the ftp problem

Nant ftp task thanks Paco

what i mean by publich

is there a command line application or nant task that can public like visual studio publish...

答:
The visual studio publish command rebuilds your solution and then copies the files in the solution directory to a new directory. I use the following target to do almost the same:

```<code><target name="copyToPublish">
    <delete dir="${dir.publish}" />
    <mkdir dir="${dir.publish}" />
    <mkdir dir="${dir.publish}\wwwroot"/>
    <copy todir="${dir.publish}\wwwroot" includeemptydirs="false">
      <fileset basedir="${website.dir}">
        <exclude name="**/*.cs"/>
        <exclude name="**/*.pdb"/>
        <exclude name="**/*.csproj*"/>
        <exclude name="**/obj/**"/>
        <include name="**/*.*"/>
      </fileset>
    </copy>
    <mkdir dir="${dir.publish}\database"/>
    <copy todir="${dir.publish}\database" includeemptydirs="false">
      <fileset basedir="${dir.databasescripts}">
        <include name="**/*.sql" />
      </fileset>
    </copy>
    <xmlpoke
            file="${dir.publish}\wwwroot\Web.config"
            xpath="/configuration/system.web/compilation/@debug"
            value="false" />
    <xmlpoke
            file="${dir.publish}\wwwroot\Web.config"
            xpath="/configuration/system.web/trace/@enabled"
            value="false" />
    <move file="${dir.publish}\wwwroot\Web.config" tofile="${dir.publish}\wwwroot\Release.config" overwrite="true" />
    <delete file="${dir.publish}\wwwroot\Web.config" />
</target>
</code>```

Before this target you have to run the normal build procedure of course.

OwnerDisplayName: Subnus

LastEditorDisplayName: Subnus

Body:
The visual studio publish command rebuilds your solution and then copies the files in the solution directory to a new directory. I use the following target to do almost the same:

<target name="copyToPublish">
    <delete dir="${dir.publish}" />
    <mkdir dir="${dir.publish}" />
    <mkdir dir="${dir.publish}\wwwroot"/>
    <copy todir="${dir.publish}\wwwroot" includeemptydirs="false">
      <fileset basedir="${website.dir}">
        <exclude name="**/*.cs"/>
        <exclude name="**/*.pdb"/>
        <exclude name="**/*.csproj*"/>
        <exclude name="**/obj/**"/>
        <include name="**/*.*"/>
      </fileset>
    </copy>
    <mkdir dir="${dir.publish}\database"/>
    <copy todir="${dir.publish}\database" includeemptydirs="false">
      <fileset basedir="${dir.databasescripts}">
        <include name="**/*.sql" />
      </fileset>
    </copy>
    <xmlpoke
            file="${dir.publish}\wwwroot\Web.config"
            xpath="/configuration/system.web/compilation/@debug"
            value="false" />
    <xmlpoke
            file="${dir.publish}\wwwroot\Web.config"
            xpath="/configuration/system.web/trace/@enabled"
            value="false" />
    <move file="${dir.publish}\wwwroot\Web.config" tofile="${dir.publish}\wwwroot\Release.config" overwrite="true" />
    <delete file="${dir.publish}\wwwroot\Web.config" />
</target>

Before this target you have to run the normal build procedure of course.

OwnerDisplayName: Paco


问:
Which bluetooth connection type is the right one to choose?
I have a Samsung Gear S3 (running Tizen) with a selfmade web-app for logging Data from the heartrate monitor as well as from the Pedometer to a .csv-file. I would like to send each line in the .csv via Bluetooth to an UWP App. As I am a total beginner with C# and Bluetooth connections, I am struggling to understand the basic concepts of the different connection modes.

So here my question: In my specific usecase, would I choose RFCOMM, GATT or LE?

Thanks in advance.

答:
Seems a vast Issue. I would suggest you to check out this post for now:

GATT over SPP profile for bluetooth communication?


问:
Unix - How to print last lines of a file and each time ignore the first same character?
I am using following command to print the content of a file at the bottom

```<code>tail --lines=+$(($LINENO + 1)) ~/.zshrc
</code>```

After that command follows a table showing information about my file.
This information has to be written with # in front of each line so it's a comment.

Therefore the print shows the #, too.

How do I ignore the first character in each line when printing the content after my tail command ?

答:
Just pipe to a sed:

```<code>tail --lines=+$(($LINENO + 1)) ~/.zshrc | sed 's/^[[:blank:]]*#//'
</code>```

Body:
I am using following command to print the content of a file at the bottom

tail --lines=+$(($LINENO + 1)) ~/.zshrc

After that command follows a table showing information about my file.
This information has to be written with # in front of each line so it's a comment.

Therefore the print shows the #, too.

How do I ignore the first character in each line when printing the content after my tail command ?

Body:
Just pipe to a sed:

tail --lines=+$(($LINENO + 1)) ~/.zshrc | sed 's/^[[:blank:]]*#//'


问:
Ngrx: populate success dispatched actions on component
I'm dispatching an ADD_SOURCE action from my component that when it success dispatches another ADD_SOURCE_SUCCESS:

```<code>this.store$
  .select(fromRoot.getUserState)
  .filter(user => user.id != null && user.logged)
  .takeUntil(this.componentDestroyed$)
  .do(user => this.store$.dispatch({type: 'ADD_SOURCE', payload: user.username}))
  .subscribe();
</code>```

This is the effect that returns the ADD_SOURCE_SUCCESS according to a net call:

```<code>@Effect({ dispatch: true })
  addSource$: Observable<Action> = this.actions$
    .ofType('ADD_SOURCE')
    .switchMap(
      (action: Action) =>
        this.userService.addCard(action.payload.username, action.payload.token)
          .map((card: CardDTO) => {
            return <Action>{
              type: 'ADD_SOURCE_SUCCESS',
              payload: <ICard>{ ... }
            };
          })
          .catch(_ => {
            return Observable.of(<Action>{ type: 'ADD_SOURCE_FAILED', payload: { }});
          }));
</code>```

So, then a new ADD_SOURCE_SUCCESS is dispatched on my reducer:

```<code>private static saveSourceSuccess(sourcesRdx, type, payload) {
    return <ISourceRedux>{
        ids: [ ...sourcesRdx.ids, payload.id ],
        entities: Object.assign({}, sourcesRdx.entities, {[payload.id]: payload}),
        selectedIds: sourcesRdx.selectedIds,
        editingSource: null
    };
}
</code>```

Nevertheless, I don't quite figure out how to say on my component that the operation has been success and do one thing or another one...

Any ideas?

答:
in your reducer, you should also handle the success & fail errors, set the store with an error message or whatever you need as data, and make a selector on it. Then the ui should subscribe to this new selector and you ll be notified
check this chapter
selectors</p>

Body:
I'm dispatching an ADD_SOURCE action from my component that when it success dispatches another ADD_SOURCE_SUCCESS:

this.store$
  .select(fromRoot.getUserState)
  .filter(user => user.id != null && user.logged)
  .takeUntil(this.componentDestroyed$)
  .do(user => this.store$.dispatch({type: 'ADD_SOURCE', payload: user.username}))
  .subscribe();

This is the effect that returns the ADD_SOURCE_SUCCESS according to a net call:

@Effect({ dispatch: true })
  addSource$: Observable<Action> = this.actions$
    .ofType('ADD_SOURCE')
    .switchMap(
      (action: Action) =>
        this.userService.addCard(action.payload.username, action.payload.token)
          .map((card: CardDTO) => {
            return <Action>{
              type: 'ADD_SOURCE_SUCCESS',
              payload: <ICard>{ ... }
            };
          })
          .catch(_ => {
            return Observable.of(<Action>{ type: 'ADD_SOURCE_FAILED', payload: { }});
          }));

So, then a new ADD_SOURCE_SUCCESS is dispatched on my reducer:

private static saveSourceSuccess(sourcesRdx, type, payload) {
    return <ISourceRedux>{
        ids: [ ...sourcesRdx.ids, payload.id ],
        entities: Object.assign({}, sourcesRdx.entities, {[payload.id]: payload}),
        selectedIds: sourcesRdx.selectedIds,
        editingSource: null
    };
}

Nevertheless, I don't quite figure out how to say on my component that the operation has been success and do one thing or another one...

Any ideas?


问:
Convert float64 column to datetime pandas
I have the following pandas DataFrame column dfA['TradeDate']:

```<code>0     20100329.0
1     20100328.0
2     20100329.0
...
</code>```

and I wish to transform it to a datetime.

Based on another tread on SO, I convert it first to a string and then apply the strptime function.

```<code>dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype('int').to_string() ,'%Y%m%d')
</code>```

However this returns the error that my format is incorrect (ValueError).

An issue that I spotted is that the column is not properly to string, but to an object.

When I try:

```<code>dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype(int).astype(str),'%Y%m%d')
</code>```

It returns: must be a Str and not Series.

答:
You can use:

```<code>df['TradeDate'] = pd.to_datetime(df['TradeDate'], format='%Y%m%d.0')
print (df)
   TradeDate
0 2010-03-29
1 2010-03-28
2 2010-03-29
</code>```

But if some bad values, add errors='coerce' for replace them to NaT

```<code>print (df)
    TradeDate
0  20100329.0
1  20100328.0
2  20100329.0
3  20153030.0
4         yyy

df['TradeDate'] = pd.to_datetime(df['TradeDate'], format='%Y%m%d.0', errors='coerce')
print (df)
   TradeDate
0 2010-03-29
1 2010-03-28
2 2010-03-29
3        NaT
4        NaT
</code>```

Body:
I have the following pandas DataFrame column dfA['TradeDate']:

0     20100329.0
1     20100328.0
2     20100329.0
...

and I wish to transform it to a datetime.

Based on another tread on SO, I convert it first to a string and then apply the strptime function.

dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype('int').to_string() ,'%Y%m%d')

However this returns the error that my format is incorrect (ValueError).

An issue that I spotted is that the column is not properly to string, but to an object.

When I try:

dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype(int).astype(str),'%Y%m%d')

It returns: must be a Str and not Series.

Body:
You can use:

df['TradeDate'] = pd.to_datetime(df['TradeDate'], format='%Y%m%d.0')
print (df)
   TradeDate
0 2010-03-29
1 2010-03-28
2 2010-03-29

But if some bad values, add errors='coerce' for replace them to NaT

print (df)
    TradeDate
0  20100329.0
1  20100328.0
2  20100329.0
3  20153030.0
4         yyy

df['TradeDate'] = pd.to_datetime(df['TradeDate'], format='%Y%m%d.0', errors='coerce')
print (df)
   TradeDate
0 2010-03-29
1 2010-03-28
2 2010-03-29
3        NaT
4        NaT


问:
about xpath when using scrapy
xpath sentences:

```<code>item['title'] = response.xpath('//span[@class="title"]/text()').extract_first()
item['content'] = response.xpath('//div[@class="content"]').extract_first()
</code>```

results：

```<code>{
'title': '\t史蒂芬霍金',
'content': '<div class="content"><div>能够在过去这么多年的时间里研究并学习宇宙学<br>\r\n对我来说意义非凡</div></div>'
}
</code>```

questions：

1、How to remove \t in title field?

2、How to remove

 in content field?(the children nodes can not be removed.)

答:
```<code>item['content'] = response.xpath('string(//div[@class="content"])').extract_first()
</code>```

string() will concatenate all the text in the current node.

if you want to get rid of white space, you can use normalize-space(), it's like python's strip() that built on top of string():

```<code>item['content'] = response.xpath('normalize-space(//div[@class="content"])').extract_first()
</code>```

Title: about xpath when using scrapy

Body:
xpath sentences:

item['title'] = response.xpath('//span[@class="title"]/text()').extract_first()
item['content'] = response.xpath('//div[@class="content"]').extract_first()

results：

{
'title': '\t史蒂芬霍金',
'content': '

能够在过去这么多年的时间里研究并学习宇宙学
\r\n对我来说意义非凡

'
}

questions：

1、How to remove \t in title field?

2、How to remove

 in content field?(the children nodes can not be removed.)

Body:
item['content'] = response.xpath('string(//div[@class="content"])').extract_first()

string() will concatenate all the text in the current node.

if you want to get rid of white space, you can use normalize-space(), it's like python's strip() that built on top of string():

item['content'] = response.xpath('normalize-space(//div[@class="content"])').extract_first()


问:
How to Store Previous Value Of Loop in variable
JSONObject jsonRoot = new JSONObject(response);

```<code>    ArrayList<Level2_Women> alUser = new ArrayList<>();
    JSONArray parentArray = jsonRoot.getJSONArray("categories");

    StringBuffer finalBufferData = new StringBuffer();

    for (int j = 0; j <parentArray.length(); j++) {

            JSONObject finalObject = parentArray.getJSONObject(j);

            user.setCategory(finalObject.getString("category"));
            String catid = finalObject.getString("category_id");

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

I am Using this loop.In my Loop there are 12 elements,But its print only last value.How i can print all element in Listview?

答:
Use list to store all values then use </p>

```<code>List<String> list = new ArrayList<String>();
for (int j = 0; j <parentArray.length(); j++) {
        JSONObject finalObject = parentArray.getJSONObject(j);
        user.setCategory(finalObject.getString("category"));
        String catid = finalObject.getString("category_id");
        list.add(catid);
}
</code>```

Body:
JSONObject jsonRoot = new JSONObject(response);

    ArrayList<Level2_Women> alUser = new ArrayList<>();
    JSONArray parentArray = jsonRoot.getJSONArray("categories");

    StringBuffer finalBufferData = new StringBuffer();

    for (int j = 0; j <parentArray.length(); j++) {

            JSONObject finalObject = parentArray.getJSONObject(j);

            user.setCategory(finalObject.getString("category"));
            String catid = finalObject.getString("category_id");

    }
    return user;
}

I am Using this loop.In my Loop there are 12 elements,But its print only last value.How i can print all element in Listview?

Body:
Use list to store all values then use

List<String> list = new ArrayList<String>();
for (int j = 0; j <parentArray.length(); j++) {
        JSONObject finalObject = parentArray.getJSONObject(j);
        user.setCategory(finalObject.getString("category"));
        String catid = finalObject.getString("category_id");
        list.add(catid);
}


问:
Incorrect answer of Euclidean Distance Java
I am making a program to calculate the Euclidean Distance of 4 values of Training Data with 4 values of Test Data. For KNN i need to find the Euclidean Distance which i programmed in Java and i am getting an incorrect answer from the result.

```<code>/**
 *
 *
 */
public class KNN {
double w1,x1,y1,z1;
double w2,x2,y2,z2;
  Scanner n=new Scanner(System.in);
////3 preset values of the Test Data///////
  void Test()
{
    int x;
    System.out.println("Enter 1 for TD 1 2 for TD 2 and 3 for TD 3");
    x=n.nextInt();
    if(x==1){
    w2=89;
    x2=34;
    y2=27;
    z2=38;}
    else if(x==2)
    {
    w2=58;
    x2=87;
    y2=35;
    z2=38;}
    else if(x==3)
    {
    w2=34;
    x2=61;
    y2=49;
    z2=68;}
    }

//////Input values of Training Data/////
void input()
{

    System.out.println("Enter Feature 1 of Training Data ");
    w1=n.nextDouble();
    System.out.println("Enter Feature 2 of Training Data ");
    x1=n.nextDouble();
    System.out.println("Enter Feature 3 of Training Data ");
    y1=n.nextDouble();
    System.out.println("Enter Feature 4 of Training Data ");
    y1=n.nextDouble();

}

///////Formula for the Euclidean Distance for Training and Test data//////
double formula()
{  double r1,r2,r3,r4;
double r5;
r1=(w2-w1);
r2=(x2-x1);
r3=(y2-y1);
r4=(z2-z1);
r5=(r1*r1)+(r2*r2)+(r3*r3)+(r4*r4);
 System.out.println(r5);
    return Math.sqrt(r5) ;
}
</code>```

The Answer i am getting for the Test Values which are in this case w1,x1,y1,z1
are 89,34,27 and 38 respectively and for the Training Data i am using 69,72,72 and 29
With the calculator i am getting the answer 62.84
but from the result of the code is giving me an answer of

```<code>Start program? 1 for yes and anything else for cancel
1
Enter 1 for TD 1 2 for TD 2 and 3 for TD 3
1
Enter Feature 1 of Training Data
69
Enter Feature 2 of Training Data
72
Enter Feature 3 of Training Data
72
Enter Feature 4 of Training Data
29
3292.0
57.37595315112421
Enter 1 for TD 1 2 for TD 2 and 3 for TD 3
</code>```

Mind you this program is for completing an assignment so i made it in 5 minutes. So go easy on me about the way it is formated

答: Your input method is wrongly assigning y1 twice, instead of assigning the last read value to z1.

Body:
I am making a program to calculate the Euclidean Distance of 4 values of Training Data with 4 values of Test Data. For KNN i need to find the Euclidean Distance which i programmed in Java and i am getting an incorrect answer from the result.

/**
 *
 *
 */
public class KNN {
double w1,x1,y1,z1;
double w2,x2,y2,z2;
  Scanner n=new Scanner(System.in);
////3 preset values of the Test Data///////
  void Test()
{
    int x;
    System.out.println("Enter 1 for TD 1 2 for TD 2 and 3 for TD 3");
    x=n.nextInt();
    if(x==1){
    w2=89;
    x2=34;
    y2=27;
    z2=38;}
    else if(x==2)
    {
    w2=58;
    x2=87;
    y2=35;
    z2=38;}
    else if(x==3)
    {
    w2=34;
    x2=61;
    y2=49;
    z2=68;}
    }

//////Input values of Training Data/////
void input()
{

    System.out.println("Enter Feature 1 of Training Data ");
    w1=n.nextDouble();
    System.out.println("Enter Feature 2 of Training Data ");
    x1=n.nextDouble();
    System.out.println("Enter Feature 3 of Training Data ");
    y1=n.nextDouble();
    System.out.println("Enter Feature 4 of Training Data ");
    y1=n.nextDouble();

}

///////Formula for the Euclidean Distance for Training and Test data//////
double formula()
{  double r1,r2,r3,r4;
double r5;
r1=(w2-w1);
r2=(x2-x1);
r3=(y2-y1);
r4=(z2-z1);
r5=(r1*r1)+(r2*r2)+(r3*r3)+(r4*r4);
 System.out.println(r5);
    return Math.sqrt(r5) ;
}

The Answer i am getting for the Test Values which are in this case w1,x1,y1,z1
are 89,34,27 and 38 respectively and for the Training Data i am using 69,72,72 and 29
With the calculator i am getting the answer 62.84
but from the result of the code is giving me an answer of

Start program? 1 for yes and anything else for cancel
1
Enter 1 for TD 1 2 for TD 2 and 3 for TD 3
1
Enter Feature 1 of Training Data
69
Enter Feature 2 of Training Data
72
Enter Feature 3 of Training Data
72
Enter Feature 4 of Training Data
29
3292.0
57.37595315112421
Enter 1 for TD 1 2 for TD 2 and 3 for TD 3

Mind you this program is for completing an assignment so i made it in 5 minutes. So go easy on me about the way it is formated


答: Delegate the actual printing to lp, just as every other solution does.

Title: printing with java in linux

Body:
Does anyone know any good tutorial or howto how to print with java application in linux? In search but i can not find any good tutorial.

Thx


问:
To push selected values from one dynamic table to another dynamic table
I have two tables named products and customers:-

```<code><table cellpadding="0" cellspacing="0">
     <thead>
        <tr>
           <th>Product Code</th>
        </tr>
       </thead>
    <tbody>
  <tr ng-repeat="row in service track by $index" ng-class="{'ISselected': isSelected(row, $index)}" ng-click="selectedRow(row, $index)">
        <td>{{row}}</td>
  </tr>
    </tbody>
</table>

<table cellpadding="0" cellspacing="0">
      <thead>
         <tr>
           <th>Customer Code</th>
         </tr>
      </thead>
       <tbody>
         <tr ng-repeat="row in customers track by $index">
            <td>{{row}}</td>
         </tr>
       </tbody>
   </table>
</code>```

And a button:-

```<code><button type="button" class="btn btn-info">Add</button>
</code>```

My directive code:-

```<code>scope.services = [];
 scope.customers = [];
  scope.selectedRowID = null;

            scope.selectedRow = function(rowID){
                    scope.selectedRowID = scope.selectedRowID == rowID ? null : rowID;
                }

            scope.isSelected = function(rowID){
                    return (scope.selectedRowID == rowID);
            }
</code>```

What I want here is when I select a particular row/value from the 'products' table and press 'add' button then that row/value gets pushed or added to my customers' table. The data inside from both tables are coming from the backend.

答:
You don't need a directive, rather controller functions will do the job by pushing the selected row into customer data.

Here is basic fiddler, which perform similar stuff. hope it helps.

Body:
I have two tables named products and customers:-

           Product Code

        {{row}}

           Customer Code

            {{row}}

And a button:-

<button type="button" class="btn btn-info">Add</button>

My directive code:-

scope.services = [];
 scope.customers = [];
  scope.selectedRowID = null;

            scope.selectedRow = function(rowID){
                    scope.selectedRowID = scope.selectedRowID == rowID ? null : rowID;
                }

            scope.isSelected = function(rowID){
                    return (scope.selectedRowID == rowID);
            }

What I want here is when I select a particular row/value from the 'products' table and press 'add' button then that row/value gets pushed or added to my customers' table. The data inside from both tables are coming from the backend.


问:
Changing the devise locale in React-native
I have successfully installed react-native-i18n and its works fine. However, I want to change the locale inside the React native app itself.

I have added a button( Touchable opacity ) and have written the following code :

```<code>onPress={() => { i18n.locale = 'ar'; }}
</code>```

However, this does not change the locale to 'ar' and all my translations are still coming for english ( en-US ) only. I dont want the user to go to phone settings and change the locale from there. Can I not do it from the app itself? Only so that the locale is limited for my app only.

答: You need to rerender the app. Listen for ConfigurationChange event to rerender or you may refer this GitHub issue. Easier hack is to set a state once you do i18n.locale = 'ar' :)</p>

Body:
I have successfully installed react-native-i18n and its works fine. However, I want to change the locale inside the React native app itself.

I have added a button( Touchable opacity ) and have written the following code :

onPress={() => { i18n.locale = 'ar'; }}

However, this does not change the locale to 'ar' and all my translations are still coming for english ( en-US ) only. I dont want the user to go to phone settings and change the locale from there. Can I not do it from the app itself? Only so that the locale is limited for my app only.


问:
Hostname does not match in Lollipop devices but works fine in Postman and marshmallow devices
Recently SSL certificates were added to the server, so I have changed the url in android from http://appname.com to https://www.appname.com , this works fine on marshmallow devices and Postman, but on Lollipop devices throws javax.net.ssl.SSLException: hostname in certificate didn't match: www.appname.com != www.companyname.com OR www.companyname.com OR companyname.com

I have tried adding the companyname.com in setHostnameVerifier but it did not help. here is the code:

```<code> HashMap<String, String> postDataParams=new HashMap<>();
        postDataParams.put("u_phone",CN);
        postDataParams.put("u_code",st);
        postDataParams.put("device_flag",mob_device);
        postDataParams.put("app_type","PRO");
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                HostnameVerifier hv =
                        HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify("companyname.com", session);
            }
        };

        try{

            URL url = new URL("https://www.appname.com/sync/validatecheck.php");
            HttpsURLConnection urlConnection =
                    (HttpsURLConnection)url.openConnection();
            //urlConnection.setHostnameVerifier(hostnameVerifier);
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);

            OutputStream os = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=urlConnection.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                while ((line=br.readLine()) != null) {
                    result+=line;
                }
            }
            else {
                result="";

            }
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection "+e.toString());
        }
</code>```

What might be the issue here? and how to solve this?

答:
The error means that the hostname to which the certificate has been issued (CN field in subject) does not match with the server name.

If you are using the URL https://www.appname.com then the certificate should be issued to www.appname.com or *.appname.com. It hostname of the certificate is appname.com then error is correct and you can use https://appname.com but not https://www.appname.com.

Deploy your server in https://appname.com, issue a new certificate for www.appname.com or set a HostnameVerifier to allow www.appname.com

Body:
Recently SSL certificates were added to the server, so I have changed the url in android from http://appname.com to https://www.appname.com , this works fine on marshmallow devices and Postman, but on Lollipop devices throws javax.net.ssl.SSLException: hostname in certificate didn't match: www.appname.com != www.companyname.com OR www.companyname.com OR companyname.com

I have tried adding the companyname.com in setHostnameVerifier but it did not help. here is the code:

 HashMap<String, String> postDataParams=new HashMap<>();
        postDataParams.put("u_phone",CN);
        postDataParams.put("u_code",st);
        postDataParams.put("device_flag",mob_device);
        postDataParams.put("app_type","PRO");
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                HostnameVerifier hv =
                        HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify("companyname.com", session);
            }
        };

        try{

            URL url = new URL("https://www.appname.com/sync/validatecheck.php");
            HttpsURLConnection urlConnection =
                    (HttpsURLConnection)url.openConnection();
            //urlConnection.setHostnameVerifier(hostnameVerifier);
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);

            OutputStream os = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=urlConnection.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                while ((line=br.readLine()) != null) {
                    result+=line;
                }
            }
            else {
                result="";

            }
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

What might be the issue here? and how to solve this?


答:
Your query does not even seem syntactically correct (it uses MAX() but lacks GROUP BY).  One method uses rank():

```<code> SELECT CID, to_char(UPDATED_DATE, 'yyyy-mm-dd hh24:mi:ss' )
 FROM (SELECT t.*,
              RANK() OVER (PARTITION BY CID ORDER BY UPDATED_DATE DESC) as seqnum
       FROM mytable t
       WHERE CID = 201
      ) t
WHERE senqum = 1;
</code>```

I should note that it seems strange that you want to return two identical rows.  You can include other columns in the above query.  Or, just do an aggregation:

```<code>SELECT CID, to_char(max(UPDATED_DATE ), 'yyyy-mm-dd hh24:mi:ss' ),
       COUNT(*) as numRecords
FROM mytable
WHERE CID = 201
GROUP BY CID;
</code>```

Title: How to select the last inserted records by date, time, minutes and seconds

Body:
I have 4 records with the same CID# 201. I'm trying to get the last updated records by the second.  The issue it is returning all 4 of the records. I would like to return the last updated records by CID# 201. Here is my code.

 SELECT CID, to_char( max( UPDATED_DATE ), 'yyyy-mm-dd hh24:mi:ss' )
 FROM mytable
 WHERE CID = 201;

This is the return records. NOT DESIRED

**`CID#`|   `UPDATED_DATE`**
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:29:36`
 `201` | `03/30/2017 7:29:36`

This is what I want returned. YES DESIRED

**`CID`|   `UPDATED_DATE`**
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:30:22`

What am I missing here?

Body:
Your query does not even seem syntactically correct (it uses MAX() but lacks GROUP BY).  One method uses rank():

 SELECT CID, to_char(UPDATED_DATE, 'yyyy-mm-dd hh24:mi:ss' )
 FROM (SELECT t.*,
              RANK() OVER (PARTITION BY CID ORDER BY UPDATED_DATE DESC) as seqnum
       FROM mytable t
       WHERE CID = 201
      ) t
WHERE senqum = 1;

I should note that it seems strange that you want to return two identical rows.  You can include other columns in the above query.  Or, just do an aggregation:

SELECT CID, to_char(max(UPDATED_DATE ), 'yyyy-mm-dd hh24:mi:ss' ),
       COUNT(*) as numRecords
FROM mytable
WHERE CID = 201
GROUP BY CID;


问:
How to `navigate` to new screen from button in header with react-navigation?
I'm using react-navigation and want to add a button to the right on my header that will navigate to a different screen. But when setting up the navigationOptions, I'm wondering how I can get access to the navigate function in the callback that is invoked when the button is pressed:

```<code>const RootNavigationStack = StackNavigator({
  PokemonList: {
    screen: PokemonListWrapper,
    navigationOptions: {
      title: ({state}) => `Pokedex`,
      header: ({ state, setParams }) => {
        return {
          visible: true,
          right: (
            <Button
              title={'Add'}
              onPress={() => // navigate to new screen here
            />
          ),
        }
      }
    },
  },
, {
  headerMode: 'screen'
})
</code>```

Any ideas how this can be achieved? I was thinking of maybe using withNavigation, but am still not quite clear on how that would work.

答:
Try this.</p>

```<code>    header: ({ navigate }) => ({
       right: (
          <Button onPress={() => navigate('screen2')}  />
       )
    }),
</code>```

Body:
I'm using react-navigation and want to add a button to the right on my header that will navigate to a different screen. But when setting up the navigationOptions, I'm wondering how I can get access to the navigate function in the callback that is invoked when the button is pressed:

const RootNavigationStack = StackNavigator({
  PokemonList: {
    screen: PokemonListWrapper,
    navigationOptions: {
      title: ({state}) => `Pokedex`,
      header: ({ state, setParams }) => {
        return {
          visible: true,
          right: (
            <Button
              title={'Add'}
              onPress={() => // navigate to new screen here
            />
          ),
        }
      }
    },
  },
, {
  headerMode: 'screen'
})

Any ideas how this can be achieved? I was thinking of maybe using withNavigation, but am still not quite clear on how that would work.

Body:
Try this.

    header: ({ navigate }) => ({
       right: (
          <Button onPress={() => navigate('screen2')}  />
       )
    }),


问:
Powershell DSC ConfigurationData keys
I'm new to DSC and just trying to understand some basic concept around configuration data.  I understand that you can pass dynamic config data into your configuration.  I'm also now able to encrypt credentials using a certificate by passing in the CertificateFile key into the AllNodes variable of the config data.

I'm just trying to understand how this is applied.  I was under the impression that the config data just allowed you present dynamic data for the configuration to use.  Does this mean that if, for some bizarre reason, I wanted to hardcode the certificatefile into the configuration, rather than in the config data, I could do so?

Or can this only be applied via ConfigData? If so, are there other "system" keys that can be applied to config data? I've not been able to find any documentation online that explains this.

Example config data:

```<code>$ConfigData=    @{
    AllNodes = @(
                    @{
                        NodeName = "MYSERVER"
                        CertificateFile = "C:\MyPublicKey.cer"
                    };
                );
}
</code>```

There is nothing in the main configuration that seems to expect the key "CertificateFile."

Thanks.

答:
By using the built-in DSC ConfigurationData parameter, you can define data that can be used within a configuration. This allows you to create a single configuration that can be used for multiple nodes or for different environments. For example, if you are developing an application, you can use one configuration for both development and production environments, and use configuration data to specify data for each environment.

Reference:

https://blogs.msdn.microsoft.com/powershell/2014/01/09/separating-what-from-where-in-powershell-dsc/

https://msdn.microsoft.com/en-us/powershell/dsc/configdata

Title: Powershell DSC ConfigurationData keys

Body:
I'm new to DSC and just trying to understand some basic concept around configuration data.  I understand that you can pass dynamic config data into your configuration.  I'm also now able to encrypt credentials using a certificate by passing in the CertificateFile key into the AllNodes variable of the config data.

I'm just trying to understand how this is applied.  I was under the impression that the config data just allowed you present dynamic data for the configuration to use.  Does this mean that if, for some bizarre reason, I wanted to hardcode the certificatefile into the configuration, rather than in the config data, I could do so?

Or can this only be applied via ConfigData? If so, are there other "system" keys that can be applied to config data? I've not been able to find any documentation online that explains this.

Example config data:

$ConfigData=    @{
    AllNodes = @(
                    @{
                        NodeName = "MYSERVER"
                        CertificateFile = "C:\MyPublicKey.cer"
                    };
                );
}

There is nothing in the main configuration that seems to expect the key "CertificateFile."

Thanks.


问:
How do you get a widget's children in Qt?
I'm simulating keyPresses to an application through Qt's KeyPress function. All the KeyPresses work fine. However when I pass a QT::Key_Enter which is supposed to press the OK button of the currently active window, or QT::Key_Cancel for the cancel button, it does nothing.

I'm thinking maybe, because these buttons don't have the focus, and the parent window itself has it. How do you get the children of a window? or rather find the OK or Cancel button on it so you could set it as the activeWindow and then pass KeyPresses successfully?

I have:

```<code>QWidget *pWin = QApplication::activeWindow;
QObjectList *pList = pWin->children();
//how do you iterate through the list and find the OK or Cancel button?
</code>```

答:
You can use the findChild() function with the object name to get a specific child.

You can also use findChildren() to get all the children that have the same name and then iterate through the list using foreach() or QListIterator.

To get a button you can try:

```<code>QPushButton* button = pWin->findChild<QPushButton*>("Button name");
</code>```

Body:
I'm simulating keyPresses to an application through Qt's KeyPress function. All the KeyPresses work fine. However when I pass a QT::Key_Enter which is supposed to press the OK button of the currently active window, or QT::Key_Cancel for the cancel button, it does nothing.

I'm thinking maybe, because these buttons don't have the focus, and the parent window itself has it. How do you get the children of a window? or rather find the OK or Cancel button on it so you could set it as the activeWindow and then pass KeyPresses successfully?

I have:

QWidget *pWin = QApplication::activeWindow;
QObjectList *pList = pWin->children();
//how do you iterate through the list and find the OK or Cancel button?

Body:
You can use the findChild() function with the object name to get a specific child.

You can also use findChildren() to get all the children that have the same name and then iterate through the list using foreach() or QListIterator.

To get a button you can try:

QPushButton* button = pWin->findChild<QPushButton*>("Button name");