问:
How to use phone default printer function to print the content of PDF opened from WebView in Xamarin Android
Can any one help me with the problem, to print the url content.
I am opening the PDF file in a web view of my application and then trying to print the document from there by placing separate button for printing. Please look at the code below.

    [Activity(Label = "PdfView")]
    public class PdfView : Activity
    {
        public static PdfView _context;
        Android.Content.Res.Resources res;
        private static string ErrorTitle, ErrorMsg;
        private static ProgressBar progressBar;

        WebView mWebView, Web_Print;
        RelativeLayout LL_Print,LL_input;
        string MyUrl;
        private WebClient _webClient = new WebClient();
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _context = this;
            res = _context.Resources;
            SetContentView(Resource.Layout.web_pdf);
            ErrorTitle = res.GetString(Resource.String.error_title);
            ErrorMsg = res.GetString(Resource.String.Somethingwentwrong);
            progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar1);
            LL_Print = FindViewById<RelativeLayout>(Resource.Id.LL_Print);
            LL_input = FindViewById<RelativeLayout>(Resource.Id.LL_input);
            Web_Print = FindViewById<WebView>(Resource.Id.Web_Print);
            Web_Print.Visibility = ViewStates.Gone;
            LL_Print.Visibility = ViewStates.Gone;
            var customWebViewClient = new WebViewLoaderClient();
            mWebView = FindViewById<WebView>(Resource.Id.Web);
            mWebView.Download += MWebview_Download;
            mWebView.Settings.JavaScriptEnabled = true;
            mWebView.Settings.BuiltInZoomControls = true;
            mWebView.SetWebViewClient(customWebViewClient);
            mWebView.SetWebChromeClient(new WebChromeClient());
            String myPdfUrl = APIConstants.InvoicePdfUrl;
            MyUrl = "http://docs.google.com/gview?embedded=true&url=" + myPdfUrl;
            mWebView.LoadUrl(MyUrl);

            InitComonents();
        }

        private void MWebview_Download(object sender, DownloadEventArgs e)
        {
            mWebView.Visibility = ViewStates.Gone;
            LL_input.Visibility = ViewStates.Gone;
            LL_Print.Visibility = ViewStates.Visible;
            Web_Print.Visibility = ViewStates.Visible;
            var Url = e.Url;
            CustomWebViewClient client = new CustomWebViewClient(this);
            Web_Print.SetWebViewClient(client);
            Web_Print.SetWebChromeClient(new WebChromeClient());
            Web_Print.Settings.JavaScriptEnabled = true;
            Web_Print.LoadUrl(Url);
            Web_Print.Settings.UseWideViewPort = true;
            Web_Print.Settings.LoadWithOverviewMode = true;
        }

        #region // Initializing widgets
        public void InitComonents()
        {
            try
            {
                LinearLayout img_viw = FindViewById<LinearLayout>(Resource.Id.img_WV_back);
                LinearLayout img_viw_Home = FindViewById<LinearLayout>(Resource.Id.img_WV_home);

            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }
        #endregion

        #region // Webview client
        public class WebViewLoaderClient : WebViewClient
        {
            public event EventHandler<bool> OnPageLoaded;
            public override bool ShouldOverrideUrlLoading(WebView view, string url)
            {
                view.LoadUrl(url);
                return true;
            }
            public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
            {
                base.OnPageStarted(view, url, favicon);
                progressBar.Visibility = ViewStates.Visible;
            }
            public override void OnPageFinished(WebView view, string url)
            {
                base.OnPageFinished(view, url);
                progressBar.Visibility = ViewStates.Gone;
            }
            public override void OnReceivedError(WebView view, ClientError errorCode, string description, string failingUrl)
            {
                base.OnReceivedError(view, errorCode, description, failingUrl);
                view.Visibility = ViewStates.Gone;
                Error();
            }
        }
        class MonkeyWebViewClient : WebViewClient
        {
            public override bool ShouldOverrideUrlLoading(WebView view, string url)
            {
                view.LoadUrl(url);
                return true;
            }
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {
                view.LoadUrl("file:///android_asset/myerrorpage.html");
            }
        }
        #endregion

        #region Error Message for Web View Error
        public static void Error()
        {
            AlertDialog.Builder alert = new AlertDialog.Builder(_context);
            alert.SetTitle(ErrorTitle);
            alert.SetMessage(ErrorMsg);
            alert.SetPositiveButton(Resource.String.ok, (senderAlert, args) =>
            {
                _context.Finish();
            });
            alert.SetCancelable(false);
            Dialog dialog = alert.Create();
            dialog.Show();
        }

        public void doWebViewPrint(string url)
        {
            PrintDocumentAdapter adapter;
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
                adapter = mWebView.CreatePrintDocumentAdapter("test");
            else
                adapter = mWebView.CreatePrintDocumentAdapter();
            var printMgr = (PrintManager)GetSystemService(PrintService);
            printMgr.Print("printTest", adapter, null);
        }
        #endregion
    }

    public class CustomWebViewClient : WebViewClient
    {
        private PdfView myActivity;
        public bool shouldOverrideUrlLoading(WebView view, string url)
        {
            view.LoadUrl(url);
            return false;
        }
        public override void OnPageFinished(WebView view, string url)
        {
            Log.Debug("PRINT", "page finished loading " + url);
            myActivity.doWebViewPrint(url);
            //CreateWebPrintJob(view);
            base.OnPageFinished(view, url);
        }

        private void CreateWebPrintJob(WebView view)
        {
            throw new NotImplementedException();
        }

        public CustomWebViewClient(PdfView activity)
        {
            myActivity = activity;
        }
    }
}
```

This is able show the content of the PDF and open the printer function but the content of the PDF is not able to view in the printer function as preview i.e., getting me as follows

So, Can any one help me with this problem to rectify and able to get the PDF content viewed in the web to print it.

答:
Please see the following code which made it possible to print::
The complete game changer here is scale calculation,

.
.
.
.
.
.
.
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _context = this;
            res = _context.Resources;
            SetContentView(Resource.Layout.xxxxxxxxxxxxxxxx);
            var customWebViewClient = new WebViewLoaderClient();
            mWebView = FindViewById<WebView>(Resource.Id.Web);
            //mWebView.Download += MWebview_Download;
            UserLoginDetailList = UserInfoDBServices.getUserLoginDetailsfromDBfordroid();
            ObjLangList = UserInfoDBServices.GetCurrentLanguageListfordroid();
            mWebView.Settings.JavaScriptEnabled = true;
            mWebView.Settings.BuiltInZoomControls = true;
            mWebView.SetWebViewClient(customWebViewClient);
            String myPdfUrl = APIConstants.InvoicePdfUrl;
            MyUrl = "http://docs.google.com/gview?embedded=true&url=" + myPdfUrl;//Here in myPdfUrl variable place the url of the pdf you are getting from your server
            mWebView.LoadUrl(MyUrl);
            InitComonents();
        }
        #region // Initializing widgets
        public void InitComonents()
        {
            try
            {
                Print = FindViewById<LinearLayout>(Resource.Id.ll_TNP_Pirnt);
                Print.Visibility = ViewStates.Visible;
                Print.Click += delegate
                  {
                      LL_Print.Clickable = false;
                      var printManager = (PrintManager)GetSystemService(Context.PrintService);
                      var content = FindViewById<LinearLayout>(Resource.Id.LL_input);
                      var printAdapter = new GenericPrintAdapter(this, content);

                      printManager.Print("MyPrintJob", printAdapter, null);
                  };
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }
        #endregion
        public class GenericPrintAdapter:PrintDocumentAdapter
        {
            View view;
            Context context;
            PrintedPdfDocument document;
            float scale;
            private DownloadPdfView downloadPdfView;
            private RelativeLayout content;

            public GenericPrintAdapter(DownloadPdfView downloadPdfView, View view)
            {
                this.downloadPdfView = downloadPdfView;
                this.view = view;
            }

            public override void OnLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras)
            {
                try
                {
                    document = new PrintedPdfDocument(context, newAttributes);

                    CalculateScale(newAttributes);

                    var printInfo = new PrintDocumentInfo
                        .Builder("Invoice.pdf")
                        .SetContentType(PrintContentType.Document)
                        .SetPageCount(1)
                        .Build();

                    callback.OnLayoutFinished(printInfo, true);
                }
                catch(Exception ex)
                {
                    ex.Message.ToString();
                }

            }

            public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback)
            {

                try
                {
                    PrintedPdfDocument.Page page = document.StartPage(0);

                    page.Canvas.Scale(scale, scale);

                    view.Draw(page.Canvas);

                    document.FinishPage(page);

                    WritePrintedPdfDoc(destination);

                    document.Close();

                    document.Dispose();

                    callback.OnWriteFinished(pages);
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }

            }
            void CalculateScale(PrintAttributes newAttributes)
            {
                try
                {
                    int dpi = Math.Max(newAttributes.GetResolution().HorizontalDpi, newAttributes.GetResolution().VerticalDpi);

                    int leftMargin = (int)(dpi * (float)newAttributes.MinMargins.LeftMils / 1000);
                    int rightMargin = (int)(dpi * (float)newAttributes.MinMargins.RightMils / 1000);
                    int topMargin = (int)(dpi * (float)newAttributes.MinMargins.TopMils / 1000);
                    int bottomMargin = (int)(dpi * (float)newAttributes.MinMargins.BottomMils / 1000);

                    int w = (int)(dpi * (float)newAttributes.GetMediaSize().WidthMils / 3500) - leftMargin - rightMargin;
                    int h = (int)(dpi * (float)newAttributes.GetMediaSize().HeightMils / 3500) - topMargin - bottomMargin;

                    scale = Math.Min((float)document.PageContentRect.Width() / w, (float)document.PageContentRect.Height() / h);
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }

            }
            void WritePrintedPdfDoc(ParcelFileDescriptor destination)
            {
                try
                {
                    var javaStream = new Java.IO.FileOutputStream(destination.FileDescriptor);
                    var osi = new OutputStreamInvoker(javaStream);
                    using (var mem = new MemoryStream())
                    {
                        document.WriteTo(mem);
                        var bytes = mem.ToArray();
                        osi.Write(bytes, 0, bytes.Length);
                    }
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }
            }
        }

        #region // Webview client
        public class WebViewLoaderClient : WebViewClient
        {
            public event EventHandler<bool> OnPageLoaded;
            public override bool ShouldOverrideUrlLoading(WebView view, string url)
            {
                view.LoadUrl(url);
                return true;
            }
            public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
            {
                base.OnPageStarted(view, url, favicon);
                progressBar.Visibility = ViewStates.Visible;
            }
            public override void OnPageFinished(WebView view, string url)
            {
                base.OnPageFinished(view, url);
                progressBar.Visibility = ViewStates.Gone;
            }
            public override void OnReceivedError(WebView view, ClientError errorCode, string description, string failingUrl)
            {
                base.OnReceivedError(view, errorCode, description, failingUrl);
                view.Visibility = ViewStates.Gone;
                Error();
            }
        }
        class MonkeyWebViewClient : WebViewClient
        {
            public override bool ShouldOverrideUrlLoading(WebView view, string url)
            {
                view.LoadUrl(url);
                return true;
            }
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {
                view.LoadUrl("file:///android_asset/myerrorpage.html");
            }
        }
        #endregion

        #region Error Message for Web View Error
        public static void Error()
        {
            AlertDialog.Builder alert = new AlertDialog.Builder(_context);
            alert.SetTitle(ErrorTitle);
            alert.SetMessage(ErrorMsg);
            alert.SetPositiveButton(Resource.String.ok, (senderAlert, args) =>
            {
                _context.Finish();
            });
            alert.SetCancelable(false);
            Dialog dialog = alert.Create();
            dialog.Show();
        }
        #endregion
    }
}
```

Body:
Can any one help me with the problem, to print the url content.
I am opening the PDF file in a web view of my application and then trying to print the document from there by placing separate button for printing. Please look at the code below.

    [Activity(Label = "PdfView")]
    public class PdfView : Activity
    {
        public static PdfView _context;
        Android.Content.Res.Resources res;
        private static string ErrorTitle, ErrorMsg;
        private static ProgressBar progressBar;

        WebView mWebView, Web_Print;
        RelativeLayout LL_Print,LL_input;
        string MyUrl;
        private WebClient _webClient = new WebClient();
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _context = this;
            res = _context.Resources;
            SetContentView(Resource.Layout.web_pdf);
            ErrorTitle = res.GetString(Resource.String.error_title);
            ErrorMsg = res.GetString(Resource.String.Somethingwentwrong);
            progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar1);
            LL_Print = FindViewById<RelativeLayout>(Resource.Id.LL_Print);
            LL_input = FindViewById<RelativeLayout>(Resource.Id.LL_input);
            Web_Print = FindViewById<WebView>(Resource.Id.Web_Print);
            Web_Print.Visibility = ViewStates.Gone;
            LL_Print.Visibility = ViewStates.Gone;
            var customWebViewClient = new WebViewLoaderClient();
            mWebView = FindViewById<WebView>(Resource.Id.Web);
            mWebView.Download += MWebview_Download;
            mWebView.Settings.JavaScriptEnabled = true;
            mWebView.Settings.BuiltInZoomControls = true;
            mWebView.SetWebViewClient(customWebViewClient);
            mWebView.SetWebChromeClient(new WebChromeClient());
            String myPdfUrl = APIConstants.InvoicePdfUrl;
            MyUrl = "http://docs.google.com/gview?embedded=true&url=" + myPdfUrl;
            mWebView.LoadUrl(MyUrl);

            InitComonents();
        }

        private void MWebview_Download(object sender, DownloadEventArgs e)
        {
            mWebView.Visibility = ViewStates.Gone;
            LL_input.Visibility = ViewStates.Gone;
            LL_Print.Visibility = ViewStates.Visible;
            Web_Print.Visibility = ViewStates.Visible;
            var Url = e.Url;
            CustomWebViewClient client = new CustomWebViewClient(this);
            Web_Print.SetWebViewClient(client);
            Web_Print.SetWebChromeClient(new WebChromeClient());
            Web_Print.Settings.JavaScriptEnabled = true;
            Web_Print.LoadUrl(Url);
            Web_Print.Settings.UseWideViewPort = true;
            Web_Print.Settings.LoadWithOverviewMode = true;
        }

        #region // Initializing widgets
        public void InitComonents()
        {
            try
            {
                LinearLayout img_viw = FindViewById<LinearLayout>(Resource.Id.img_WV_back);
                LinearLayout img_viw_Home = FindViewById<LinearLayout>(Resource.Id.img_WV_home);

            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }
        #endregion

        #region // Webview client
        public class WebViewLoaderClient : WebViewClient
        {
            public event EventHandler<bool> OnPageLoaded;
            public override bool ShouldOverrideUrlLoading(WebView view, string url)
            {
                view.LoadUrl(url);
                return true;
            }
            public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
            {
                base.OnPageStarted(view, url, favicon);
                progressBar.Visibility = ViewStates.Visible;
            }
            public override void OnPageFinished(WebView view, string url)
            {
                base.OnPageFinished(view, url);
                progressBar.Visibility = ViewStates.Gone;
            }
            public override void OnReceivedError(WebView view, ClientError errorCode, string description, string failingUrl)
            {
                base.OnReceivedError(view, errorCode, description, failingUrl);
                view.Visibility = ViewStates.Gone;
                Error();
            }
        }
        class MonkeyWebViewClient : WebViewClient
        {
            public override bool ShouldOverrideUrlLoading(WebView view, string url)
            {
                view.LoadUrl(url);
                return true;
            }
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {
                view.LoadUrl("file:///android_asset/myerrorpage.html");
            }
        }
        #endregion

        #region Error Message for Web View Error
        public static void Error()
        {
            AlertDialog.Builder alert = new AlertDialog.Builder(_context);
            alert.SetTitle(ErrorTitle);
            alert.SetMessage(ErrorMsg);
            alert.SetPositiveButton(Resource.String.ok, (senderAlert, args) =>
            {
                _context.Finish();
            });
            alert.SetCancelable(false);
            Dialog dialog = alert.Create();
            dialog.Show();
        }

        public void doWebViewPrint(string url)
        {
            PrintDocumentAdapter adapter;
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
                adapter = mWebView.CreatePrintDocumentAdapter("test");
            else
                adapter = mWebView.CreatePrintDocumentAdapter();
            var printMgr = (PrintManager)GetSystemService(PrintService);
            printMgr.Print("printTest", adapter, null);
        }
        #endregion
    }

    public class CustomWebViewClient : WebViewClient
    {
        private PdfView myActivity;
        public bool shouldOverrideUrlLoading(WebView view, string url)
        {
            view.LoadUrl(url);
            return false;
        }
        public override void OnPageFinished(WebView view, string url)
        {
            Log.Debug("PRINT", "page finished loading " + url);
            myActivity.doWebViewPrint(url);
            //CreateWebPrintJob(view);
            base.OnPageFinished(view, url);
        }

        private void CreateWebPrintJob(WebView view)
        {
            throw new NotImplementedException();
        }

        public CustomWebViewClient(PdfView activity)
        {
            myActivity = activity;
        }
    }
}

This is able show the content of the PDF and open the printer function but the content of the PDF is not able to view in the printer function as preview i.e., getting me as follows

So, Can any one help me with this problem to rectify and able to get the PDF content viewed in the web to print it.


来源: stackexchange

问:
Android Studio 3.0 submodule compile failed
App level build gradle dependencies

```<code>devCompile project(path: ':mymodule', configuration: 'devRelease')
proCompile project(path: ':mymodule', configuration: 'proRelease')
qaCompile project(path: ':mymodule', configuration: 'qaRelease')
offlineCompile project(path: ':mymodule', configuration: 'offlineRelease')
</code>```

mentioned

```<code>publishNonDefault true
flavorDimensions "default"
</code>```

I have tried This accepted answer but didn't work.

Update:
Look at the library gradle flavor that I want to compile. I have the same flavor mentioned in my app's Module.

```<code>        dev {
            manifestPlaceholders = [facebookId: "SOME_FACEBOOK_ID_1"]
        }
        pro {
            manifestPlaceholders = [facebookId: "SOME_FACEBOOK_ID_2"]
        }
        qa {
            manifestPlaceholders = [facebookId: "SOME_FACEBOOK_ID_3"]
        }
        offline {
            manifestPlaceholders = [facebookId: "SOME_FACEBOOK_ID_4"]
        }
</code>```

答:
You just need to reduce the details you provide:

```<code>compile project(path: ':mymodule')
</code>```

The details what in which configuration is decided by gradle now by themselves. So it became way easier. Instead of 4 lines you just need the above now.

Also remove the publishNonDefault true from your modules gradle. It is not needed anymore.

ContentLicense: CC BY-SA 3.0

Body:
App level build gradle dependencies

devCompile project(path: ':mymodule', configuration: 'devRelease')
proCompile project(path: ':mymodule', configuration: 'proRelease')
qaCompile project(path: ':mymodule', configuration: 'qaRelease')
offlineCompile project(path: ':mymodule', configuration: 'offlineRelease')

mentioned

publishNonDefault true
flavorDimensions "default"

I have tried This accepted answer but didn't work.

Update:
Look at the library gradle flavor that I want to compile. I have the same flavor mentioned in my app's Module.

        dev {
            manifestPlaceholders = [facebookId: "SOME_FACEBOOK_ID_1"]
        }
        pro {
            manifestPlaceholders = [facebookId: "SOME_FACEBOOK_ID_2"]
        }
        qa {
            manifestPlaceholders = [facebookId: "SOME_FACEBOOK_ID_3"]
        }
        offline {
            manifestPlaceholders = [facebookId: "SOME_FACEBOOK_ID_4"]
        }

Body:
You just need to reduce the details you provide:

compile project(path: ':mymodule')

The details what in which configuration is decided by gradle now by themselves. So it became way easier. Instead of 4 lines you just need the above now.

Also remove the publishNonDefault true from your modules gradle. It is not needed anymore.


问:
Java if- else strings .contains not working error
If I put entity.about = "phone" and test = "phone" then the search list is updated but if I put entity.about = "this is phone" and test = "phone" then the search list is not updated.

```<code>public void onSearchConfirmed(final CharSequence text) {
    productsRef = FirebaseDatabase.getInstance().getReference("products");
    searchList.clear();
    final String test = text.toString();
    productsRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                ProductEntity entity = postSnapshot.getValue(ProductEntity.class);
                if(entity.about.contains(test) || entity.vendor_address.contains(test)) {
                    searchList.add(entity) ;
                }
            }
        }
    }
}
</code>```

答:
What I was doing wrong not considering the fact that contains function in String class is actually case sensitive. This is what I needed to do:</p>

```<code>final String test = text.toString().toLowerCase() ;
    productsRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                ProductEntity entity = postSnapshot.getValue(ProductEntity.class);
                if(entity.about.toLowerCase().contains(test) || entity.vendor_address.toLowerCase().contains(test)) {
                    searchList.add(entity) ;
                }
            }
</code>```

Body:
If I put entity.about = "phone" and test = "phone" then the search list is updated but if I put entity.about = "this is phone" and test = "phone" then the search list is not updated.

public void onSearchConfirmed(final CharSequence text) {
    productsRef = FirebaseDatabase.getInstance().getReference("products");
    searchList.clear();
    final String test = text.toString();
    productsRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                ProductEntity entity = postSnapshot.getValue(ProductEntity.class);
                if(entity.about.contains(test) || entity.vendor_address.contains(test)) {
                    searchList.add(entity) ;
                }
            }
        }
    }
}

Body:
What I was doing wrong not considering the fact that contains function in String class is actually case sensitive. This is what I needed to do:

final String test = text.toString().toLowerCase() ;
    productsRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                ProductEntity entity = postSnapshot.getValue(ProductEntity.class);
                if(entity.about.toLowerCase().contains(test) || entity.vendor_address.toLowerCase().contains(test)) {
                    searchList.add(entity) ;
                }
            }


问:
solution: ts file defined in parent/parallel folder to give import in child module
I have defined directive inside app folder since it is common directive and trying to use in child module project which is inside app/dashboard/project
folder so when I am trying to import it in my child module it is giving can not file module error. same happened when I try to use any service defined in top module and to import in child module.

```<code>import { CpLoopDecorator }  from '../app.facets.directive';
[ts] Cannot find module '../app.facets.directive'.
</code>```

solution:
It is just issue with relative path so once I did ../../app.facets.directive it started giving reference of file since I was importing it in child module

答:
i think you didn't export it, please export your directive in your module:</p>

```<code>@NgModule({
  declarations: [
    facetsDirective
  ],

  exports: [facetsDirective]<== add this line
})
</code>```

Body:
I have defined directive inside app folder since it is common directive and trying to use in child module project which is inside app/dashboard/project
folder so when I am trying to import it in my child module it is giving can not file module error. same happened when I try to use any service defined in top module and to import in child module.

import { CpLoopDecorator }  from '../app.facets.directive';
[ts] Cannot find module '../app.facets.directive'.

solution:
It is just issue with relative path so once I did ../../app.facets.directive it started giving reference of file since I was importing it in child module

Body:
i think you didn't export it, please export your directive in your module:

@NgModule({
  declarations: [
    facetsDirective
  ],

  exports: [facetsDirective]<== add this line
})


问:
Compile time Bimap static_assert failure
I am trying to have a simple compile time Bimap with the use of constexpr and std::array.

This seems to work fine with the first example.
However with the second example I have the following static error:

error: static_assert failed "3 == 3.3"

          static_assert(meta_dict.find_key_of_value(3) == 3.3, "3 == 3.3");    // fails

Here the code available on Wandbox. Should compile (except the above error) with Clang>=5.0.0 and GCC>=8.0.0.

```<code>#include <utility>
#include <array>
#include <stdexcept>
#include <string_view>
#include <iostream>

template<class Key, class Value, std::size_t N>
struct MetaBimap {
    using Item = std::pair<Key, Value>;

    constexpr MetaBimap(const std::array<Item, N>& d)
        : dictionnary{d}
        {}

    constexpr Value find_value_of_key(const Key& key, int range = N) const
    {
        if (range == 0)
            throw std::out_of_range("Cannot find key");
        return (dictionnary[range - 1].first == key)
            ? dictionnary[range - 1].second
            : find_value_of_key(key, range - 1);
    }

    constexpr Key find_key_of_value(const Value& value, int range = N) const
    {
        if (range == 0)
            throw std::out_of_range("Cannot find value");
        return (dictionnary[range - 1].second == value)
            ? dictionnary[range - 1].first
            : find_key_of_value(value, range - 1);
    }

    std::array<Item, N> dictionnary;
};

int main()
{
    // first example
    {
        using namespace std::string_view_literals;
        constexpr std::array<std::pair<std::string_view, int>, 3> meta_array {{
            { "one"sv, 1 },
            { "two"sv, 2 },
            { "three"sv, 3 }
        }};
        constexpr MetaBimap<std::string_view, int, 3> meta_dict = meta_array;

        // OK on wandbox with Clang>=5.0.0 and GCC>=8.0.0 (though not working on my computer with Clang=5.0.0)
        static_assert(meta_dict.find_value_of_key("one"sv) == 1, "one == 1");
        static_assert(meta_dict.find_key_of_value(3) == "three"sv, "3 == three");
    }

    // second example
    {
        constexpr std::array<std::pair<float, int>, 3> meta_array {{
            { 1.1, 1 },
            { 2.2, 2 },
            { 3.3, 3 }
        }};
        constexpr MetaBimap<float, int, 3> meta_dict = meta_array;

        static_assert(meta_dict.find_value_of_key(1.1) == 1, "1.1 == 1");       // OK
        std::cout << meta_dict.find_key_of_value(3) << std::endl;
        // static_assert(meta_dict.find_key_of_value(3) == 3.3, "3 == 3.3");    // fails
    }
}
</code>```

Why is there a static failure here and how to fix it ?
Also as bonus, any way to simplify the construction of the bimap ?

答:
The problem can be reduced to this:

```<code>constexpr float a = 3.3;
static_assert (a == 3.3f, "float 3.3 is different from literal compiled 3.3f"); // ok
static_assert (a == 3.3, "float 3.3 is different from literal compiled 3.3"); //this fails
</code>```

the literal 3.3 written in code is treated by compiler as a double, and when comparing a float with a double, having them different precisions, it can happens (almost always) they don't match

with 3.3f you are telling the compiler that the literal written in code should be treated as float, while not specifying any suffix will default to double

Have a look here

Body:
I am trying to have a simple compile time Bimap with the use of constexpr and std::array.

This seems to work fine with the first example.
However with the second example I have the following static error:

error: static_assert failed "3 == 3.3"

          static_assert(meta_dict.find_key_of_value(3) == 3.3, "3 == 3.3");    // fails

Here the code available on Wandbox. Should compile (except the above error) with Clang>=5.0.0 and GCC>=8.0.0.

#include <utility>
#include <array>
#include <stdexcept>
#include <string_view>
#include <iostream>

template<class Key, class Value, std::size_t N>
struct MetaBimap {
    using Item = std::pair<Key, Value>;

    constexpr MetaBimap(const std::array<Item, N>& d)
        : dictionnary{d}
        {}

    constexpr Value find_value_of_key(const Key& key, int range = N) const
    {
        if (range == 0)
            throw std::out_of_range("Cannot find key");
        return (dictionnary[range - 1].first == key)
            ? dictionnary[range - 1].second
            : find_value_of_key(key, range - 1);
    }

    constexpr Key find_key_of_value(const Value& value, int range = N) const
    {
        if (range == 0)
            throw std::out_of_range("Cannot find value");
        return (dictionnary[range - 1].second == value)
            ? dictionnary[range - 1].first
            : find_key_of_value(value, range - 1);
    }

    std::array<Item, N> dictionnary;
};

int main()
{
    // first example
    {
        using namespace std::string_view_literals;
        constexpr std::array<std::pair<std::string_view, int>, 3> meta_array {{
            { "one"sv, 1 },
            { "two"sv, 2 },
            { "three"sv, 3 }
        }};
        constexpr MetaBimap<std::string_view, int, 3> meta_dict = meta_array;

        // OK on wandbox with Clang>=5.0.0 and GCC>=8.0.0 (though not working on my computer with Clang=5.0.0)
        static_assert(meta_dict.find_value_of_key("one"sv) == 1, "one == 1");
        static_assert(meta_dict.find_key_of_value(3) == "three"sv, "3 == three");
    }

    // second example
    {
        constexpr std::array<std::pair<float, int>, 3> meta_array {{
            { 1.1, 1 },
            { 2.2, 2 },
            { 3.3, 3 }
        }};
        constexpr MetaBimap<float, int, 3> meta_dict = meta_array;

        static_assert(meta_dict.find_value_of_key(1.1) == 1, "1.1 == 1");       // OK
        std::cout << meta_dict.find_key_of_value(3) << std::endl;
        // static_assert(meta_dict.find_key_of_value(3) == 3.3, "3 == 3.3");    // fails
    }
}

Why is there a static failure here and how to fix it ?
Also as bonus, any way to simplify the construction of the bimap ?

Body:
The problem can be reduced to this:

constexpr float a = 3.3;
static_assert (a == 3.3f, "float 3.3 is different from literal compiled 3.3f"); // ok
static_assert (a == 3.3, "float 3.3 is different from literal compiled 3.3"); //this fails

the literal 3.3 written in code is treated by compiler as a double, and when comparing a float with a double, having them different precisions, it can happens (almost always) they don't match

with 3.3f you are telling the compiler that the literal written in code should be treated as float, while not specifying any suffix will default to double

Have a look here


问:
What is the correct way to implement Struct abstraction in Go?
I'm having some issues understanding Go's struct inheritance. I'm trying to do somewhat of an abstraction for an object type. See the example code below:

```<code>package main

type Animal struct{}
type Dog struct {
    Animal
    Color string
}

type Person struct {
    Name string
    Age  int
    Pet  *Animal
}

func main() {
    dog := &Dog{Color: "brown"}
    tom := &Person{Name: "Tom", Age: 13, Pet: dog}
}
</code>```

This is causing a compilation error:

cannot use dog (type *Dog) as type *Animal in field value

What is the correct way to go about doing an abstraction like this? Is it possible in Go?

End goal for the example would be to have different types of Pets - Dog, Cat, Hamser, etc. Then be able to store that into a struct expecting type Animal.

To visualize, something like:

```<code>type Person struct {
    Name string
    Age  int
    Pet  *Dog OR *Cat OR *Hamster
}
</code>```

Go Playground Link

答:
Two working samples:

1- Try this:

```<code>package main

import (
    "fmt"
)

type Animal interface {
    color() string
}
type Dog struct {
    Color string
}

func (d Dog) color() string {
    return d.Color
}

type Person struct {
    Name string
    Age  int
    Pet  Animal
}

func main() {
    dog := &Dog{Color: "brown"}
    tom := &Person{Name: "Tom", Age: 13, Pet: dog}
    fmt.Println(tom.Pet.color())
}
</code>```

2- Try this:

```<code>package main

import (
    "fmt"
)

type Animal struct{}
type Dog struct {
    Animal
    Color string
}

type Person struct {
    Name string
    Age  int
    Pet  interface{}
}

func main() {
    dog := &Dog{Color: "brown"}
    tom := &Person{Name: "Tom", Age: 13, Pet: dog}
    fmt.Println(tom.Name)
}
</code>```

Body:
I'm having some issues understanding Go's struct inheritance. I'm trying to do somewhat of an abstraction for an object type. See the example code below:

package main

type Animal struct{}
type Dog struct {
    Animal
    Color string
}

type Person struct {
    Name string
    Age  int
    Pet  *Animal
}

func main() {
    dog := &Dog{Color: "brown"}
    tom := &Person{Name: "Tom", Age: 13, Pet: dog}
}

This is causing a compilation error:

cannot use dog (type *Dog) as type *Animal in field value

What is the correct way to go about doing an abstraction like this? Is it possible in Go?

End goal for the example would be to have different types of Pets - Dog, Cat, Hamser, etc. Then be able to store that into a struct expecting type Animal.

To visualize, something like:

type Person struct {
    Name string
    Age  int
    Pet  *Dog OR *Cat OR *Hamster
}

Go Playground Link

Body:
Two working samples:

1- Try this:

package main

import (
    "fmt"
)

type Animal interface {
    color() string
}
type Dog struct {
    Color string
}

func (d Dog) color() string {
    return d.Color
}

type Person struct {
    Name string
    Age  int
    Pet  Animal
}

func main() {
    dog := &Dog{Color: "brown"}
    tom := &Person{Name: "Tom", Age: 13, Pet: dog}
    fmt.Println(tom.Pet.color())
}

2- Try this:

package main

import (
    "fmt"
)

type Animal struct{}
type Dog struct {
    Animal
    Color string
}

type Person struct {
    Name string
    Age  int
    Pet  interface{}
}

func main() {
    dog := &Dog{Color: "brown"}
    tom := &Person{Name: "Tom", Age: 13, Pet: dog}
    fmt.Println(tom.Name)
}


问:
How to plot line graph with x and y categorical axis?
I'm trying to plot a line graph that compares 2 categorical variables. However I keep running into errors. I've put my code below:</p>

```<code>import matplotlib.pyplot as plt

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing",
"washing"]

fig, ax = plt.subplots()
ax.plot(activity, dog, label="dog")
ax.plot(activity, cat, label="cat")
ax.legend()

plt.show()
</code>```

答:
To provide an answer here: When being run with matplotlib >=2.1, the code from the question

```<code>import matplotlib.pyplot as plt

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing",
"washing"]

fig, ax = plt.subplots()
ax.plot(activity, dog, label="dog")
ax.plot(activity, cat, label="cat")
ax.legend()

plt.show()
</code>```

runs fine and produces

For earlier versions of matplotlib, axes should be numeric. Hence you need to convert the categories into numbers, plot them, then set the ticklabels accordingly.

```<code>import numpy as np
import matplotlib.pyplot as plt

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing",
"washing"]

catu, cati = np.unique(cat, return_inverse=True)
dogu, dogi = np.unique(dog, return_inverse=True)

fig, ax = plt.subplots()
ax.plot(range(len(dog)), dogi, label="dog")
ax.plot(range(len(cat)), cati, label="cat")

ax.set_xticks(range(len(activity)))
ax.set_xticklabels(activity)

ax.set_yticks(range(len(catu)))
ax.set_yticklabels(catu)

ax.legend()
plt.show()
</code>```

Body:
I'm trying to plot a line graph that compares 2 categorical variables. However I keep running into errors. I've put my code below:

import matplotlib.pyplot as plt

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing",
"washing"]

fig, ax = plt.subplots()
ax.plot(activity, dog, label="dog")
ax.plot(activity, cat, label="cat")
ax.legend()

plt.show()

Body:
To provide an answer here: When being run with matplotlib >=2.1, the code from the question

import matplotlib.pyplot as plt

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing",
"washing"]

fig, ax = plt.subplots()
ax.plot(activity, dog, label="dog")
ax.plot(activity, cat, label="cat")
ax.legend()

plt.show()

runs fine and produces

For earlier versions of matplotlib, axes should be numeric. Hence you need to convert the categories into numbers, plot them, then set the ticklabels accordingly.

import numpy as np
import matplotlib.pyplot as plt

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing",
"washing"]

catu, cati = np.unique(cat, return_inverse=True)
dogu, dogi = np.unique(dog, return_inverse=True)

fig, ax = plt.subplots()
ax.plot(range(len(dog)), dogi, label="dog")
ax.plot(range(len(cat)), cati, label="cat")

ax.set_xticks(range(len(activity)))
ax.set_xticklabels(activity)

ax.set_yticks(range(len(catu)))
ax.set_yticklabels(catu)

ax.legend()
plt.show()


问:
Python ASYNC IO Image Processing
I'm currently taking images from a webcam that should be processed as soon as they are captured. The code uses the cv2.videocapture() function.

Idea: As soon as an Image is captured I want to use the time the system needs to capture a new image for computation on the previous image.

To achieve this task I use the asyncio library.

First of all I define a producer function that produces n images which should be stored in a queue:

```<code>async def produce(queue, n):
    for x in range(n):
        # produce an item
        print('producing {}/{}'.format(x, n))
        # simulate i/o operation using sleep
        await asyncio.sleep(random.random())
        item = obtainImage()
        z.append(x)
        # put the item in the queue
        await queue.put(item)
</code>```

After that I implemented a consumer function which waits for an entry in the queue and computes some image features (here a simple threshold):

```<code> async def consume(queue):
        while True:
            # wait for an item from the producer
            # Load the image stored in the queue
            item = await queue.get()
            # process the item and store value
            ret,thresh1 = cv2.threshold(item,127,255,cv2.THRESH_BINARY)

            # simulate i/o operation using sleep
            await asyncio.sleep(random.random())

            # Notify the queue that the item has been processed
            queue.task_done()

            #Return the Processesed image
            return thresh1
</code>```

To start the functions I created a run function and added it into an event loop (The run method contains a parameter of how many images i want to process):

```<code>async def run(n):
    queue = asyncio.Queue()
    # schedule the consumer
    consumer = asyncio.ensure_future(consume(queue))
    # run the producer and wait for completion
    await produce(queue, n)
    # wait until the consumer has processed all items
    await queue.join()
    # the consumer is still awaiting for an item, cancel it
    consumer.cancel()

  loop = asyncio.get_event_loop()
  loop.run_until_complete(run(10))
  print(loop)
  loop.close()
</code>```

As long as I use print statements I get an async output like this:

producing 0/10

producing 1/10

consuming 0...

producing 2/10

consuming 1...

producing 3/10

consuming 2...

producing 4/10

consuming 3...

Which is exactly what I desire in terms of order. However, I can`t get back any thresholded image. What am I missing?

Thank you in advance

答:
Minimal example with global queue for results returning (tested with Python 3.5.2)

```<code>import asyncio
import random

outQ = asyncio.Queue()

async def produce(queue, n):
    for x in range(n):
        print('producing {}/{}'.format(x, n))
        await asyncio.sleep(random.random())
        item = x
        await queue.put(item)

async def consume(queue):
    while True:
        print('consume ')
        item = await queue.get()
        thresh1 = item**2
        print("... adding %d" % thresh1)
        await outQ.put(thresh1)
        await asyncio.sleep(random.random())
        queue.task_done()

async def run(n):
    queue = asyncio.Queue()
    consumer = asyncio.ensure_future(consume(queue))
    await produce(queue, n)
    await queue.join()
    consumer.cancel()

loop = asyncio.get_event_loop()
loop.run_until_complete(run(10))
loop.close()

while not outQ.empty():
    print(outQ.get_nowait())
</code>```

Output:

```<code>...
producing 9/10
... adding 64
consume
... adding 81
consume
0
1
4
9
16
25
36
49
64
81
</code>```

ContentLicense: CC BY-SA 4.0

Title: Python ASYNC IO Image Processing

Body:
I'm currently taking images from a webcam that should be processed as soon as they are captured. The code uses the cv2.videocapture() function.

Idea: As soon as an Image is captured I want to use the time the system needs to capture a new image for computation on the previous image.

To achieve this task I use the asyncio library.

First of all I define a producer function that produces n images which should be stored in a queue:

async def produce(queue, n):
    for x in range(n):
        # produce an item
        print('producing {}/{}'.format(x, n))
        # simulate i/o operation using sleep
        await asyncio.sleep(random.random())
        item = obtainImage()
        z.append(x)
        # put the item in the queue
        await queue.put(item)

After that I implemented a consumer function which waits for an entry in the queue and computes some image features (here a simple threshold):

 async def consume(queue):
        while True:
            # wait for an item from the producer
            # Load the image stored in the queue
            item = await queue.get()
            # process the item and store value
            ret,thresh1 = cv2.threshold(item,127,255,cv2.THRESH_BINARY)

            # simulate i/o operation using sleep
            await asyncio.sleep(random.random())

            # Notify the queue that the item has been processed
            queue.task_done()

            #Return the Processesed image
            return thresh1

To start the functions I created a run function and added it into an event loop (The run method contains a parameter of how many images i want to process):

async def run(n):
    queue = asyncio.Queue()
    # schedule the consumer
    consumer = asyncio.ensure_future(consume(queue))
    # run the producer and wait for completion
    await produce(queue, n)
    # wait until the consumer has processed all items
    await queue.join()
    # the consumer is still awaiting for an item, cancel it
    consumer.cancel()

  loop = asyncio.get_event_loop()
  loop.run_until_complete(run(10))
  print(loop)
  loop.close()

As long as I use print statements I get an async output like this:

producing 0/10

producing 1/10

consuming 0...

producing 2/10

consuming 1...

producing 3/10

consuming 2...

producing 4/10

consuming 3...

Which is exactly what I desire in terms of order. However, I can`t get back any thresholded image. What am I missing?

Thank you in advance

Body:
Minimal example with global queue for results returning (tested with Python 3.5.2)

import asyncio
import random

outQ = asyncio.Queue()

async def produce(queue, n):
    for x in range(n):
        print('producing {}/{}'.format(x, n))
        await asyncio.sleep(random.random())
        item = x
        await queue.put(item)

async def consume(queue):
    while True:
        print('consume ')
        item = await queue.get()
        thresh1 = item**2
        print("... adding %d" % thresh1)
        await outQ.put(thresh1)
        await asyncio.sleep(random.random())
        queue.task_done()

async def run(n):
    queue = asyncio.Queue()
    consumer = asyncio.ensure_future(consume(queue))
    await produce(queue, n)
    await queue.join()
    consumer.cancel()

loop = asyncio.get_event_loop()
loop.run_until_complete(run(10))
loop.close()

while not outQ.empty():
    print(outQ.get_nowait())

Output:

...
producing 9/10
... adding 64
consume
... adding 81
consume
0
1
4
9
16
25
36
49
64
81


问:
Typescript keyboard event : argument of type 'Event' is not assignable to parameter of type 'KeyboardEvent'
I'have the following error even if the code run perfectly:

```<code>"TS2345: Argument of type 'Event' is not assignable to parameter of type 'KeyboardEvent'.
  Property 'altKey' is missing in type 'Event'."

// In a Class

public listenTo = (window: Window) => {
  ['keydown', 'keyup'].forEach(eventName => {
     window.addEventListener(eventName, e => {
       this.handleEvent(e); // <- error here
     });
   });
}

public handleEvent = (event: KeyboardEvent) => {
    const { key } = event;
    //...
}
</code>```

I tried to define the event type to KeyboardEvent, but I have the following error :

```<code> window.addEventListener(eventName, (e:KeyboardEvent) => {
           this.handleEvent(e); // <- error here
         });

 TS2345: Argument of type '(event: KeyboardEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
  Type '(event: KeyboardEvent) => void' is not assignable to type 'EventListenerObject'.
 Property 'handleEvent' is missing in type '(event: KeyboardEvent) => void'.
</code>```

Is there a way to pass through or resolve the issue ?

答:
TypeScript isn't able to make the full leap here, because all it knows is the event name will be a string, so the most general event type is used.

Examples below converted to a stand alone running example - so I've taken things "out of a class" for the demo...

While the strings are keydown and keyup you can guarantee the type safety, and overrule the compiler:

```<code>let listenTo = (window: Window) => {
  ['keydown', 'keyup'].forEach(eventName => {
     window.addEventListener(eventName, e => {
       handleEvent(<any>e);
     });
   });
}

let handleEvent = (event: KeyboardEvent) => {
    const { key } = event;
    //...
}
</code>```

This would fall down if some other string was added to your array of event names.

Full type safety is available when using a string directly, due to specialized signatures:

```<code>  window.addEventListener('keydown', e => {
     handleEvent(e); // e is KeyboardEvent
  });
</code>```

So you could type your array more strongly to get the correct types goodness:

```<code>type KeyboardEventNames = 'keydown' | 'keyup';

let listenTo = (window: Window) => {
  const eventNames: KeyboardEventNames[] = ['keydown', 'keyup'];
  eventNames.forEach(eventName => {
     window.addEventListener(eventName, e => {
       handleEvent(e);
     });
  });
}

let handleEvent = (event: KeyboardEvent) => {
    const { key } = event;
    //...
}
</code>```

In this last example, we restict the type of elements in the array to only keyboard event names, so the compiler now knows it isn't dealing with just any old string, and can infer the event type.

Body:
I'have the following error even if the code run perfectly:

"TS2345: Argument of type 'Event' is not assignable to parameter of type 'KeyboardEvent'.
  Property 'altKey' is missing in type 'Event'."

// In a Class

public listenTo = (window: Window) => {
  ['keydown', 'keyup'].forEach(eventName => {
     window.addEventListener(eventName, e => {
       this.handleEvent(e); // <- error here
     });
   });
}

public handleEvent = (event: KeyboardEvent) => {
    const { key } = event;
    //...
}

I tried to define the event type to KeyboardEvent, but I have the following error :

 window.addEventListener(eventName, (e:KeyboardEvent) => {
           this.handleEvent(e); // <- error here
         });

 TS2345: Argument of type '(event: KeyboardEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
  Type '(event: KeyboardEvent) => void' is not assignable to type 'EventListenerObject'.
 Property 'handleEvent' is missing in type '(event: KeyboardEvent) => void'.

Is there a way to pass through or resolve the issue ?

Body:
TypeScript isn't able to make the full leap here, because all it knows is the event name will be a string, so the most general event type is used.

Examples below converted to a stand alone running example - so I've taken things "out of a class" for the demo...

While the strings are keydown and keyup you can guarantee the type safety, and overrule the compiler:

let listenTo = (window: Window) => {
  ['keydown', 'keyup'].forEach(eventName => {
     window.addEventListener(eventName, e => {
       handleEvent(<any>e);
     });
   });
}

let handleEvent = (event: KeyboardEvent) => {
    const { key } = event;
    //...
}

This would fall down if some other string was added to your array of event names.

Full type safety is available when using a string directly, due to specialized signatures:

  window.addEventListener('keydown', e => {
     handleEvent(e); // e is KeyboardEvent
  });

So you could type your array more strongly to get the correct types goodness:

type KeyboardEventNames = 'keydown' | 'keyup';

let listenTo = (window: Window) => {
  const eventNames: KeyboardEventNames[] = ['keydown', 'keyup'];
  eventNames.forEach(eventName => {
     window.addEventListener(eventName, e => {
       handleEvent(e);
     });
  });
}

let handleEvent = (event: KeyboardEvent) => {
    const { key } = event;
    //...
}

In this last example, we restict the type of elements in the array to only keyboard event names, so the compiler now knows it isn't dealing with just any old string, and can infer the event type.


问:
How to change 'sort glyph icon' color in DataGridView of Windows Form C#?
I've changed the column header color by default. Now, I want to change the 'sort glyph icon' color in DataGridView of Windows Form C# when it gets sorted:

See the above picture. The column is sorted but icon's color makes it's visibility inadequate.

Please let me know if it's color can be changed. Thanks!

答:
There is no property for changing color of sort icon. As an option to change it, you can handle CellPainting event and draw the cell yourself.

Example

```<code>private void dgv1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    var grid = (DataGridView)sender;
    var sortIconColor = Color.Red;
    if (e.RowIndex == -1 && e.ColumnIndex > -1)
    {
        using (var b = new SolidBrush(BackColor))
        {
            //Draw Background
            e.PaintBackground(e.CellBounds, false);

            //Draw Text Default
            //e.Paint(e.CellBounds, DataGridViewPaintParts.ContentForeground);

            //Draw Text Custom
            TextRenderer.DrawText(e.Graphics, string.Format("{0}", e.FormattedValue),
                e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Left);

            //Draw Sort Icon
            if (grid.SortedColumn?.Index == e.ColumnIndex)
            {
                var sortIcon = grid.SortOrder == SortOrder.Ascending ? "▲":"▼";

                //Or draw an icon here.
                TextRenderer.DrawText(e.Graphics, sortIcon,
                    e.CellStyle.Font, e.CellBounds, sortIconColor,
                    TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            }

            //Prevent Default Paint
            e.Handled = true;
        }
    }
}
</code>```

Draw Visual Styles Sort Icon

To see drawing with Visual Styles sort icon, take a look at this post.

Body:
There is no property for changing color of sort icon. As an option to change it, you can handle CellPainting event and draw the cell yourself.

Example

private void dgv1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    var grid = (DataGridView)sender;
    var sortIconColor = Color.Red;
    if (e.RowIndex == -1 && e.ColumnIndex > -1)
    {
        using (var b = new SolidBrush(BackColor))
        {
            //Draw Background
            e.PaintBackground(e.CellBounds, false);

            //Draw Text Default
            //e.Paint(e.CellBounds, DataGridViewPaintParts.ContentForeground);

            //Draw Text Custom
            TextRenderer.DrawText(e.Graphics, string.Format("{0}", e.FormattedValue),
                e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Left);

            //Draw Sort Icon
            if (grid.SortedColumn?.Index == e.ColumnIndex)
            {
                var sortIcon = grid.SortOrder == SortOrder.Ascending ? "▲":"▼";

                //Or draw an icon here.
                TextRenderer.DrawText(e.Graphics, sortIcon,
                    e.CellStyle.Font, e.CellBounds, sortIconColor,
                    TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            }

            //Prevent Default Paint
            e.Handled = true;
        }
    }
}

Draw Visual Styles Sort Icon

To see drawing with Visual Styles sort icon, take a look at this post.


问:
Infinite loop with Angular expression binding
I have an angular application that displays the value returned by a controller method through a simple expression binding:

{{getValue()}}

```

<p>If the method in question just returns a value, the method is called twice, and that is strange enough:</p>

<pre class="lang-js prettyprint-override"><code>$scope.getValue = function(){
  return 'some value';
}
</code>```

But if the method does some asynchronous work such as getting a file from the server, the code goes into an infinite loop:

$scope.getValueAsync = function(){
  $http.get('myfile.html')
    .success(function (data, status, headers, config) {
      return 'some async value';
    });

  return 'file not found'; // same value returned every time but $digest cycle still loops
}
```

I'm new to Angular so have probably missed something basic here, but can someone please explain what is going on?

Plunker

Here's a plunker to play with http://plnkr.co/7BriYDbdVJvIoIigQcTU

答: I met the same problem as you, to fix the problem we can cache the results of the function. For this purpose I prefer to use Lo-Dash’s memoize function. I create a demo to show you how i managed to fix this problem.The following link contains the demo:http://plnkr.co/edit/KBmk4J2ZCt0SsmZlnKZi?p=preview

Body:
I have an angular application that displays the value returned by a controller method through a simple expression binding:

{{getValue()}}

If the method in question just returns a value, the method is called twice, and that is strange enough:

$scope.getValue = function(){
  return 'some value';
}

But if the method does some asynchronous work such as getting a file from the server, the code goes into an infinite loop:

$scope.getValueAsync = function(){
  $http.get('myfile.html')
    .success(function (data, status, headers, config) {
      return 'some async value';
    });

  return 'file not found'; // same value returned every time but $digest cycle still loops
}

I'm new to Angular so have probably missed something basic here, but can someone please explain what is going on?

Plunker

Here's a plunker to play with http://plnkr.co/7BriYDbdVJvIoIigQcTU


问:
Select multiple objects with the same name
So I have a sheet with some pictures. All of these are just a copy paste of the original picture so they all have the same name "Flower".

I want to select all of them and flip them. But it will only select the original, how do I get past this? I tried incorporating a loop as well, without luck.

```<code>Sub Test()
    ActiveSheet.Shapes.Range(Array("Flower")).Select
    Selection.ShapeRange.Flip msoFlipHorizontal
End Sub
</code>```

I know that I could simply rename them to Flower1, Flower2 etc. but the plan is to use this for a lot of pictures, so it would take to long to change manually. If it could all be done with a loop, that would be fine, but then I would still have the same problem as above.

答:
There are two objects in VBA that could be useful - the shape collection named Shapes and the Shape itself. Thus, you can loop through the collection like this:

```<code>Sub Test()

    Dim shShape         As Shape
    Dim shCollection    As Shapes

    Set shCollection = ActiveSheet.Shapes

    For Each shShape In shCollection
        shShape.Flip msoFlipHorizontal
    Next shShape

End Sub
</code>```

Body:
So I have a sheet with some pictures. All of these are just a copy paste of the original picture so they all have the same name "Flower".

I want to select all of them and flip them. But it will only select the original, how do I get past this? I tried incorporating a loop as well, without luck.

Sub Test()
    ActiveSheet.Shapes.Range(Array("Flower")).Select
    Selection.ShapeRange.Flip msoFlipHorizontal
End Sub

I know that I could simply rename them to Flower1, Flower2 etc. but the plan is to use this for a lot of pictures, so it would take to long to change manually. If it could all be done with a loop, that would be fine, but then I would still have the same problem as above.

Body:
There are two objects in VBA that could be useful - the shape collection named Shapes and the Shape itself. Thus, you can loop through the collection like this:

Sub Test()

    Dim shShape         As Shape
    Dim shCollection    As Shapes

    Set shCollection = ActiveSheet.Shapes

    For Each shShape In shCollection
        shShape.Flip msoFlipHorizontal
    Next shShape

End Sub


问:
How to log SQL queries to a log file with CakePHP
I have a CakePHP 1.2 application that makes a number of AJAX calls using the AjaxHelper object.  The AjaxHelper makes a call to a controller function which then returns some data back to the page.

I would like to log the SQL queries that are executed by the AJAX controller functions.  Normally, I would just turn the debug level to 2 in config/core.php, however, this breaks my AJAX functionality because it causes the output SQL queries to be appended to the output that is returned to the client side.

To get around this issue, I would like to be able to log any SQL queries performed to a log file.  Any suggestions?

答: This is a fantastic way to debug things like this, https://github.com/cakephp/debug_kit</p>

ContentLicense: CC BY-SA 2.5


问:
Bitnami RedMine mysql service not restarting
I have a redmine project management system setup on my windows server on MYSQL DB.

I had some issues when tried to restart the redmineMysql service and as  per a article on stackoverflow, I deleted the service from registry and recreated the service using 'sc create redmineMYSQL binpath= "D:\Bitnami\redmine-2.6.0-1\mysql\bin\mysqld.exe"'

Now when I try to restart the service I get a error "error 1053 the service did not respond to the start or control request in a timely fashion"

the time in which the service is restarting, for around 20-25 seconds my mysql is up and available to redmine but then post the error message the mysql goes down again.

答:
ImagePath looks like this:

```<code> "C:\BitNami\REDMIN~1.2-0\apache2\bin\httpd.exe" -k runservice
</code>```

It is of REG_EXPAND_SZ under HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\redmineApache

As for mysql:

This is how default serviceinstall.bat looks like, from: Binami/redmine-2.3.2.-0/mysql/scripts

```<code>@echo off
rem -- Check if argument is INSTALL or REMOVE

if not ""%1"" == ""INSTALL"" goto remove

"C:\BitNami\redmine-2.4.2-0/mysql\bin\mysqld.exe" --install "redmineMySQL" --defaults-file="C:\BitNami\redmine-2.4.2-0/mysql\my.ini"

net start "redmineMySQL" >NUL
goto end

:remove
rem -- STOP SERVICES BEFORE REMOVING

net stop "redmineMySQL" >NUL
"C:\BitNami\redmine-2.4.2-0/mysql\bin\mysqld.exe" --remove "redmineMySQL"

:end
exit
</code>```

Body:
ImagePath looks like this:

 "C:\BitNami\REDMIN~1.2-0\apache2\bin\httpd.exe" -k runservice

It is of REG_EXPAND_SZ under HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\redmineApache

As for mysql:

This is how default serviceinstall.bat looks like, from: Binami/redmine-2.3.2.-0/mysql/scripts

@echo off
rem -- Check if argument is INSTALL or REMOVE

if not ""%1"" == ""INSTALL"" goto remove

"C:\BitNami\redmine-2.4.2-0/mysql\bin\mysqld.exe" --install "redmineMySQL" --defaults-file="C:\BitNami\redmine-2.4.2-0/mysql\my.ini"

net start "redmineMySQL" >NUL
goto end

:remove
rem -- STOP SERVICES BEFORE REMOVING

net stop "redmineMySQL" >NUL
"C:\BitNami\redmine-2.4.2-0/mysql\bin\mysqld.exe" --remove "redmineMySQL"

:end
exit


问:
Cannot remove gerrit trigger server from jenkins
Added a gerrit trigger plugin in the jenkins. While setting up a gerrit server within the gerrit trigger configuration, I cannot remove the server already configured. It simply says

```<code>Cannot remove the last server!
</code>```

But I can edit the server details. Anyone has faced this issue?

```<code>Jenkins ver. 1.653
gerrit trigger version  2.21.1
</code>```

I dont have any job configured with Gerrit Trigger, and this jenkins is a fresh instance. Just have a test job

答:
By the words what I understand is that I cannot remove the last, the final server. That means there should be at least one server configured, I cannot remove all of them. If you want to remove this, you have to create one more and delete the older one.

But not sure why it is so

Body:
Added a gerrit trigger plugin in the jenkins. While setting up a gerrit server within the gerrit trigger configuration, I cannot remove the server already configured. It simply says

Cannot remove the last server!

But I can edit the server details. Anyone has faced this issue?

Jenkins ver. 1.653
gerrit trigger version  2.21.1

I dont have any job configured with Gerrit Trigger, and this jenkins is a fresh instance. Just have a test job


问:
How to move a document in Cloud Firestore?
Can someone help me how to rename, move or update document or collection names in Cloud Firestore?

Also is there anyway that I can access my Cloud Firestore to update my collections or documents from terminal or any application?

答:
Actually there is no move method that allows you to simply move a document from a location to another. You need to create one. For moving a document from a location to another, I suggest you use the following method:

```<code>public void moveFirestoreDocument(DocumentReference fromPath, final DocumentReference toPath) {
    fromPath.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document != null) {
                    toPath.set(document.getData())
                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Log.d(TAG, "DocumentSnapshot successfully written!");
                                fromPath.delete()
                                .addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void aVoid) {
                                            Log.d(TAG, "DocumentSnapshot successfully deleted!");
                                        }
                                })
                                .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            Log.w(TAG, "Error deleting document", e);
                                        }
                                });
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.w(TAG, "Error writing document", e);
                            }
                        });
                } else {
                    Log.d(TAG, "No such document");
                }
            } else {
                Log.d(TAG, "get failed with ", task.getException());
            }
        }
    });
}
</code>```

In which fromPath is the location of the document that you want to be moved and toPath is the location in which you want to move the document.

The flow is as follows:

Get the document from fromPath location.

Write the document to toPath location.

Delete the document from fromPath location.

That's it!

Body:
Actually there is no move method that allows you to simply move a document from a location to another. You need to create one. For moving a document from a location to another, I suggest you use the following method:

public void moveFirestoreDocument(DocumentReference fromPath, final DocumentReference toPath) {
    fromPath.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document != null) {
                    toPath.set(document.getData())
                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Log.d(TAG, "DocumentSnapshot successfully written!");
                                fromPath.delete()
                                .addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void aVoid) {
                                            Log.d(TAG, "DocumentSnapshot successfully deleted!");
                                        }
                                })
                                .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            Log.w(TAG, "Error deleting document", e);
                                        }
                                });
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.w(TAG, "Error writing document", e);
                            }
                        });
                } else {
                    Log.d(TAG, "No such document");
                }
            } else {
                Log.d(TAG, "get failed with ", task.getException());
            }
        }
    });
}

In which fromPath is the location of the document that you want to be moved and toPath is the location in which you want to move the document.

The flow is as follows:

Get the document from fromPath location.

Write the document to toPath location.

Delete the document from fromPath location.

That's it!


问:
Add new mime type for media
I want to upload some dfxp files to media by this code:

```<code>if ( !function_exists('media_handle_upload') ) {
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}

  $id = media_handle_sideload(array('name' =>'test.dfxp', 'tmp_name' =>****/test.dfxp' ));
</code>```

But I get this error:

```<code>Sorry, this file type is not permitted for security reasons.
</code>```

even when I put this function above the code to add the mime type:

```<code>function custom_upload_mimes( $existing_mimes ) {
    // add webm to the list of mime types
    $existing_mimes['dfxp'] = 'application/dfxp';
    // return the array back to the function with our added mime type
    return $existing_mimes;
}
add_filter('upload_mimes', 'custom_upload_mimes');
</code>```

And Yes I checked the mimes and I found it.

How can I solve this ?

答:
I don't think there is mime type called 'application/dfxp' try this

```<code>$existing_mimes['dfxp'] = 'application/xml';
</code>```

insted of

```<code>$existing_mimes['dfxp'] = 'application/dfxp';
</code>```

Title: Add new mime type for media

Body:
I want to upload some dfxp files to media by this code:

if ( !function_exists('media_handle_upload') ) {
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}

  $id = media_handle_sideload(array('name' =>'test.dfxp', 'tmp_name' =>****/test.dfxp' ));

But I get this error:

Sorry, this file type is not permitted for security reasons.

even when I put this function above the code to add the mime type:

function custom_upload_mimes( $existing_mimes ) {
    // add webm to the list of mime types
    $existing_mimes['dfxp'] = 'application/dfxp';
    // return the array back to the function with our added mime type
    return $existing_mimes;
}
add_filter('upload_mimes', 'custom_upload_mimes');

And Yes I checked the mimes and I found it.

How can I solve this ?

Body:
I don't think there is mime type called 'application/dfxp' try this

$existing_mimes['dfxp'] = 'application/xml';

insted of

$existing_mimes['dfxp'] = 'application/dfxp';


问:
reactjs - unit testing with enzyme
I am oretty new to react and am trying to unit test the following piece of code that I have in my react component

```<code>import React,{Component} from 'react';

const styleSheet = document.styleSheets[0];

const keyframes =
  `@-webkit-keyframes pulse {
    0% {
      transform: scale(0.9);
      opacity: 0.6;
    }
    50% {
      transform: scale(1);
      opacity: 1;
    }
    100% {
      transform: scale(0.9);
      opacity: 0.6;
    }
  }`;

styleSheet.insertRule(keyframes, styleSheet.cssRules.length);
const style = {
  animation: 'pulse 5.5s infinite ease-in-out'
};

class someclass extends Component {

  render() {
    return (
      <svg style={style}>

      </svg>
    );
  }
}

export default someclass;
</code>```

This is my test file:

```<code>import React from 'react'
import {shallow, mount, render} from 'enzyme'
import {expect} from 'chai'
import someclassfrom '.../src/components/someclass';

describe('someclass', () => {
  it('should have the main svg', () => {
    const wrapper = shallow(<someclass/>);
    expect(wrapper.find('svg')).to.have.length(1);

  })
})
</code>```

but I keep on getting the following error:

```<code>Cannot read property '0' of undefined
</code>```

How I can mock the same? Thanks in advance

答:
@pj013 for unit testing of your component. you can use Jest + Enzyme combination:

```<code>expect(wrapper.find('svg').length).toEqual(1);
</code>```

or

```<code>expect(wrapper.find('svg').length).toBe(1);
</code>```

Title: reactjs - unit testing with enzyme

Body:
I am oretty new to react and am trying to unit test the following piece of code that I have in my react component

import React,{Component} from 'react';

const styleSheet = document.styleSheets[0];

const keyframes =
  `@-webkit-keyframes pulse {
    0% {
      transform: scale(0.9);
      opacity: 0.6;
    }
    50% {
      transform: scale(1);
      opacity: 1;
    }
    100% {
      transform: scale(0.9);
      opacity: 0.6;
    }
  }`;

styleSheet.insertRule(keyframes, styleSheet.cssRules.length);
const style = {
  animation: 'pulse 5.5s infinite ease-in-out'
};

class someclass extends Component {

  render() {
    return (
      <svg style={style}>

      </svg>
    );
  }
}

export default someclass;

This is my test file:

import React from 'react'
import {shallow, mount, render} from 'enzyme'
import {expect} from 'chai'
import someclassfrom '.../src/components/someclass';

describe('someclass', () => {
  it('should have the main svg', () => {
    const wrapper = shallow(<someclass/>);
    expect(wrapper.find('svg')).to.have.length(1);

  })
})

but I keep on getting the following error:

Cannot read property '0' of undefined

How I can mock the same? Thanks in advance

Body:
@pj013 for unit testing of your component. you can use Jest + Enzyme combination:

expect(wrapper.find('svg').length).toEqual(1);

or

expect(wrapper.find('svg').length).toBe(1);


问:
Does OpenGL care if I work with large numbers?
For example, I could relate the positions where I draw my entities to the screen before sending them to OpenGL - or: I give OpenGL the direct coordinates, relative to the game world, which are of course in a much larger scale.

Is drawing with large vertex coordinates slow?

答:
Speed of larger values will be the same as smaller values of the same data type.  But if you want more than the normal 32bit precision and enable something like GL_EXT_vertex_attrib_64bit, then there may be performance penalties for that.

Large values are allowed, but one extra thing to watch out for other than the standard floating point precision issues is the precision of the depth buffer.

The depth precision is non-linearly distributed.  So it is more precise close up and less precise for things far away.  So if you want to be able to use a wide range of values for vertex coordinates, be aware that you may see z-fighting artifacts if you intend to render giant objects very far away from the camera very small things close to the camera.  Setting your near and far clip planes as close as possible to your actual scene extents will help but may not be enough to fix the problem.  See http://www.opengl.org/resources/faq/technical/depthbuffer.htm, especially the last two points for more details.

Also, I know you asked about vertex positions, but texture coordinates may have additional precision limits beyond normal floating point rules.  Assigning a texture coordinate of (9999999.5, 9999999.5) and expecting it to wrap properly to the (0..1, 0..1) range may not work as you expect (depending on implementation/hardware).


问:
Jhipster - Customize CRUD Interface
Is there any way to change the code that generate CRUD interface in Jhipster .

What we trying to do is : we need to add new buttons in all CRUD interfaces , and changing some layout design .

So please guide me how to do that if that possible .

答:
It's currently not possible at generator level unless you want to fork it, maybe in the future when blueprints get implemented.

So now, you just generate code and modify it manually and when you will run jhipster upgrade to keep up with JHipster's evolutions, the upgrade generator will use git to merge you manual changes with generated code.

Title: Jhipster - Customize CRUD Interface


问:
Google maps not showing on Ionic when the plugin is used
I want to display maps in my application but Google map isn't showing up. I have made my application on Ionic and I have used the Cordova Google Maps plugin. Here is the link to my code. Please help me. </p>

答:
Try to add this in config.xml plugins list:</p>

```<code><plugin name="cordova-plugin-googlemaps" spec="~2.0.6">
    <variable name="API_KEY_FOR_ANDROID" value="Your_key" />
</plugin>
</code>```

Body:
Try to add this in config.xml plugins list:

<plugin name="cordova-plugin-googlemaps" spec="~2.0.6">
    <variable name="API_KEY_FOR_ANDROID" value="Your_key" />
</plugin>


问:
Can't see the bottom of screen when using an ion-segment in the screen
I'm using the ion-grid / ion-row / ion-col to define a form and it works fine. On the top of this form, I'm also using an ion-segment to implement some tabs:

```<code><ion-header no-border>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title class="home-toolbar-background">Mes sports</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <div padding *ngIf="items && items.length > 0">
    <ion-segment text-center [(ngModel)]="item"
                 (ngModelChange)="onItemChange($event)">
      <ion-segment-button value="item1" *ngIf="hasSport('item1')">
        Item1
      </ion-segment-button>
      <ion-segment-button value="item2" *ngIf="hasSport('item2')">
        Item2
      </ion-segment-button>
      <ion-segment-button value="item3" *ngIf="hasSport('item3')">
        Item3
      </ion-segment-button>
      (...)
    </ion-segment>
  </div>

  <ion-grid>
    ...
  </ion-grid>
</ion-content>
</code>```

It works fine within the browser in development mode but, in IonicView, I can't reach the end of the form by scrolling. It seems the height of the screen is calculated without the height of the tabs block.

Note that this screen is part of

```<code><ion-tabs>
  <ion-tab tabIcon="pricetag" tabTitle="Tab1" [root]="tab1"></ion-tab>
  <ion-tab tabIcon="calendar" tabTitle="Tab2" [root]="tab2"></ion-tab>
  <ion-tab tabIcon="walk" tabTitle="Items" [root]="tabItems"></ion-tab> <--------------
  <ion-tab tabIcon="person" tabTitle="Tab3" [root]="tab3"></ion-tab>
  <ion-tab tabIcon="chatboxes" tabTitle="Notifs" [root]="tabNotifications"></ion-tab>
</ion-tabs>
</code>```

Thanks very much for your help!

答:
I too faced similar issue and it might look silly but it does the trick.

At the end of your ion-content your

```<code><ion-content padding>
  <div padding *ngIf="items && items.length > 0">
    <ion-segment text-center [(ngModel)]="item"
                 (ngModelChange)="onItemChange($event)">
      <ion-segment-button value="item1" *ngIf="hasSport('item1')">
        Item1
      </ion-segment-button>
      <ion-segment-button value="item2" *ngIf="hasSport('item2')">
        Item2
      </ion-segment-button>
      <ion-segment-button value="item3" *ngIf="hasSport('item3')">
        Item3
      </ion-segment-button>
      (...)
    </ion-segment>
  </div>

  <ion-grid>
    ...
  </ion-grid>

<div padding></div>
<div padding></div>
</ion-content>
</code>```

What happens is .scroll-content is been occupied till the bottom of the screen.
and tabs are placed above the .scroll-content NOTE: tabs are not a part of the respected Screen.thats why we are faceing this issue will solve just by bottom of the screen upto the tabs min-height:58px will solve it

Body:
I'm using the ion-grid / ion-row / ion-col to define a form and it works fine. On the top of this form, I'm also using an ion-segment to implement some tabs:

<ion-header no-border>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title class="home-toolbar-background">Mes sports</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

 0">
    <ion-segment text-center [(ngModel)]="item"
                 (ngModelChange)="onItemChange($event)">
      <ion-segment-button value="item1" *ngIf="hasSport('item1')">
        Item1
      </ion-segment-button>
      <ion-segment-button value="item2" *ngIf="hasSport('item2')">
        Item2
      </ion-segment-button>
      <ion-segment-button value="item3" *ngIf="hasSport('item3')">
        Item3
      </ion-segment-button>
      (...)
    </ion-segment>

  <ion-grid>
    ...
  </ion-grid>
</ion-content>

It works fine within the browser in development mode but, in IonicView, I can't reach the end of the form by scrolling. It seems the height of the screen is calculated without the height of the tabs block.

Note that this screen is part of

<ion-tabs>
  <ion-tab tabIcon="pricetag" tabTitle="Tab1" [root]="tab1"></ion-tab>
  <ion-tab tabIcon="calendar" tabTitle="Tab2" [root]="tab2"></ion-tab>
  <ion-tab tabIcon="walk" tabTitle="Items" [root]="tabItems"></ion-tab> <--------------
  <ion-tab tabIcon="person" tabTitle="Tab3" [root]="tab3"></ion-tab>
  <ion-tab tabIcon="chatboxes" tabTitle="Notifs" [root]="tabNotifications"></ion-tab>
</ion-tabs>

Thanks very much for your help!

Body:
I too faced similar issue and it might look silly but it does the trick.

At the end of your ion-content your <div padding></div>

<ion-content padding>
  <div padding *ngIf="items && items.length > 0">
    <ion-segment text-center [(ngModel)]="item"
                 (ngModelChange)="onItemChange($event)">
      <ion-segment-button value="item1" *ngIf="hasSport('item1')">
        Item1
      </ion-segment-button>
      <ion-segment-button value="item2" *ngIf="hasSport('item2')">
        Item2
      </ion-segment-button>
      <ion-segment-button value="item3" *ngIf="hasSport('item3')">
        Item3
      </ion-segment-button>
      (...)
    </ion-segment>
  </div>

  <ion-grid>
    ...
  </ion-grid>

<div padding></div>
<div padding></div>
</ion-content>

What happens is .scroll-content is been occupied till the bottom of the screen.
and tabs are placed above the .scroll-content NOTE: tabs are not a part of the respected Screen.thats why we are faceing this issue will solve just by bottom of the screen upto the tabs min-height:58px will solve it


问:
Bash : how to rename files that have two extentions?
I call a small program to convert .tap files (retrogaming) into .wav audio files. The program output the new file and just add the .wav extention
example : "file.tap" becomes "file.tap.wav".

I wrote a tiny script to batch the conversion. It works but I cannot manage to rename the file at the end so to remove the ".tap" in the filename.
Note that sometime the original file has lowercase or uppercase.

here is my code. Any help is welcome.
My idea was to 'erase' the ".tap" or ".TAP" in the final filename.
nb : I must use $file.wav like that in the instruction, otherwise it doesn't work.
thank you for your help

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

for file in `ls`;
do
    ./tape_converter -11 -a $file $file.wav ;
    mv $file ${file/\.tap\.wav/\.wav/};

done
</code>```

答:
Here is my final code. Thanks to
thanasisp. It works fine. Happy.</p>

```<code> for i in *;
    do mv "$i" "$(echo $i|tr A-Z a-z)";
 done

 mkdir output

 for f in *.tap;
 do
         ./tape_converter -11 -a $f ${f%.*}.wav ;
         mv *.wav output/
 done
</code>```

Body:
I call a small program to convert .tap files (retrogaming) into .wav audio files. The program output the new file and just add the .wav extention
example : "file.tap" becomes "file.tap.wav".

I wrote a tiny script to batch the conversion. It works but I cannot manage to rename the file at the end so to remove the ".tap" in the filename.
Note that sometime the original file has lowercase or uppercase.

here is my code. Any help is welcome.
My idea was to 'erase' the ".tap" or ".TAP" in the final filename.
nb : I must use $file.wav like that in the instruction, otherwise it doesn't work.
thank you for your help

#!/bin/bash

for file in `ls`;
do
    ./tape_converter -11 -a $file $file.wav ;
    mv $file ${file/\.tap\.wav/\.wav/};

done

Body:
Here is my final code. Thanks to
thanasisp. It works fine. Happy.

 for i in *;
    do mv "$i" "$(echo $i|tr A-Z a-z)";
 done

 mkdir output

 for f in *.tap;
 do
         ./tape_converter -11 -a $f ${f%.*}.wav ;
         mv *.wav output/
 done


问:
Complex text file to XML-File transformation
I want to create a XML-File with following .txt.

The following objects have all the same structure. Is it possible to create a XML?

I don´t need the whole content of the .txt. Only "Information ObjectX, Delta X, Delta Y, Delta Z, all Rotations, CALLOUT and PART_TYPE" are important and neccessary.

At its best, I want to convert these Files directly in a C# program.

Thanks for your help!

```<code> ============================================================
Created by             : Muster
Date                           :  13.11.2017 10:10:10
Activated component            : File
Node name                      :  abc123abc
============================================================
Information Object # 1

Name                 Object1
File-Path        FilePath
Component-Path       Component-Path
Typ                  Component

Color                2 (Green)
Component-Typ        Body
Version          301   01 Jan 2017 10:10 (Created by Muster)

Object is visible

Positions:

Delta X              =   5.00000000010
Delta Y              =   16.0000000001
Delta Z              =   20.0000000200

Rotations:

X-vector             XC =    0.0                  X =    0.0
                     YC =    1.0                  Y =    1.0
                     ZC =    0.0                  Z =    0.0

Y-vector             XC =   -1.0                  X =   -1.0
                     YC =    0.0                  Y =    0.0
                     ZC =    0.0                  Z =    0.0

Z-vektor             XC =    0.0                  X =    0.0
                     YC =    0.0                  Y =    0.0
                     ZC =    1.0                  Z =    1.0

Component is xxx
3 Rotations- and Translations available

------------------------------------------------------------

------------------------------------------------------------

CALLOUT    = 4890 (string)
PART_NAME = body head (string)
PART_TYPE = Item (string)

************************************************************

Information Object # 2

Name                 Object2
File-Path        FilePath
Component-Path       Component-Path
Typ                  Component

Color                2 (Green)
Component-Typ        Body
Version          301   01 Jan 2017 10:10 (Created by Muster)

Object is visible

Positions:

Delta X              =   5.00000000010
Delta Y              =   25.0000000000
Delta Z              =   20.000000200

Rotations:

X-vector             XC =    0.0                  X =    0.0
                     YC =    1.0                  Y =    1.0
                     ZC =    0.0                  Z =    0.0

Y-vector             XC =   -1.0                  X =   -1.0
                     YC =    0.0                  Y =    0.0
                     ZC =    0.0                  Z =    0.0

Z-vektor             XC =    0.0                  X =    0.0
                     YC =    0.0                  Y =    0.0
                     ZC =    1.0                  Z =    1.0

Component is xxx
3 Rotations- and Translations available

------------------------------------------------------------
------------------------------------------------------------

CALLOUT    = 4891 (string)
PART_NAME = body head (string)
PART_TYPE = Item (string)
</code>```

答:
As requested here is part of the reader that reads the Delta X, Y & Z.
You can read the line and check if it StartsWith Delta. You can Split the line on the equals sign and Trim the string and then parse to a decimal value. You can then repeat this for the other Delta values.

```<code>//values to store the delta values in
decimal deltaX, deltaY, deltaZ;
//The reader for the text file
using (var reader = new StreamReader("filename.txt"))
{
    string line;
    //read file line by line
    while ((line = reader.ReadLine()) != null)
    {

        //Check if line starts with Delta
        if (line.StartsWith("Delta"))
        {
            //For this line you can split by  '=' and then read the second value in the array, trim the string and parse to a decimal value
            deltaX = decimal.Parse(line.Split(new[] {'='})[1].Trim());
            //move reader to next line as we know it will be DeltaY & repeat
            reader.ReadLine();
            deltaY = decimal.Parse(line.Split(new[] { '=' })[1].Trim());
            reader.ReadLine();
            deltaZ = decimal.Parse(line.Split(new[] { '=' })[1].Trim());
        }
    }
}
</code>```

Feel free to have a go at the Part_X and other lines you want to read. If you have any problems add the code to the question and people will help where they can.

Body:
I want to create a XML-File with following .txt.

The following objects have all the same structure. Is it possible to create a XML?

I don´t need the whole content of the .txt. Only "Information ObjectX, Delta X, Delta Y, Delta Z, all Rotations, CALLOUT and PART_TYPE" are important and neccessary.

At its best, I want to convert these Files directly in a C# program.

Thanks for your help!

 ============================================================
Created by             : Muster
Date                           :  13.11.2017 10:10:10
Activated component            : File
Node name                      :  abc123abc
============================================================
Information Object # 1

Name                 Object1
File-Path        FilePath
Component-Path       Component-Path
Typ                  Component

Color                2 (Green)
Component-Typ        Body
Version          301   01 Jan 2017 10:10 (Created by Muster)

Object is visible

Positions:

Delta X              =   5.00000000010
Delta Y              =   16.0000000001
Delta Z              =   20.0000000200

Rotations:

X-vector             XC =    0.0                  X =    0.0
                     YC =    1.0                  Y =    1.0
                     ZC =    0.0                  Z =    0.0

Y-vector             XC =   -1.0                  X =   -1.0
                     YC =    0.0                  Y =    0.0
                     ZC =    0.0                  Z =    0.0

Z-vektor             XC =    0.0                  X =    0.0
                     YC =    0.0                  Y =    0.0
                     ZC =    1.0                  Z =    1.0

Component is xxx
3 Rotations- and Translations available

------------------------------------------------------------

------------------------------------------------------------

CALLOUT    = 4890 (string)
PART_NAME = body head (string)
PART_TYPE = Item (string)

************************************************************

Information Object # 2

Name                 Object2
File-Path        FilePath
Component-Path       Component-Path
Typ                  Component

Color                2 (Green)
Component-Typ        Body
Version          301   01 Jan 2017 10:10 (Created by Muster)

Object is visible

Positions:

Delta X              =   5.00000000010
Delta Y              =   25.0000000000
Delta Z              =   20.000000200

Rotations:

X-vector             XC =    0.0                  X =    0.0
                     YC =    1.0                  Y =    1.0
                     ZC =    0.0                  Z =    0.0

Y-vector             XC =   -1.0                  X =   -1.0
                     YC =    0.0                  Y =    0.0
                     ZC =    0.0                  Z =    0.0

Z-vektor             XC =    0.0                  X =    0.0
                     YC =    0.0                  Y =    0.0
                     ZC =    1.0                  Z =    1.0

Component is xxx
3 Rotations- and Translations available

------------------------------------------------------------
------------------------------------------------------------

CALLOUT    = 4891 (string)
PART_NAME = body head (string)
PART_TYPE = Item (string)

Body:
As requested here is part of the reader that reads the Delta X, Y & Z.
You can read the line and check if it StartsWith Delta. You can Split the line on the equals sign and Trim the string and then parse to a decimal value. You can then repeat this for the other Delta values.

//values to store the delta values in
decimal deltaX, deltaY, deltaZ;
//The reader for the text file
using (var reader = new StreamReader("filename.txt"))
{
    string line;
    //read file line by line
    while ((line = reader.ReadLine()) != null)
    {

        //Check if line starts with Delta
        if (line.StartsWith("Delta"))
        {
            //For this line you can split by  '=' and then read the second value in the array, trim the string and parse to a decimal value
            deltaX = decimal.Parse(line.Split(new[] {'='})[1].Trim());
            //move reader to next line as we know it will be DeltaY & repeat
            reader.ReadLine();
            deltaY = decimal.Parse(line.Split(new[] { '=' })[1].Trim());
            reader.ReadLine();
            deltaZ = decimal.Parse(line.Split(new[] { '=' })[1].Trim());
        }
    }
}

Feel free to have a go at the Part_X and other lines you want to read. If you have any problems add the code to the question and people will help where they can.