问:
How to do dynamic design in xaml in xamarin forms
I need to dynamic design in xaml. Is there a method such as asp.net mvc razor or another method?</p>

答:
What I want is expanding the page when items add. It solved my problem.

Xaml;

```<code><StackLayout Padding="20">
            <Picker Title="myTitle"
                    SelectedItem="{Binding Selected}"
                    FontSize="15">
                <Picker.Items>
                    <x:String>Item 1</x:String>
                    <x:String>Item 2</x:String>
                </Picker.Items>
            </Picker>

            <Label Text="myLabel"
                   Margin="5,0,0,0"
                   TextColor="Gray"
                   IsVisible="{Binding IsVisible}"
                   FontSize="13"/>
</StackLayout>

</code>```

ViewModel;

```<code>private string _selected;
public string Selected
{
     get { return _selected; }
     set
     {
         _selected = value;
         if (_selected == "Item 1")
         {
             IsVisible = true;
         }
         else if (_selected == "Item 2")
         {
             IsVisible = false;
         }
         OnPropertyChanged("Selected");
     }
}
</code>```

Body:
What I want is expanding the page when items add. It solved my problem.

Xaml;

<StackLayout Padding="20">
            <Picker Title="myTitle"
                    SelectedItem="{Binding Selected}"
                    FontSize="15">
                <Picker.Items>
                    <x:String>Item 1</x:String>
                    <x:String>Item 2</x:String>
                </Picker.Items>
            </Picker>

            <Label Text="myLabel"
                   Margin="5,0,0,0"
                   TextColor="Gray"
                   IsVisible="{Binding IsVisible}"
                   FontSize="13"/>
</StackLayout>

ViewModel;

private string _selected;
public string Selected
{
     get { return _selected; }
     set
     {
         _selected = value;
         if (_selected == "Item 1")
         {
             IsVisible = true;
         }
         else if (_selected == "Item 2")
         {
             IsVisible = false;
         }
         OnPropertyChanged("Selected");
     }
}


来源: stackexchange

问:
Include TeX in Roxygen comments
I want to use TeX in Roxygen comments.

E.g.,

```<code>#' @title   $f(y|\theta)$
#'
#'@description
#'
#'  \begin{eqnarray*}
#'         a + b &=& c \\
#'         a + b &=& c \\
#'         \theta &=& \beta \\
#'  \end{eqnarray*}
#'
#'
#'@references
#'@param
#'@importFrom
#'@seealso
#'@inheritParams
</code>```

Is there some methods such that the PDF manual reflects TeX scripts in Roxygen comments .

答:
Use eqn for inline equations: \eqn{f(x|theta)}. See here about how to document an inline equation for PDF, HTML and ASCII.

Use deqn for equations in blocks. I don't think that the environment eqnarray is available, but the array environment is available:

```<code>\deqn{\begin{array}[ccc] a + b &=& c \\ a + b &=& c \\ \theta &=& \beta \end{array}}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Include TeX in Roxygen comments

Body:
I want to use TeX in Roxygen comments.

E.g.,

#' @title   $f(y|\theta)$
#'
#'@description
#'
#'  \begin{eqnarray*}
#'         a + b &=& c \\
#'         a + b &=& c \\
#'         \theta &=& \beta \\
#'  \end{eqnarray*}
#'
#'
#'@references
#'@param
#'@importFrom
#'@seealso
#'@inheritParams

Is there some methods such that the PDF manual reflects TeX scripts in Roxygen comments .

Body:
Use eqn for inline equations: \eqn{f(x|theta)}. See here about how to document an inline equation for PDF, HTML and ASCII.

Use deqn for equations in blocks. I don't think that the environment eqnarray is available, but the array environment is available:

\deqn{\begin{array}[ccc] a + b &=& c \\ a + b &=& c \\ \theta &=& \beta \end{array}}


问:
C++ macros with define or inline?

Possible Duplicate:

  Inline functions vs Preprocessor macros

Inline functions were introduced in C++ to replace C style macros (#define macroname...), still, I see lots of C++ code using old C style macros rather than inlined functions, are inlined function inferior to old C style macros?

答:
I would say macros are inferior to inlined functions.

Inlined functions are type safe and macros are not. That's the big advantage of them. The compiler is helping you make better code.

With that said, there are a few things that macros can do that functions cannot. There are not many of these things though...

I believe C programmers get used to macros and just continue their habits into C++.

ContentLicense: CC BY-SA 3.0

Title: C++ macros with define or inline?


问:
Simplest code that can host html files in node.js through Cloud Functions hosting?
So, after reading a lot of documentation and tutorials, I realized that node.js can use "var http = require('http')" and "var fs = require('fs')" and some other code lines to serve html files but if it is hosted by Firebase Cloud Functions, that would not work because Firebase Cloud Functions works differently.

Can I get any simple code example how I can serve an html file index.html within node.js for Firebase Cloud Functions hosting?

答:
You can simply host your index.html file by putting it in /public folder and deploy to Firebase Host. https://firebase.google.com/docs/hosting/quickstart

Steps are quick simple.
1. Install FirebaseCLI
2. Call $firebase init - to create the project and generate firebase.json, package.json, a public folder with .html files
3. modify the file and upload using the command $firebase deploy

This works for static (just HTML) or SPA (single page application)

Cloud Function is mostly used to build dynamic websites and API.


问:
Why my loading gif makes my page to load slower?
I used some code to display a gif before my page load but it is
increasing  my page's loading speed...

Here is where I use that code - http://sarkarinaukrihome.com/

JS

```<code>$(window).load(function() {
  // Animate loader off screen
  $(".se-pre-con").fadeOut("fast");;
});
</code>```

HTML

```<code><div class="se-pre-con"></div>
</code>```

CSS

```<code>.no-js #loader {
  display: none;
}

.js #loader {
  display: block;
  position: absolute;
  left: 100px;
  top: 0;
}

.se-pre-con {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: url(Preloader_2.gif) center no-repeat #fff;
}
</code>```

答:
You can see in the picture below the differents loading times of your website's files...
Your image quiz.png seems quite fat so it will take some time to load it...

As you just use it in a small format, you maybe should reduce its size ! ;)

Also, notes that your website is searching for some LOGO.png that it doesn't find ... ( doesn't really matters though )

With chrome's inspector :

Body:
I used some code to display a gif before my page load but it is
increasing  my page's loading speed...

Here is where I use that code - http://sarkarinaukrihome.com/

JS

$(window).load(function() {
  // Animate loader off screen
  $(".se-pre-con").fadeOut("fast");;
});

HTML

CSS

.no-js #loader {
  display: none;
}

.js #loader {
  display: block;
  position: absolute;
  left: 100px;
  top: 0;
}

.se-pre-con {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: url(Preloader_2.gif) center no-repeat #fff;
}


问:
Apollo GraphQL local and global error handling
I'm using Apollo to interact with a GraphQL server in a Web application written in React. I'm trying to implement error handling in the application and relying on apollo-link-error for this.

Now, there are 2 categories of errors that I need to handle:

errors that can be handled locally in the component which does the Apollo query or mutation, i.e. an invalid form field on which I need to show contextual error information

errors that can be handled globally, for example by showing a toast notification displaying error details somewhere in the page

Clearly, once the error is handled locally I need it to not be handled globally, because it doesn't make much sense to show an error message next to a form field and a generic error via a toast message.

The first stumbling block I encountered when trying to implement this is that the global error handling logic triggers before the local error handling logic, which prevents me from being able to intercept the error locally and then find a way to prevent the global logic from kicking in.

I created codesandbox example which sets up an ApolloClient in the simplest possible way, uses the http and error links, and uses the react-apollo Query component to do a query for a resource that doesn't exist, generating an error.

I'm handling the error both in the onError callback of the Query component (so local error handling), and in the apollo-link-error handler (so global error handling), and printing to the console the errors.

It shows that the global error handling logic kicks in before the local error handling. I would need it to be the other way around.

答:
I've published a library called react-apollo-network-status which handles exactly this use case. Let me know if it's useful to you!

The opt-in/-out behaviour for treating some errors locally is implemented by setting a context variable on the operation which can be read in the error link.


问:
Getting a count of records in a core data entity
Does anyone know of an existing function or property that provides a count of the records in a Core Data entity?</p>

答:
```<code>   func getRecordsCount() {
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: _entityName)
        do {
            let count = try context.count(for: fetchRequest)
            print(count)
        } catch {
            print(error.localizedDescription)
        }
    }
</code>```


问:
Rejected reason: We are not able to continue because we cannot locate the in-app purchases within your app
I have a project in flutter. I submitted to the appstore. It reject showing the error as:

We have started the review of your app, but we are not able to continue because we cannot locate the in-app purchases within your app.

Then I removed all the subscriptions code from the project and from the itunes too and submitted to the appstore. And again it rejected saying same error as:

We have started the review of your app, but we are not able to continue because we cannot locate the in-app purchases within your app.

Now I have all deleted subscriptions from the project and itunes too.
Can anyone help to solve this problem? The solutions in stackoverflow couldn't solve my problem.

答: They are not asking you to remove the IAP. They are asking you to tell them how to reach the interface that offers the user the IAP. They don’t see it and they don’t have time to explore. They need instructions. Leave the IAP in, and give them instructions. </p>


问:
Update only part of a page on postback
I have 2 divs, one div has an html button that runs at serverside and generates an rdlc report into reportviewer that is in another div on the same page.
After the postback the whole page refreshes and clears the data in the dropdown I already selected before the postback.
Please how can I prevent the value of the drop down and other controls from being cleared after report generation from postback. UpdatePanel didnt work for me
Thank you

Loading data to the select dropdown

```<code>$(document).ready(function () {
    //$("#assayreport").tableHeadFixer({ 'foot': true });
    "responsive"; true,
        "serverSide"; true,
            "info"; true,
                "stateSave"; true,
                    $.ajax({
                        url: 'RhemaServices.asmx/GetJobs',
                        data: '{"jobnumber":"","clientID":"0","status":"2"}',
                        type: 'POST',
                        dataType: 'json',
                        contentType: "application/json; charset-utf-8",
                        success: function (data) {
                            jobdatavariable = data
                            $.each(data, function (i, item) {
                                $('<option value="' + item.TotalInvoiceValue + '">' + item.JobNumber + '</option>').appendTo('#jobcard');
                            });
                        },
                        error: function (err) {
                            console.log(err)
                        },
                        complete: function () {
                        }

                    });
});

<div class="col-md-4">
            <div class="box box-primary">
                <div class="box-header">
                   <%-- <h3 class="box-title" id="jobidss" style="color: #3C8DBC;">Job Card Details</h3>--%>
                    <div class="box-tools pull-right">
                        <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
                    </div>
                </div>
                <div class="box-body">
                    <div class="col-lg-8">
                        <div class="form-group">
                            <label style="color: red;">Select Job Card </label>
                            <div class=".col-xs-3">
                                <select class="select2  form-control" id="jobcard" name="jobcard" onchange="return getJobNo()">
                                    <option selected="selected"></option>
                                </select>
                            </div>
                        </div>
                        <div style="display: nones;">
                            <span style="float: right">
                                <button id="but_add" class="btn btn-primary fa fa-eye" runat="server" onserverclick="LoadData"> Get Invoice</button></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

   <div class="col-md-8">
            <div class="box box-info">
                <div class="box-header">
                    <h3 class="box-title" id="jobidS" style="color: #3C8DBC;">Gold Assay Invoice</h3>
                    <div class="box-tools pull-right">
                        <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
                    </div>
                </div>
                <div class="box-body" style="display: nones">
                    <form runat="server">
                        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
                        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                            <ContentTemplate>
                                <rsweb:ReportViewer ID="rv" runat="server" Height="800px" Width="100%" SizeToReportContent="True" ShowBackButton="False" ShowCredentialPrompts="False" ShowDocumentMapButton="False" ShowFindControls="False" ShowParameterPrompts="False" ShowPromptAreaButton="False">
                                </rsweb:ReportViewer>
                            </ContentTemplate>
                        </asp:UpdatePanel>

                        <asp:HiddenField ID="jobnumber" runat="server" />
                    </form>
                </div>
            </div>

        </div>
</code>```

C# Code for page load and button click event (LoadData)

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {

        }
    }
    protected  void LoadData(object sender, EventArgs e)
    {
        rv.ProcessingMode = ProcessingMode.Local;
        rv.LocalReport.ReportPath = Server.MapPath("~/Reports/Invoice.rdlc");
        DataTable dt = GetData();

        ReportDataSource datasource = new ReportDataSource("DataSet1", dt);

        rv.LocalReport.DataSources.Clear();
        rv.LocalReport.DataSources.Add(datasource);
        rv.LocalReport.Refresh();

    }
</code>```

答:
so you have binded Dropdown by ajax jquery, in this case what happens that each time you post back jquery's $(document).ready(){} event fires and your dropdown fills value again and resets its values so for solution what you can do is just bind drop down by code behind on page load Event in c# try below code.

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
       jobcard.DataSource=dtJobCard;//get data in this dtJobCard using DB or from wherever you want to get
       jobcard.DataTextField="JobNumber";
       jobcard.DataValueField="TotalInvoiceValue";
       jobcard.DataBind();
    }
}
</code>```

And Make ASP.NET Dropdown control change it like this in aspx code.

```<code><asp:DropDownList ID="jobcard" runat="server">
    </asp:DropDownList>
</code>```

UPDATE
if this is a requirements then you can do following things.
store value in hidden field and check if there is any value in hidden field if yes then fill the ddl and set value else do nothing. below is full code.
Change script code

```<code>    $(document).ready(function () {

        //$("#assayreport").tableHeadFixer({ 'foot': true });
        "responsive"; true,
            "serverSide"; true,
                "info"; true,
                    "stateSave"; true,
                        $.ajax({
                            url: 'RhemaServices.asmx/GetJobs',
                            data: '{"jobnumber":"","clientID":"0","status":"2"}',
                            type: 'POST',
                            dataType: 'json',
                            contentType: "application/json; charset-utf-8",
                            success: function (data) {
                                jobdatavariable = data
                                $.each(data, function (i, item) {
                                    $('<option value="' + item.TotalInvoiceValue + '">' + item.JobNumber + '</option>').appendTo('#jobcard');
                                });
                            },
                            error: function (err) {
                                console.log(err)
                            },
                            complete: function () {
                            }

                        });
            if($('#jobnumber').val()!="")
             {
                $('#jobcard').val($('#jobnumber').val());
             }
    });
</code>```

Create onchange function
 like this

```<code>function getJobNo()
{
   $('#jobnumber').val($('#jobcard').val());
}
</code>```

Synthetically i may be wrong but this logic should work.

Title: Update only part of a page on postback

Body:
I have 2 divs, one div has an html button that runs at serverside and generates an rdlc report into reportviewer that is in another div on the same page.
After the postback the whole page refreshes and clears the data in the dropdown I already selected before the postback.
Please how can I prevent the value of the drop down and other controls from being cleared after report generation from postback. UpdatePanel didnt work for me
Thank you

Loading data to the select dropdown

$(document).ready(function () {
    //$("#assayreport").tableHeadFixer({ 'foot': true });
    "responsive"; true,
        "serverSide"; true,
            "info"; true,
                "stateSave"; true,
                    $.ajax({
                        url: 'RhemaServices.asmx/GetJobs',
                        data: '{"jobnumber":"","clientID":"0","status":"2"}',
                        type: 'POST',
                        dataType: 'json',
                        contentType: "application/json; charset-utf-8",
                        success: function (data) {
                            jobdatavariable = data
                            $.each(data, function (i, item) {
                                $('<option value="' + item.TotalInvoiceValue + '">' + item.JobNumber + '</option>').appendTo('#jobcard');
                            });
                        },
                        error: function (err) {
                            console.log(err)
                        },
                        complete: function () {
                        }

                    });
});

                   <%--
Job Card Details
--%>

                        <button type="button" class="btn btn-box-tool" data-widget="collapse"></button>

                            Select Job Card

                                <select class="select2  form-control" id="jobcard" name="jobcard" onchange="return getJobNo()">
                                    <option selected="selected"></option>
                                </select>

                                <button id="but_add" class="btn btn-primary fa fa-eye" runat="server" onserverclick="LoadData"> Get Invoice</button>

Gold Assay Invoice

                        <button type="button" class="btn btn-box-tool" data-widget="collapse"></button>

                    <form runat="server">
                        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
                        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                            <ContentTemplate>
                                <rsweb:ReportViewer ID="rv" runat="server" Height="800px" Width="100%" SizeToReportContent="True" ShowBackButton="False" ShowCredentialPrompts="False" ShowDocumentMapButton="False" ShowFindControls="False" ShowParameterPrompts="False" ShowPromptAreaButton="False">
                                </rsweb:ReportViewer>
                            </ContentTemplate>
                        </asp:UpdatePanel>

                        <asp:HiddenField ID="jobnumber" runat="server" />
                    </form>

C# Code for page load and button click event (LoadData)

protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {

        }
    }
    protected  void LoadData(object sender, EventArgs e)
    {
        rv.ProcessingMode = ProcessingMode.Local;
        rv.LocalReport.ReportPath = Server.MapPath("~/Reports/Invoice.rdlc");
        DataTable dt = GetData();

        ReportDataSource datasource = new ReportDataSource("DataSet1", dt);

        rv.LocalReport.DataSources.Clear();
        rv.LocalReport.DataSources.Add(datasource);
        rv.LocalReport.Refresh();

    }

Body:
so you have binded Dropdown by ajax jquery, in this case what happens that each time you post back jquery's $(document).ready(){} event fires and your dropdown fills value again and resets its values so for solution what you can do is just bind drop down by code behind on page load Event in c# try below code.

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
       jobcard.DataSource=dtJobCard;//get data in this dtJobCard using DB or from wherever you want to get
       jobcard.DataTextField="JobNumber";
       jobcard.DataValueField="TotalInvoiceValue";
       jobcard.DataBind();
    }
}

And Make ASP.NET Dropdown control change it like this in aspx code.

<asp:DropDownList ID="jobcard" runat="server">
    </asp:DropDownList>

UPDATE
if this is a requirements then you can do following things.
store value in hidden field and check if there is any value in hidden field if yes then fill the ddl and set value else do nothing. below is full code.
Change script code

    $(document).ready(function () {

        //$("#assayreport").tableHeadFixer({ 'foot': true });
        "responsive"; true,
            "serverSide"; true,
                "info"; true,
                    "stateSave"; true,
                        $.ajax({
                            url: 'RhemaServices.asmx/GetJobs',
                            data: '{"jobnumber":"","clientID":"0","status":"2"}',
                            type: 'POST',
                            dataType: 'json',
                            contentType: "application/json; charset-utf-8",
                            success: function (data) {
                                jobdatavariable = data
                                $.each(data, function (i, item) {
                                    $('<option value="' + item.TotalInvoiceValue + '">' + item.JobNumber + '</option>').appendTo('#jobcard');
                                });
                            },
                            error: function (err) {
                                console.log(err)
                            },
                            complete: function () {
                            }

                        });
            if($('#jobnumber').val()!="")
             {
                $('#jobcard').val($('#jobnumber').val());
             }
    });

Create onchange function
 like this

function getJobNo()
{
   $('#jobnumber').val($('#jobcard').val());
}

Synthetically i may be wrong but this logic should work.


问:
Can AutoMapper Map Between a Value Type (Enum) and Reference Type? (string)
Weird problem - i'm trying to map between an enum and a string, using AutoMapper:

```<code>Mapper.CreateMap<MyEnum, string>()
   .ForMember(dest => dest, opt => opt.MapFrom(src => src.ToString()));
</code>```

Don't worry that im using .ToString(), in reality i'm using an extension method on the enum itself (.ToDescription()), but i've kept it simple for the sake of the question.

The above throws an object reference error, when im doing simply setting up the mapping.

Considering this works:

```<code>string enumString = MyEnum.MyEnumType.ToString();
</code>```

I can't see why my AutoMapper configuration does not.

Can AutoMapper handle this, am i doing something wrong, or is this a bug with AutoMapper?

Any ideas?

EDIT

I also tried using a custom resolver:

```<code>Mapper.CreateMap<MyEnum, string>()
                .ForMember(dest => dest, opt => opt.ResolveUsing<MyEnumResolver>());

public class MyEnumResolver: ValueResolver<MyEnum,string>
{
   protected override string ResolveCore(MyEnum source)
   {
      return source.ToString();
   }
}
</code>```

Same error on same line. :(

答:
For mapping between two types where you're taking control of the entire mapping, use ConvertUsing:

```<code>Mapper.CreateMap<MyEnum, string>().ConvertUsing(src => src.ToString());
</code>```

All the other methods assume you're mapping to individual members on the destination type.

Body:
Weird problem - i'm trying to map between an enum and a string, using AutoMapper:

Mapper.CreateMap<MyEnum, string>()
   .ForMember(dest => dest, opt => opt.MapFrom(src => src.ToString()));

Don't worry that im using .ToString(), in reality i'm using an extension method on the enum itself (.ToDescription()), but i've kept it simple for the sake of the question.

The above throws an object reference error, when im doing simply setting up the mapping.

Considering this works:

string enumString = MyEnum.MyEnumType.ToString();

I can't see why my AutoMapper configuration does not.

Can AutoMapper handle this, am i doing something wrong, or is this a bug with AutoMapper?

Any ideas?

EDIT

I also tried using a custom resolver:

Mapper.CreateMap<MyEnum, string>()
                .ForMember(dest => dest, opt => opt.ResolveUsing<MyEnumResolver>());

public class MyEnumResolver: ValueResolver<MyEnum,string>
{
   protected override string ResolveCore(MyEnum source)
   {
      return source.ToString();
   }
}

Same error on same line. :(

Body:
For mapping between two types where you're taking control of the entire mapping, use ConvertUsing:

Mapper.CreateMap<MyEnum, string>().ConvertUsing(src => src.ToString());

All the other methods assume you're mapping to individual members on the destination type.


问:
How to make sublime text 3 mark syntax of lex on windows
i am trying to mark lex syntax in sublime text 3

i downloaded from github package that marks the syntax of lex file and put it on

Sublime Text 3\Packages

and then i restart sublime text 3 and nothing has changed

```<code>%{

    #include <string.h>

%}
</code>```

This code is fully white also after installing the package from github(the color doesn't change)

the git i cloned is- https://github.com/textmate/lex-flex.tmbundle

答:
As suggested here, for lexer syntax texmate syntax files can be used with SublimeText.

To mark lex syntax in sublime text 3:

clone git repository into packages/User: https://github.com/textmate/lex-flex.tmbundle

open a lexer file

set lexer syntax in View -> Syntax -> User > Lex/Flex

Body:
i am trying to mark lex syntax in sublime text 3

i downloaded from github package that marks the syntax of lex file and put it on

Sublime Text 3\Packages

and then i restart sublime text 3 and nothing has changed

%{

    #include <string.h>

%}

This code is fully white also after installing the package from github(the color doesn't change)

the git i cloned is- https://github.com/textmate/lex-flex.tmbundle


问:
Reset progress bar after form submit using jQuery
I have a progress bar on a form which works fine but I need to reset its value after the file as been upload.

My code:

```<code><div class="bar-position">
  <div class="col-md-14 col-md-14 progress-container">
    <div class="progress progress-striped active">
      <div class="progress-bar progress-bar-success" style="width:0%"></div>
    </div>
  </div>
</div>
</code>```

I have tried using this after the file upload but it does not work:

```<code>$('.progress').val(0);
</code>```

Where am I going wrong? I have looked at a number of posts but I can't find a solution that will work with my code.

答:
You progress bar uses width property to show progress. To reset it use the following:

```<code>$('.progress-bar').css("width","0%");
</code>```

Body:
I have a progress bar on a form which works fine but I need to reset its value after the file as been upload.

My code:

I have tried using this after the file upload but it does not work:

$('.progress').val(0);

Where am I going wrong? I have looked at a number of posts but I can't find a solution that will work with my code.

Body:
You progress bar uses width property to show progress. To reset it use the following:

$('.progress-bar').css("width","0%");


问:
The difference between "majority" and "linearizable"
Read the docs a few times but still cannot understand the difference in the behavior of "majority" and "linearizable" read concerns:

"majority"

The query returns the instance’s most recent data acknowledged as having been written to a majority of members in the replica set.

"linearizable"

The query returns data that reflects all successful writes issued with a write concern of "majority" and acknowledged prior to the start of the read operation.

The docs also mention an option "writeConcernMajorityJournalDefault", it says that with that option set to false the data can be rolled back even when using "linearizable".

Could someone explain please, how both concerns work and how this option impacts them?

答:
In my understanding, Read Concern majority in an node will immediately return the read query with the most recent majority committed (written to the majority of the nodes) data that is available in that node.  On the other hand, Read Concern linearizable will wait till the completion concurrently executing writes to propagate to a majority of replica set members before returning results.

Both of them guaranty that the data read has been acknowledged by a majority of the replica set members, i.e. the documents read are durable and guaranteed not to roll back.

As Read Concern linearizable waits for the concurrently executing writes to be finished, it's performance is significantly slower than that of Read Concern majority.

Similarly, since Read Concern majority don't wait for the concurrently executing writes, it will return fast, but it may return stale data(still durable & w:majority acknowledged). See this example for details: https://docs.mongodb.com/manual/reference/read-concern-majority/#example

In that example between t3~t5 (after t3 and before t5) primary and secondaries will return different data with Read Concern majority.


问:
Converting TimeZone Date Object without Changing Time
I want to convert the date from one timeZone into another TimeZone

For Eg: "Sun May 01 2019 00:00:00 GMT+0530 (India Standard Time)" is the current date object , i want to convert the date based on timeZone Offset. consider the offset is '+4.0', Then i want the desired output such as "Sun May 01 2019 00:00:00 +04:00", i have used moment utcOffset
but it gives result such as "Sun May 19 2019 22:30:00 GMT+0530".

答:
You should take a look at this answer. The top answer provides a good way how to do it in vanilla javascript.

If you would like to use a library to achieve that, I would suggest to look into date-fns. It doesn't have the mutability issues that moment does. If you opt for using it, you should use it together with date-fns-timezone


问:
How can I wait on multiple results, then filter them based on received data?
I have two observables that I would like to wait for the results of both so I can filter the results of one based upon the other. Individually they wor:

```<code>this.allValues$ = this.store.select(selectors.getAllValues)
this.myId$ = this.store.select(selectors.myId)
</code>```

and I can render them to the template with the async pipe

However I would like to make a class property which holds a filtered array. If it were synchronous JS, something like

```<code>this.filteredResults = allValues.filter(value => value.id === myId)
</code>```

ziping will get me the values

```<code>this.filteredResults$ = zip(
  this.store.select(selectors.getAllValues),
  this.store.select(selectors.myId)
)
</code>```

template:
    results: {{ filteredResults$ | async | json }}

But I cannot understand how to filter like I want. I've tried chaining a pipe to the zip:

```<code>.pipe(
   tap((...args) => {
     console.log({ args }) // only one result so no hope of dropping in `map` or `filter` here
   })
)
</code>```

But this has the effect of removing the allValues array from the result set. allValues is vastly larger so presumably taking longer and zip is no longer waiting for everything to emit so I guess pipe isn't the solution, though it seems close.

How can I can I access both these result sets, filter them, and put that result in an observable I can render in the template with filteredResults$ | async | json?

答:
It's easy to overlook NgRx selectors. You should check out the documentation, because what you are trying to achieve is possible with the createSelector method. This will have multiple benefits (cleaner code, reusable selector, etc)

https://ngrx.io/guide/store/selectors#using-selectors-for-multiple-pieces-of-state

Something like this might work in your case:

```<code>export const yourCombinedSelector = createSelector(
  selectors.getAllValues,
  selectors.myId,
  (allValues, myId) => {
    // perform logic and return the data you need
  }
);
</code>```

Then

```<code>const data$ = this.store.select(selectors.yourCombinedSelector)
</code>```

Body:
I have two observables that I would like to wait for the results of both so I can filter the results of one based upon the other. Individually they wor:

this.allValues$ = this.store.select(selectors.getAllValues)
this.myId$ = this.store.select(selectors.myId)

and I can render them to the template with the async pipe

However I would like to make a class property which holds a filtered array. If it were synchronous JS, something like

this.filteredResults = allValues.filter(value => value.id === myId)

ziping will get me the values

this.filteredResults$ = zip(
  this.store.select(selectors.getAllValues),
  this.store.select(selectors.myId)
)

template:
    results: {{ filteredResults$ | async | json }}

But I cannot understand how to filter like I want. I've tried chaining a pipe to the zip:

.pipe(
   tap((...args) => {
     console.log({ args }) // only one result so no hope of dropping in `map` or `filter` here
   })
)

But this has the effect of removing the allValues array from the result set. allValues is vastly larger so presumably taking longer and zip is no longer waiting for everything to emit so I guess pipe isn't the solution, though it seems close.

How can I can I access both these result sets, filter them, and put that result in an observable I can render in the template with filteredResults$ | async | json?

Body:
It's easy to overlook NgRx selectors. You should check out the documentation, because what you are trying to achieve is possible with the createSelector method. This will have multiple benefits (cleaner code, reusable selector, etc)

https://ngrx.io/guide/store/selectors#using-selectors-for-multiple-pieces-of-state

Something like this might work in your case:

export const yourCombinedSelector = createSelector(
  selectors.getAllValues,
  selectors.myId,
  (allValues, myId) => {
    // perform logic and return the data you need
  }
);

Then

const data$ = this.store.select(selectors.yourCombinedSelector)


问:
Remove field from query mongoose
My User model have name,..., password, resetToken, resetTokenExp property.

If I query user (findById, find({}),...), I want to drop password, resetToken and resetTokenExp field

```<code>User.findById(id)
  .select('-password -resetToken -resetTokenExp')
  .exec()
</code>```

I can use select but these fields are common ones and I dont want to type select everytime I query. How can I set remove these fields globally for User schema

答:
You can make reusable functions something like this

so by default, these three fields will be excluded from the result

```<code>function fetchUser(id, exludeFields = { password: false, resetToken: false, resetTokenExp: false }) {
    return User.findById(id)
        .select(exludeFields)
        .exec();
}
</code>```

Title: Remove field from query mongoose

Body:
My User model have name,..., password, resetToken, resetTokenExp property.

If I query user (findById, find({}),...), I want to drop password, resetToken and resetTokenExp field

User.findById(id)
  .select('-password -resetToken -resetTokenExp')
  .exec()

I can use select but these fields are common ones and I dont want to type select everytime I query. How can I set remove these fields globally for User schema

Body:
You can make reusable functions something like this

so by default, these three fields will be excluded from the result

function fetchUser(id, exludeFields = { password: false, resetToken: false, resetTokenExp: false }) {
    return User.findById(id)
        .select(exludeFields)
        .exec();
}


问:
Click on “R more” button on mouthshut.com reviews using python
I'm trying to scroll through http://www.mouthshut.com/mobile-operators/Reliance-Jio-reviews-925812061 page. I need to click on the "Read MORE" button in review section, but I can't find it with using beautiful soup in python..</p>

答:
Tried to run the code suggested by G_M but got an error. But solved it using the following steps:

Platform: Using Windows 10, Anaconda-Jupyter Notebook, Chrome browser.

Step 1: installed selenium using the following command in Jupyter notebook:

!pip install selenium

Step 2: executed the code by G_M above: it showed me the following error:

WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see sites.google.com/a/chromium.org/chromedriver/home.

Downloaded chromedriver from the link provided in the error message: from the mentioned link downloaded the latest version of chromedriver. It's a zip file. unzip the file you will get an .exe file,  upload it to the same location/folder where the Jupyter notebook is running.

Restart the notebook. And execute the code again. It's working fine now.

I am using this code to expand the comments by clicking 'Read More' link in the review web page for a product. The code it's working fine except for the 1st comment it was not expanded completely. I don't know why but the code is working fine on other comments.


问:
Objective-C retain question
In Xcode I have a UINavigationController on wichh I push a UIViewController.

In that UIViewController I init an UIScrollView.

All good.

However, after switching to another view I log the retain count of the controller and to my surprise it's one instead of zero.

Here's the code:

```<code>scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

[self.view addSubview:scroller];
</code>```

and:

```<code>- (void)dealloc {
    [super dealloc];

    NSLog(@"retaincount, %d", [scroller retainCount]);  //displays 2

    [scroller release];

    NSLog(@"retaincount, %d", [scroller retainCount]); // displays 1
}
</code>```

I only init it ones and add it to the UIViewControllers view.

Kind regards,

Tom

答:
self.view is retaining it. When your UIViewController deallocs, it'll release self.view, which will release all its retained subviews. In fact, you should probably release it soon after adding it to self.view.

That said, I strongly second @fluchtpunkt's answer. Examining the retainCount property looking for debugging info will only lead to confusion and increasingly coherent and ranty posts on Stack Overflow.

Title: Objective-C retain question

Body:
In Xcode I have a UINavigationController on wichh I push a UIViewController.

In that UIViewController I init an UIScrollView.

All good.

However, after switching to another view I log the retain count of the controller and to my surprise it's one instead of zero.

Here's the code:

scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

[self.view addSubview:scroller];

and:

- (void)dealloc {
    [super dealloc];

    NSLog(@"retaincount, %d", [scroller retainCount]);  //displays 2

    [scroller release];

    NSLog(@"retaincount, %d", [scroller retainCount]); // displays 1
}

I only init it ones and add it to the UIViewControllers view.

Kind regards,

Tom


问:
Pixi.js makes browser crashed when use PIXI ticker
My problem is chrome browser stopped after about 2 minutes later ticker started.

const renderer = new PIXI.Renderer({
    width: window.innerWidth,
    height: window.innerHeight,
    backgroundColor: 0x2c3e50,
    antialias: true,
});

const stage = new PIXI.Container();
const ticker = new PIXI.Ticker();

const initialLine = new PIXI.Graphics();
const dx = 0.2;

const xData = [50, 100, 150, 200];
const yData = [20, 90, 40, 100];

let lastX = xData[xData.length - 1];
let lastY = yData[yData.length - 1];

document.body.appendChild(renderer.view);

const simpleLine = () => {
    initialLine.lineStyle(2, 0xFFFFFF, 1);
    initialLine.moveTo(0, 0);
    for (let i = 0; i < xData.length; i++) {
        initialLine.lineTo(xData[i], yData[i]);
    }

    initialLine.position.x = 150;
    initialLine.position.y = 50;

    stage.addChild(initialLine);
}

const addLine = () => {
    const lastIndex = xData.length - 1;
    const newX = xData[lastIndex];
    const newY = yData[lastIndex];

    initialLine.moveTo(lastX, lastY);
    initialLine.lineTo(newX, newY);
}

const moveLine = () => {
    initialLine.position.x -= dx;
}

const setTicker = () => {
    ticker.add(() => {
        moveLine();
        addLine();
        renderer.render(stage);
    }, PIXI.UPDATE_PRIORITY.LOW);
    ticker.start();
}

const changeData = () => {
    lastX = xData[xData.length - 1];
    lastY = yData[yData.length - 1];
    xData.push(lastX + 10);
    yData.push(Math.floor(Math.random() * 100));
}

setInterval(() => {
    changeData();
}, 1000);

simpleLine();
setTicker();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; }</code>```

```

It's a simple code for a line chart.

Add a basic PIXI container

Draw the first line with 4 dots.

Add next line every second using PIXI ticker and Change line x position.

It works nicely at the moment But about 2 minutes later, the browser is crashed.

I don't know why and how can I fix it.
Help me!

答:
There is an out-of-memory error. Potentially a memory leak. If run with the dev tools open, it says "Paused before potential out-of-memory-crash".

The memory usage quickly surpasses 1500 MB. But if these lines are commented out, the memory usage seems to remain stable:

```<code>// xData.push(lastX + 10);
// yData.push(Math.floor(Math.random() * 100));
</code>```

However, when the out-of-memory error occurs, xData.length is about 90. These arrays cannot be taking up the 1500+ MB.

I am not sure how PIXI stores graphics objects, but I think initialLine is consuming most of the memory. That initialLine is being moved to the left, and there is a large, growing portion that cannot be seen. An out-of-memory error is inevitable! Ideally, the parts of initialLine that are not visible should be freed.

The PIXI.graphics API doesn't seem to have a way to free old line segments. Instead of continuously moving and adding more line segments, I would clear the previous graphics and redraw the entire line (skipping parts of the line that are not visible).

Body:
My problem is chrome browser stopped after about 2 minutes later ticker started.

const renderer = new PIXI.Renderer({
    width: window.innerWidth,
    height: window.innerHeight,
    backgroundColor: 0x2c3e50,
    antialias: true,
});

const stage = new PIXI.Container();
const ticker = new PIXI.Ticker();

const initialLine = new PIXI.Graphics();
const dx = 0.2;

const xData = [50, 100, 150, 200];
const yData = [20, 90, 40, 100];

let lastX = xData[xData.length - 1];
let lastY = yData[yData.length - 1];

document.body.appendChild(renderer.view);

const simpleLine = () => {
    initialLine.lineStyle(2, 0xFFFFFF, 1);
    initialLine.moveTo(0, 0);
    for (let i = 0; i < xData.length; i++) {
        initialLine.lineTo(xData[i], yData[i]);
    }

    initialLine.position.x = 150;
    initialLine.position.y = 50;

    stage.addChild(initialLine);
}

const addLine = () => {
    const lastIndex = xData.length - 1;
    const newX = xData[lastIndex];
    const newY = yData[lastIndex];

    initialLine.moveTo(lastX, lastY);
    initialLine.lineTo(newX, newY);
}

const moveLine = () => {
    initialLine.position.x -= dx;
}

const setTicker = () => {
    ticker.add(() => {
        moveLine();
        addLine();
        renderer.render(stage);
    }, PIXI.UPDATE_PRIORITY.LOW);
    ticker.start();
}

const changeData = () => {
    lastX = xData[xData.length - 1];
    lastY = yData[yData.length - 1];
    xData.push(lastX + 10);
    yData.push(Math.floor(Math.random() * 100));
}

setInterval(() => {
    changeData();
}, 1000);

simpleLine();
setTicker();

body { margin: 0; }

It's a simple code for a line chart.

Add a basic PIXI container

Draw the first line with 4 dots.

Add next line every second using PIXI ticker and Change line x position.

It works nicely at the moment But about 2 minutes later, the browser is crashed.

I don't know why and how can I fix it.
Help me!

Body:
There is an out-of-memory error. Potentially a memory leak. If run with the dev tools open, it says "Paused before potential out-of-memory-crash".

The memory usage quickly surpasses 1500 MB. But if these lines are commented out, the memory usage seems to remain stable:

// xData.push(lastX + 10);
// yData.push(Math.floor(Math.random() * 100));

However, when the out-of-memory error occurs, xData.length is about 90. These arrays cannot be taking up the 1500+ MB.

I am not sure how PIXI stores graphics objects, but I think initialLine is consuming most of the memory. That initialLine is being moved to the left, and there is a large, growing portion that cannot be seen. An out-of-memory error is inevitable! Ideally, the parts of initialLine that are not visible should be freed.

The PIXI.graphics API doesn't seem to have a way to free old line segments. Instead of continuously moving and adding more line segments, I would clear the previous graphics and redraw the entire line (skipping parts of the line that are not visible).


问:
android.permission.ANSWER_PHONE_CALLS How I can use? for auto answer
As per android developer documentation

Android 8.0 (API level 26) introduces several new permissions related
  to telephony: The ANSWER_PHONE_CALLS permission allows your app to
  answer incoming phone calls programmatically. To handle an incoming
  phone call in your app, you can use the acceptRingingCall() method.

How my app give voice answer to  incoming call ?

but I have not found any guide or  examples about of this .
so

I want automatic answer with voice(from raw folder in app)
(I have need guide or example code like answering machine)

答:
https://developer.android.com/reference/android/telecom/TelecomManager.html#acceptRingingCall()

Acccept Answer call is deprecated API LEVEL Q

```<code>try {
                    Toast.makeText(CallAnswerDialog.this, "btn_answer click", Toast.LENGTH_SHORT).show();

                    TelecomManager tm = (TelecomManager) CallAnswerDialog.this.getSystemService(Context.TELECOM_SERVICE);
                    if (tm == null) {
                        // whether you want to handle this is up to you really
                        throw new NullPointerException("tm == null");
                    }
                    tm.acceptRingingCall();   // is deprecated Now API Level Q
                    btn_answer.setVisibility(View.GONE);
                }catch (Exception e){
                    e.printStackTrace(); }
</code>```

Body:
https://developer.android.com/reference/android/telecom/TelecomManager.html#acceptRingingCall()

Acccept Answer call is deprecated API LEVEL Q

try {
                    Toast.makeText(CallAnswerDialog.this, "btn_answer click", Toast.LENGTH_SHORT).show();

                    TelecomManager tm = (TelecomManager) CallAnswerDialog.this.getSystemService(Context.TELECOM_SERVICE);
                    if (tm == null) {
                        // whether you want to handle this is up to you really
                        throw new NullPointerException("tm == null");
                    }
                    tm.acceptRingingCall();   // is deprecated Now API Level Q
                    btn_answer.setVisibility(View.GONE);
                }catch (Exception e){
                    e.printStackTrace(); }


问:
How to initialize dynamic array in constructor using initializer_ist?
I am trying to initialize the dynamic array in the constructor using initialize_list in C++. How can I achieve this?

```<code>#include <cstdlib>
#include <initializer_list>
#include <iostream>
#include <utility>

using namespace std;

class vec {
private:
    // Variable to store the number of elements contained in this vec.
    size_t elements;
    // Pointer to store the address of the dynamically allocated memory.
    double *data;

public:
    /*
      * Constructor to create a vec variable with the contents of 'ilist'.
    */
    vec(initializer_list<double> ilist);
}

int main() {
    vec x = { 1, 2, 3 };  // should call to the constructor
    return 0;
}
</code>```

答:
initializer_list has size method, it gives you information how many elements must be allocated by new, so it could be:

```<code>vec(initializer_list<double> ilist)
{
    elements = ilist.size();
    data = new double[ ilist.size() ];
    std::copy(ilist.begin(),ilist.end(),data);
}
</code>```

Body:
I am trying to initialize the dynamic array in the constructor using initialize_list in C++. How can I achieve this?

#include <cstdlib>
#include <initializer_list>
#include <iostream>
#include <utility>

using namespace std;

class vec {
private:
    // Variable to store the number of elements contained in this vec.
    size_t elements;
    // Pointer to store the address of the dynamically allocated memory.
    double *data;

public:
    /*
      * Constructor to create a vec variable with the contents of 'ilist'.
    */
    vec(initializer_list<double> ilist);
}

int main() {
    vec x = { 1, 2, 3 };  // should call to the constructor
    return 0;
}

Body:
initializer_list has size method, it gives you information how many elements must be allocated by new, so it could be:

vec(initializer_list<double> ilist)
{
    elements = ilist.size();
    data = new double[ ilist.size() ];
    std::copy(ilist.begin(),ilist.end(),data);
}


问:
create space between bootstrap navbar and jumbotron
If i look at the following bootstrap example:
http://getbootstrap.com/examples/navbar/

then there is some space between the jumbotron and the navbar.

I digged into the css of the example and if i disable this (2 times):

```<code>.navbar {
    margin-bottom: 20px;
}
</code>```

Then the space in between disappears.
When i try to do this myself the margin-bottom has no effect.
Why is that? And how do i fix it?
(I did a search but I only find people wanting to remove the gap that I don't have...).

```<code><div class="container">

    <div class="navbar navbar-default navbar-fixed-top" role="navigation">

        <div class="container-fluid">

            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">FOOBAR</a>
            </div>

        </div> <!-- /.container-fluid -->

    </div>

    <div class="jumbotron">
        <h1>Test</h1>
    </div>

</div>
</code>```

http://jsfiddle.net/6Qp9v/

答:
Just add some padding top for the body.

```<code>body{
        padding-top: 70px;
    }
</code>```

Hope this answer solved your problem.

Body:
If i look at the following bootstrap example:
http://getbootstrap.com/examples/navbar/

then there is some space between the jumbotron and the navbar.

I digged into the css of the example and if i disable this (2 times):

.navbar {
    margin-bottom: 20px;
}

Then the space in between disappears.
When i try to do this myself the margin-bottom has no effect.
Why is that? And how do i fix it?
(I did a search but I only find people wanting to remove the gap that I don't have...).

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                </button>
                FOOBAR

Test

http://jsfiddle.net/6Qp9v/

Body:
Just add some padding top for the body.

body{
        padding-top: 70px;
    }

Hope this answer solved your problem.


问:
IDE: ProjectManager expands allways its items
Delphi 2007:
I have a projectgroup with a couple of projects (bpl/dll/exe). Whenever I start the Delphi IDE some of the project entries are expanded and some are not. I would like to see all of them compressed after the start but I cannot see a way to do that.

Any hints?

Chris

答: When you load the IDE (or a Project/ProjectGroup) does it automatically reopen whatever units you had opened in the editor the last time you closed it? If so, then I believe that the Project Explorer will always auto-expand the tree to show all active units' represenative nodes in the tree.</p>

ContentLicense: CC BY-SA 2.5


问:
Change background color of buttons onclick
I have two buttons called YES and NO whose color(i,e background-color) is light like this:

When the user click YES

YES button background color should change to green (i,e success) and NO should be in light color like this:

When the user click No

NO button background color should change to red (i,e danger) and Yes should be in light color like this:

DEMO

while surfing i saw this question. Here they are changing only one button color on click. But for my requirement both the button color should change on click.

CODE

HTML

```<code><ion-content padding>
  <ion-item lines="none">
  <ion-button class="btn-1" expand="full" color="light" >Yes</ion-button>
   <ion-button class="btn-2" expand="full"  color="light" >No</ion-button>
  </ion-item>
</ion-content>
</code>```

CSS

```<code>.btn-1{
width:45%;
float:left;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}
.btn-2{
width:45%;
float:right;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}
</code>```

TS

```<code> import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.css'],
})
export class HomePage {

}
</code>```

答:
3 values means you can't use a boolean. But you can use a number :

buttonValue = 0;
```

<pre class="lang-html prettyprint-override"><code><ion-button class="btn-1" expand="full" [color]="buttonValue > 0 ? 'success' : 'light'" (click)="buttonValue = 1">Yes</ion-button>
<ion-button class="btn-2" expand="full" [color]="buttonValue < 0 ? 'danger' : 'light'" (click)="buttonValue = -1">No</ion-button>
</code>```

Body:
I have two buttons called YES and NO whose color(i,e background-color) is light like this:

When the user click YES

YES button background color should change to green (i,e success) and NO should be in light color like this:

When the user click No

NO button background color should change to red (i,e danger) and Yes should be in light color like this:

DEMO

while surfing i saw this question. Here they are changing only one button color on click. But for my requirement both the button color should change on click.

CODE

HTML

<ion-content padding>
  <ion-item lines="none">
  <ion-button class="btn-1" expand="full" color="light" >Yes</ion-button>
   <ion-button class="btn-2" expand="full"  color="light" >No</ion-button>
  </ion-item>
</ion-content>

CSS

.btn-1{
width:45%;
float:left;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}
.btn-2{
width:45%;
float:right;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}

TS

 import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.css'],
})
export class HomePage {

}

Body:
3 values means you can't use a boolean. But you can use a number :

buttonValue = 0;

<ion-button class="btn-1" expand="full" [color]="buttonValue > 0 ? 'success' : 'light'" (click)="buttonValue = 1">Yes</ion-button>
<ion-button class="btn-2" expand="full" [color]="buttonValue < 0 ? 'danger' : 'light'" (click)="buttonValue = -1">No</ion-button>


问:
How to comparate MULTILINESTRING geometry type with POINT geometry type in VB.NET?
I want to comparate MULTILINESTRING geometry type with POINT geometry type.
In order to test if an (XY) from MULTILINESTRING match with an (XY) from POINT.
Basically MULTILINESTRING type look like something like that : MULTILINESTRING((918844.55 6670885.31,918778.87 6670898.9, 918502.96 6670936.35)), the number of (XY) coordinates can be more than 3.
And POINT type look like this : POINT(920892.39 6671627.92), but the number of (XY) coordinates  is the same.

I get this data from postgreSQl database and I don't any problem to retrieve them nor to parse each geometry type but it's to comparate them.

The difficulty I encounter is when I get MULTILINESTRING geometry type I retrieve a dataset where each lines are like the example above. So I need to comparate each (XY) coordinate of MULTILINESTRING geometry type to each (XY) POINT geometry type. If the value match I want to INSERTthe (XY) coordinates to a table.

Below my code and explanations :

Sub importcb_smn(ByVal myConnection As System.Data.Odbc.OdbcConnection)

        Dim infoDataset As DataSet, infoDataset2 As DataSet
'Here I get MULTILINESTRING type
        infoDataset = accessRequet_odbc("select st_astext(st_snaptogrid(geom, 0.01)) from netgeo_cable", myConnection)
'Here I get POINT type
        infoDataset2 = accessRequet_odbc("select st_astext(st_snaptogrid(geom, 0.01)) from netgeo_point_tech", myConnection)

        Dim t1 As Long = infoDataset2.Tables(0).Rows.Count
        Dim t2 As Long
        Dim geomCable As String, geomPt(t1) As String, geomSplit(t2) As String
        Dim parse1 As String, parse2 As String, parse3 As String
'Here I parse POINT type data to dump it into an array
        For i = 0 To infoDataset2.Tables(0).Rows.Count - 1
            parse1 = infoDataset2.Tables(0).Rows(i).ItemArray(0).Remove(0, 6)
            geomPt(i) = parse1.Substring(0, parse1.Length - 1)
        Next
'Here I parse MULTILINESTRING type
        For i = 0 To infoDataset.Tables(0).Rows.Count - 1
            parse2 = infoDataset.Tables(0).Rows(i).ItemArray(0).Remove(0, 17)
            geomCable = parse2.Substring(0, parse2.Length - 2)
            geomSplit = Split(geomCable, ",")
'I test if value matches
            For j = 0 To UBound(geomPt)
                If geomPt(j) = geomSplit(i) Then
                    Call executeCommand("insert into netgeo_cable_bis(geom) values (st_geometryfromtext('POINT(" & geomSplit(i) & ")',2154))", myConnection)
                End If
            Next
        Next
    End Sub
```

So I try to comparate 2 array. First I parse and dump each line of infoDataset2 into geomPt(). So each line of geomPt() is (XY) string.

Then I parse and dump one line of infoDataset into geomSplit(). But here each line of geomSplit() is just (XY) coordinates of 1 line of infoDaset.

That's why I try to comparate whithin the same loop. To test every (XY) coordinates of every lines of infoDataset with each lines of infoDataset2.

I get an error at if geomPt(j) = geomSplit(i) then saying : System.IndexOutOfRangeException : The index is outside the limits of the table. But I don't see how to fix it.

I want to learn from this, so, if possible, explain to me what I'm doing wrong here, or if my approach is lacking insight.

答:
Thanks to @JGH who suggested me to try whith a Postgis function to do the comparison. Indeed it is better to let the database do that work because it is made for that.

So first I do a SELECT query to get all the points of my cables (with st_dumppoints() that are near a point of comparison (st_dwithin()). Then I get index position of each point on the cable to build a new linestring (with st_line_locate_point()).

In VB.NET my query look like this : infoDataset = accessRequet_odbc("SELECT req.id, (dp).geom, netgeo_point_tech.id, ST_Line_Locate_Point(ST_LineMerge(geom_cable), (dp).geom)
FROM (SELECT id, ST_DumpPoints(geom) as dp, geom as geom_cable FROM netgeo_cable_test) as req
LEFT JOIN netgeo_point_tech ON ST_dwithin(netgeo_point_tech.geom, (dp).geom, 1)
ORDER BY req.id, (dp).path [ 1] ASC", myConnection)

Then I need to parse the result I get to extract index position and origin cable id.
With the id of original cable and the float (index position) I can insert a new linsestring which is a part of the original cable.

Let me know guys if my explanations make sense.

Body:
I want to comparate MULTILINESTRING geometry type with POINT geometry type.
In order to test if an (XY) from MULTILINESTRING match with an (XY) from POINT.
Basically MULTILINESTRING type look like something like that : MULTILINESTRING((918844.55 6670885.31,918778.87 6670898.9, 918502.96 6670936.35)), the number of (XY) coordinates can be more than 3.
And POINT type look like this : POINT(920892.39 6671627.92), but the number of (XY) coordinates  is the same.

I get this data from postgreSQl database and I don't any problem to retrieve them nor to parse each geometry type but it's to comparate them.

The difficulty I encounter is when I get MULTILINESTRING geometry type I retrieve a dataset where each lines are like the example above. So I need to comparate each (XY) coordinate of MULTILINESTRING geometry type to each (XY) POINT geometry type. If the value match I want to INSERTthe (XY) coordinates to a table.

Below my code and explanations :

Sub importcb_smn(ByVal myConnection As System.Data.Odbc.OdbcConnection)

        Dim infoDataset As DataSet, infoDataset2 As DataSet
'Here I get MULTILINESTRING type
        infoDataset = accessRequet_odbc("select st_astext(st_snaptogrid(geom, 0.01)) from netgeo_cable", myConnection)
'Here I get POINT type
        infoDataset2 = accessRequet_odbc("select st_astext(st_snaptogrid(geom, 0.01)) from netgeo_point_tech", myConnection)

        Dim t1 As Long = infoDataset2.Tables(0).Rows.Count
        Dim t2 As Long
        Dim geomCable As String, geomPt(t1) As String, geomSplit(t2) As String
        Dim parse1 As String, parse2 As String, parse3 As String
'Here I parse POINT type data to dump it into an array
        For i = 0 To infoDataset2.Tables(0).Rows.Count - 1
            parse1 = infoDataset2.Tables(0).Rows(i).ItemArray(0).Remove(0, 6)
            geomPt(i) = parse1.Substring(0, parse1.Length - 1)
        Next
'Here I parse MULTILINESTRING type
        For i = 0 To infoDataset.Tables(0).Rows.Count - 1
            parse2 = infoDataset.Tables(0).Rows(i).ItemArray(0).Remove(0, 17)
            geomCable = parse2.Substring(0, parse2.Length - 2)
            geomSplit = Split(geomCable, ",")
'I test if value matches
            For j = 0 To UBound(geomPt)
                If geomPt(j) = geomSplit(i) Then
                    Call executeCommand("insert into netgeo_cable_bis(geom) values (st_geometryfromtext('POINT(" & geomSplit(i) & ")',2154))", myConnection)
                End If
            Next
        Next
    End Sub

So I try to comparate 2 array. First I parse and dump each line of infoDataset2 into geomPt(). So each line of geomPt() is (XY) string.

Then I parse and dump one line of infoDataset into geomSplit(). But here each line of geomSplit() is just (XY) coordinates of 1 line of infoDaset.

That's why I try to comparate whithin the same loop. To test every (XY) coordinates of every lines of infoDataset with each lines of infoDataset2.

I get an error at if geomPt(j) = geomSplit(i) then saying : System.IndexOutOfRangeException : The index is outside the limits of the table. But I don't see how to fix it.

I want to learn from this, so, if possible, explain to me what I'm doing wrong here, or if my approach is lacking insight.


问:
why the class attr can not be used in this way?
Why the class attr cannot be used in this way?

class A:
    a = 1
    d = [1, 2, 3, 4]
    e = [i for i in d if i == a]
    print(e)
```

<p>and the error message is like this below:</p>

```Traceback (most recent call last):
  File "/home/gavinc/code/eigen_clients/gavinc/a002.py", line 3, in <module>
    class A:
  File "/home/gavinc/code/eigen_clients/gavinc/a002.py", line 7, in A
    e = [i for i in d if i == a]
  File "/home/gavinc/code/eigen_clients/gavinc/a002.py", line 7, in <listcomp>
    e = [i for i in d if i == a]
NameError: name 'a' is not defined
```

<p>there will be no error if I write this out side of a class, something like the following code:</p>

<pre class="lang-py prettyprint-override"><code>a1 = 1
d1 = [1, 2, 3, 4]
e1 = [i for i in d1 if i == a1]
print(e1)
</code>```

答:
When it comes to classes, instance variables are defined inside an init method as below:

```<code>class A:
    def __init__(self):
        self.a = 1
        self.d = [1, 2, 3, 4]
        self.e = [i for i in self.d if i == self.a]
        print(self.e)

# Creating an object of the class in order to trigger __init__
A()
</code>```

If you define variables directly inside the class, they'd be class variables. These can either be accessed through class instances (like instance variables usually are), or directly from the class name (like A.a, in your case).

Based on my tests, your code may be failing because the scope of the list comprehension does not contain a. I am not sure if this is because the class A still being constructed and hence lacks a proper scope to pass. I say this because replacing the comprehension with a for loop is yielding your expected results:

```<code>class A:
    a = 1
    d = [1, 2, 3, 4]
    e = []
    for i in d:
        if i == a:
            e.append(i)
    print(e)
    # [1]
</code>```

Body:
Why the class attr cannot be used in this way?

class A:
    a = 1
    d = [1, 2, 3, 4]
    e = [i for i in d if i == a]
    print(e)

and the error message is like this below:

Traceback (most recent call last):
  File "/home/gavinc/code/eigen_clients/gavinc/a002.py", line 3, in <module>
    class A:
  File "/home/gavinc/code/eigen_clients/gavinc/a002.py", line 7, in A
    e = [i for i in d if i == a]
  File "/home/gavinc/code/eigen_clients/gavinc/a002.py", line 7, in <listcomp>
    e = [i for i in d if i == a]
NameError: name 'a' is not defined

there will be no error if I write this out side of a class, something like the following code:

a1 = 1
d1 = [1, 2, 3, 4]
e1 = [i for i in d1 if i == a1]
print(e1)

Body:
When it comes to classes, instance variables are defined inside an init method as below:

class A:
    def __init__(self):
        self.a = 1
        self.d = [1, 2, 3, 4]
        self.e = [i for i in self.d if i == self.a]
        print(self.e)

# Creating an object of the class in order to trigger __init__
A()

If you define variables directly inside the class, they'd be class variables. These can either be accessed through class instances (like instance variables usually are), or directly from the class name (like A.a, in your case).

Based on my tests, your code may be failing because the scope of the list comprehension does not contain a. I am not sure if this is because the class A still being constructed and hence lacks a proper scope to pass. I say this because replacing the comprehension with a for loop is yielding your expected results:

class A:
    a = 1
    d = [1, 2, 3, 4]
    e = []
    for i in d:
        if i == a:
            e.append(i)
    print(e)
    # [1]


问:
Freemarker - default value for variable that may be missing or blank?
In Freemarker, I want to treat something that may be missing (not defined on given object or in given Map), have a null value, be an empty string "" or a string with whitespace only (" \t\n"), AKA blank string. Or a real value like "foo".

In case it's anything besides a non-blank string, I want the expression to return a default value.

How can I handle this in Freemarker?

So far, this is what I use:

```<code>${ obj.propery???then(obj.property?trim!"default") }
</code>```

But I can imagine something more ellegant, like

```<code>${ obj.property!!?trim!"default" }
</code>```

and even with trimming (which is quite common operation for templates):

```<code>${ obj.property!!!"default" }
</code>```

Is there something such in Freemarker? (Besides coding my own method or macro.)

答:
I had the same challenge and came to this solution:

```<code>${ (obj.property!"")?trim }
</code>```

It also trims the empty string but is easier to read than writing an function or a if.

Body:
In Freemarker, I want to treat something that may be missing (not defined on given object or in given Map), have a null value, be an empty string "" or a string with whitespace only (" \t\n"), AKA blank string. Or a real value like "foo".

In case it's anything besides a non-blank string, I want the expression to return a default value.

How can I handle this in Freemarker?

So far, this is what I use:

${ obj.propery???then(obj.property?trim!"default") }

But I can imagine something more ellegant, like

${ obj.property!!?trim!"default" }

and even with trimming (which is quite common operation for templates):

${ obj.property!!!"default" }

Is there something such in Freemarker? (Besides coding my own method or macro.)

Body:
I had the same challenge and came to this solution:

${ (obj.property!"")?trim }

It also trims the empty string but is easier to read than writing an function or a if.


问:
Remove URL structure for custom post type
I would like to know if its possible to remove URL structure for a custom post type. For example, I have 2 custom post types: portfolio and slider.

I want to keep URL structure for portfolio post type like this: mysite.com/portfolio/item-1 etc.

But I dont want URL structure for slider posts, since the slider will only be shown on the home page and I dont want visitors to be able to access it by going to mysite.com/slider/slide-1 for example. Is it possible?

Thanks in advance :)

Wordpress forums post: http://wordpress.org/support/topic/no-url-structure-for-custom-post-type-1?replies=1

答:
I had similar problem, in my case I had custom post type like this:

```<code>mypage.com/type
</code>```

and inside I've got a lot of posts, so of course this generated for me pages looks like:

```<code>mypage.com/type/page1
mypage.com/type/page2
...
</code>```

BUT, I knew that in the future I'll make websites there, so simple I made a redirection inside this custom post type webpages. So inside single-type.php I added:

```<code><script>
    window.location.href='www.mypage.com/404';
</script>
</code>```

So this simply redirect people to 404 page. Few weeks later, when I wanted to turn on these pages, I just deleted this code.

This is just a temporary workaround, but I hope it could help someone.

Body:
I had similar problem, in my case I had custom post type like this:

mypage.com/type

and inside I've got a lot of posts, so of course this generated for me pages looks like:

mypage.com/type/page1
mypage.com/type/page2
...

BUT, I knew that in the future I'll make websites there, so simple I made a redirection inside this custom post type webpages. So inside single-type.php I added:

<script>
    window.location.href='www.mypage.com/404';
</script>

So this simply redirect people to 404 page. Few weeks later, when I wanted to turn on these pages, I just deleted this code.

This is just a temporary workaround, but I hope it could help someone.


问:
Need to get user lists along Average in django while data in separate table
I am trying to get user list along with average login time

Model 1:

```<code>class User(models.Model):
    name = models.CharField(max_length=200)
    age = models.CharField(max_length=200)
    email = models.CharField(max_length=200)
</code>```

Model 2:

```<code>class History(models.Model):
    login_time = models.DateTimeField()
    logout_time = models.DateTimeField()
    user = models.ForeignKeyField(User, related_name="user_relation")
</code>```

I need records in list of below format avg_logged_in_time will average of be (logout_time - login-time)

```<code>Name, email, avg_logged_in_time
</code>```

答:
I think your queryset would look something like this. You can check the docs for more info. Also, you can check here for info about the F Query Expressions.

User.objects.values(
    'name', 'email', 'avg_logged_in_time'
).aggregate(
    avg_logged_in_time=Avg(
        F('history__logout_time') - F('history__login_time'), output_field=models.DateTimeField()
    )
)
```

Body:
I am trying to get user list along with average login time

Model 1:

class User(models.Model):
    name = models.CharField(max_length=200)
    age = models.CharField(max_length=200)
    email = models.CharField(max_length=200)

Model 2:

class History(models.Model):
    login_time = models.DateTimeField()
    logout_time = models.DateTimeField()
    user = models.ForeignKeyField(User, related_name="user_relation")

I need records in list of below format avg_logged_in_time will average of be (logout_time - login-time)

Name, email, avg_logged_in_time


问:
How do I create a new table taking columns from information_schema.columns with scale and precision?
I'm trying to create a table from information_schema.columns. I need precision and scale so that it helps me with decimal datatype. The problem I face here is for INT I get precision and scale, which cannot be inserted. Can someone help me with selecting the columns?
Eg:
I need select statement which gives such a output
I'm selecting from table A, it has 3 columns

```<code>name varchar(10),
price decimal(5,2),
Id int,
</code>```

What I get from the query I framed

```<code>name varchar(10),
price decimal(5,2),
Id int(10,0)
</code>```

current query:

```<code>SELECT COLUMN_NAME +' ' + DATA_TYPE + ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','') + ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')+ISNULL(','+CAST(NUMERIC_SCALE)AS VARCHAR)+')','')+',' FROM INFORMATION_SCHEMA.COLUMNS
</code>```

答:
try this if it works</p>

```<code>create table Tbl
(
    name varchar(10),
    price decimal(5,2),
    Id int
)

select
concat(
    name,' ',
    case system_type_id
        when 167 then 'varchar('+cast(max_length as varchar(10))+'), '
        when 106 then 'decimal('+cast(precision as varchar(10))+','+cast(scale as varchar(10))+'), '
        when 56 then 'int, '
        --add more case for more datatype
    else '' end
    )
From sys.columns
where object_id=(select object_id from sys.tables where name='tbl')
</code>```

Body:
I'm trying to create a table from information_schema.columns. I need precision and scale so that it helps me with decimal datatype. The problem I face here is for INT I get precision and scale, which cannot be inserted. Can someone help me with selecting the columns?
Eg:
I need select statement which gives such a output
I'm selecting from table A, it has 3 columns

name varchar(10),
price decimal(5,2),
Id int,

What I get from the query I framed

name varchar(10),
price decimal(5,2),
Id int(10,0)

current query:

SELECT COLUMN_NAME +' ' + DATA_TYPE + ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','') + ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')+ISNULL(','+CAST(NUMERIC_SCALE)AS VARCHAR)+')','')+',' FROM INFORMATION_SCHEMA.COLUMNS

Body:
try this if it works

create table Tbl
(
    name varchar(10),
    price decimal(5,2),
    Id int
)

select
concat(
    name,' ',
    case system_type_id
        when 167 then 'varchar('+cast(max_length as varchar(10))+'), '
        when 106 then 'decimal('+cast(precision as varchar(10))+','+cast(scale as varchar(10))+'), '
        when 56 then 'int, '
        --add more case for more datatype
    else '' end
    )
From sys.columns
where object_id=(select object_id from sys.tables where name='tbl')


问:
mysql password not working

Possible Duplicate:

  How to reset mysql root password ?

I executed the query

```<code>UPDATE mysql.users set password= PASSWORD('123456') WHERE users='root' and host='localhost';
flush priviledges;
</code>```

and after this mysql is not running. phpmyadmin and mysql console both are not working

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

答: You can reset the root password for MySQL.</p>

Title: mysql password not working

Body:
Possible Duplicate:

  How to reset mysql root password ?

I executed the query

UPDATE mysql.users set password= PASSWORD('123456') WHERE users='root' and host='localhost';
flush priviledges;

and after this mysql is not running. phpmyadmin and mysql console both are not working

#1045 - Access denied for user 'root'@'localhost' (using password: YES)


问:
Entering different cities with their population and then printing the max, min population with their respective cities
I have to input several cities and their population and have to print the max and minimum population with the name of the city.

I've figured out how to get the max and print it together with its country however, I dont know how to get the min.

```<code>n =int(input("Enter the number of municipalities "))

for i in range(n):

    city = input("Enter the municipality: ")
    population = float(input("Enter the population: "))
    #processing information to calculate sum and max, min and range
    sum += population

    if max < population:
        max = population
        maxcity = city

print("The municipality with the highest population of", max, "million was " + maxcity)
</code>```

I need the same result for the min as I do for the max. What can I add to the if loop to make this happen? I am not allowed to use the built in max(), min() functions!

答:
Use this:

```<code>max_value = 0
max_city = ''
min_value = 10**20
min_city = ''
for i in range(n):

    city = input("Enter the municipality: ")
    population = float(input("Enter the population: "))

    if max_value < population:
        max_value = population
        max_city = city

    if min_value > population:
        min_value = population
        min_city = city

print("The municipality with the highest population of", max_value, "million was " + max_city)
print("The municipality with the lowest population of", min_value, "million was " + min_city)
</code>```

Output:

```<code>Enter the municipality: f
Enter the population: 10
Enter the municipality: g
Enter the population: 15
Enter the municipality: h
Enter the population: 80

The municipality with the highest population of 80.0 million was h
The municipality with the lowest population of 10.0 million was f
</code>```

Body:
I have to input several cities and their population and have to print the max and minimum population with the name of the city.

I've figured out how to get the max and print it together with its country however, I dont know how to get the min.

n =int(input("Enter the number of municipalities "))

for i in range(n):

    city = input("Enter the municipality: ")
    population = float(input("Enter the population: "))
    #processing information to calculate sum and max, min and range
    sum += population

    if max < population:
        max = population
        maxcity = city

print("The municipality with the highest population of", max, "million was " + maxcity)

I need the same result for the min as I do for the max. What can I add to the if loop to make this happen? I am not allowed to use the built in max(), min() functions!

Body:
Use this:

max_value = 0
max_city = ''
min_value = 10**20
min_city = ''
for i in range(n):

    city = input("Enter the municipality: ")
    population = float(input("Enter the population: "))

    if max_value < population:
        max_value = population
        max_city = city

    if min_value > population:
        min_value = population
        min_city = city

print("The municipality with the highest population of", max_value, "million was " + max_city)
print("The municipality with the lowest population of", min_value, "million was " + min_city)

Output:

Enter the municipality: f
Enter the population: 10
Enter the municipality: g
Enter the population: 15
Enter the municipality: h
Enter the population: 80

The municipality with the highest population of 80.0 million was h
The municipality with the lowest population of 10.0 million was f


问:
Ignore Duplicates and Create list of Unique Values separated with commas in Excel
```<code>Column A   Column B  Column C         Column D
a          a         a, a, b, c, c    a, b, c
a          b
b          c
c
c
</code>```

Can anybody please help me with my problem? I need unique values in one cell.

```<code>B2=INDEX($A$2:$A$6, MATCH(0, COUNTIF($B$1:B1, $A$2:$A$6), 0))
</code>```

So far I've found how to make list separated with commas.

```<code>C2 = {=TEXTJOIN(", ", TRUE, A2:A6)}
</code>```

How to apply Index or other function to  get unique values in D2 ?

答:
Would this work in D2:

```<code>=TEXTJOIN(", ",TRUE,IF(MATCH(A2:A6,A2:A6,0)=MATCH(ROW(A2:A6),ROW(A2:A6)),A2:A6,""))
</code>```

Confirm through CtrlShiftEnter

Unable to test this myself, no TEXTJOIN() on my Excel 2016 :(

Body:
Column A   Column B  Column C         Column D
a          a         a, a, b, c, c    a, b, c
a          b
b          c
c
c

Can anybody please help me with my problem? I need unique values in one cell.

B2=INDEX($A$2:$A$6, MATCH(0, COUNTIF($B$1:B1, $A$2:$A$6), 0))

So far I've found how to make list separated with commas.

C2 = {=TEXTJOIN(", ", TRUE, A2:A6)}

How to apply Index or other function to  get unique values in D2 ?

Body:
Would this work in D2:

=TEXTJOIN(", ",TRUE,IF(MATCH(A2:A6,A2:A6,0)=MATCH(ROW(A2:A6),ROW(A2:A6)),A2:A6,""))

Confirm through CtrlShiftEnter

Unable to test this myself, no TEXTJOIN() on my Excel 2016 :(


问:
Unity3d How to detect taps on android?
Currently I am struggling to work out how to create a simple bit of code that will tell me if a tap has happened, allowing me to get the position of taps. Having looked through many different articles I am rather stumped as Touch.tapCount that is often suggested only works for ios. Also, i have tried to use Touch.deltaTime and/or Touch.deltaPosition to detect a tap but have failed.

I define a tap as having

A very short period between the finger initially touching and finally exiting the phone

Little or no movement

Thanks for reading this, I hope its clear and precise and if any detail or assistance is required on my behalf in order for your to answer feel free to ask. Any assistance is gratefully received. Thanks.

Note - I work in C#

答:
After doing some searching (Googling "unity mobile detect tap"), I found this as the top search result. @Mothil's answer gets us very close to the solution and OP's answer solves the question. However, OP's answer does not account for multiple taps. Also tracking the count of started touches, ended touches, and moved touches (e.g. int SCount, MCount, ECount) is not necessary.

Instead we can directly loop through each touch and track each individual touch by its fingerId as @mothil did. For this we'll need two arrays to track a tap's characteristics: 1) short time delay, and 2) no movement. In the arrays below, the array index is the fingerId.

```<code>private float[] timeTouchBegan;
private bool[] touchDidMove;
</code>```

We'll also need one more variable to store our desired tap time threshold. In my tests, I found that a threshold of 0.2f works pretty well.

```<code>private float tapTimeThreshold = 0.2f;
</code>```

In the Start() function, we'll initialize this to hold 10 elements for 10 touches. This can be modified to however many touches desired.

In the Update() function, we loop through each touch. If in TouchPhase.Began then we set the timeTouchBegan[fingerIndex] to the current time; we also set touchDidMove[fingerIndex] to false.

If in TouchPhase.Moved, we set touchDidMove[fingerIndex] to true.

Finally, in TouchPhase.Ended, we can calculate the tap time.

```<code>float tapTime = Time.time - timeTouchBegan[fingerIndex];
</code>```

If the tap time is less than the threshold and the touch did not move then we have a verified tap.

```<code>if (tapTime <= tapTimeThreshold && touchDidMove[fingerIndex] == false)
{
    // Tap detected at touch.position
}
</code>```

Complete Script

Here's the full class:

```<code>public class TapManager : MonoBehaviour
{
    private float[] timeTouchBegan;
    private bool[] touchDidMove;
    private float tapTimeThreshold = 0.2f;

    void Start()
    {
        timeTouchBegan = new float[10];
        touchDidMove = new bool[10];
    }

    private void Update()
    {
        // Touches
        foreach (Touch touch in Input.touches)
        {
            int fingerIndex = touch.fingerId;

            if (touch.phase == TouchPhase.Began)
            {
                Debug.Log("Finger #" + fingerIndex.ToString() + " entered!");
                timeTouchBegan[fingerIndex] = Time.time;
                touchDidMove[fingerIndex] = false;
            }
            if (touch.phase == TouchPhase.Moved)
            {
                Debug.Log("Finger #" + fingerIndex.ToString() + " moved!");
                touchDidMove[fingerIndex] = true;
            }
            if (touch.phase == TouchPhase.Ended)
            {
                float tapTime = Time.time - timeTouchBegan[fingerIndex];
                Debug.Log("Finger #" + fingerIndex.ToString() + " left. Tap time: " + tapTime.ToString());
                if (tapTime <= tapTimeThreshold && touchDidMove[fingerIndex] == false)
                {
                    Debug.Log("Finger #" + fingerIndex.ToString() + " TAP DETECTED at: " + touch.position.ToString());
                }
            }
        }
    }
}
</code>```

Unity Tests

I tested this in my game using Unity Remote. In the screenshot below, you can see my debug console logs. I did a four finger tap. You can see that fingers 0 through 3 entered and left without any movement detected. A tap was detected for each finger and each tap's location was printed to the console.

Title: Unity3d How to detect taps on android?

Body:
After doing some searching (Googling "unity mobile detect tap"), I found this as the top search result. @Mothil's answer gets us very close to the solution and OP's answer solves the question. However, OP's answer does not account for multiple taps. Also tracking the count of started touches, ended touches, and moved touches (e.g. int SCount, MCount, ECount) is not necessary.

Instead we can directly loop through each touch and track each individual touch by its fingerId as @mothil did. For this we'll need two arrays to track a tap's characteristics: 1) short time delay, and 2) no movement. In the arrays below, the array index is the fingerId.

private float[] timeTouchBegan;
private bool[] touchDidMove;

We'll also need one more variable to store our desired tap time threshold. In my tests, I found that a threshold of 0.2f works pretty well.

private float tapTimeThreshold = 0.2f;

In the Start() function, we'll initialize this to hold 10 elements for 10 touches. This can be modified to however many touches desired.

In the Update() function, we loop through each touch. If in TouchPhase.Began then we set the timeTouchBegan[fingerIndex] to the current time; we also set touchDidMove[fingerIndex] to false.

If in TouchPhase.Moved, we set touchDidMove[fingerIndex] to true.

Finally, in TouchPhase.Ended, we can calculate the tap time.

float tapTime = Time.time - timeTouchBegan[fingerIndex];

If the tap time is less than the threshold and the touch did not move then we have a verified tap.

if (tapTime <= tapTimeThreshold && touchDidMove[fingerIndex] == false)
{
    // Tap detected at touch.position
}

Complete Script

Here's the full class:

public class TapManager : MonoBehaviour
{
    private float[] timeTouchBegan;
    private bool[] touchDidMove;
    private float tapTimeThreshold = 0.2f;

    void Start()
    {
        timeTouchBegan = new float[10];
        touchDidMove = new bool[10];
    }

    private void Update()
    {
        // Touches
        foreach (Touch touch in Input.touches)
        {
            int fingerIndex = touch.fingerId;

            if (touch.phase == TouchPhase.Began)
            {
                Debug.Log("Finger #" + fingerIndex.ToString() + " entered!");
                timeTouchBegan[fingerIndex] = Time.time;
                touchDidMove[fingerIndex] = false;
            }
            if (touch.phase == TouchPhase.Moved)
            {
                Debug.Log("Finger #" + fingerIndex.ToString() + " moved!");
                touchDidMove[fingerIndex] = true;
            }
            if (touch.phase == TouchPhase.Ended)
            {
                float tapTime = Time.time - timeTouchBegan[fingerIndex];
                Debug.Log("Finger #" + fingerIndex.ToString() + " left. Tap time: " + tapTime.ToString());
                if (tapTime <= tapTimeThreshold && touchDidMove[fingerIndex] == false)
                {
                    Debug.Log("Finger #" + fingerIndex.ToString() + " TAP DETECTED at: " + touch.position.ToString());
                }
            }
        }
    }
}

Unity Tests

I tested this in my game using Unity Remote. In the screenshot below, you can see my debug console logs. I did a four finger tap. You can see that fingers 0 through 3 entered and left without any movement detected. A tap was detected for each finger and each tap's location was printed to the console.


问:
I am facing an error when using the @login_required decorator, it shows TemplateDoesNotExist at /accounts/login/
I am trying to use login decorator in my project but when I use it it shows me the error

```<code>TemplateDoesNotExist at /accounts/login/

registration/login.html
</code>```

urls.py

```<code>path('', login.login_view , name='login'),
path('fileupload/', FileUpload.fileup, name='fileupload'),
</code>```

view.py->FileUpload.py->fileup

```<code>@login_required(login_url='login')
def fileup(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)

        if form.is_valid():
            form = form.save(commit=False)
            form.user = request.user
            form.save()
            print(form.image)
            print(form.user_id)
            send_message(str(form.image), form.user_id)

            text_filename = 'media/' + str(form.image).rstrip('.jpg') + '.txt'
            form.text_file = text_filename
            print(str(form.text_file))
            form.save()
            with open(text_filename, 'r+') as file:
                new_text = file.read()

            return render(request, "pd/NewText.html", {
                'form': form,
                'new_text': new_text,
            })
    else:
        form = DocumentForm()
    return render(request, 'pd/FileUpload.html', {'form': form})
</code>```

I want if user has not signed in and try to access the url fileupload\ then it not allow until he/she has not signed in.

答:
Django is trying to redirect to the default login route, which is /accounts/login, see the documentation. And the view behind that route needs a template.

The best approach IMO, in this case, is to change the settings to point to your login URL.

```<code># settings.py
LOGIN_URL = "/"
</code>```

Body:
I am trying to use login decorator in my project but when I use it it shows me the error

TemplateDoesNotExist at /accounts/login/

registration/login.html

urls.py

path('', login.login_view , name='login'),
path('fileupload/', FileUpload.fileup, name='fileupload'),

view.py->FileUpload.py->fileup

@login_required(login_url='login')
def fileup(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)

        if form.is_valid():
            form = form.save(commit=False)
            form.user = request.user
            form.save()
            print(form.image)
            print(form.user_id)
            send_message(str(form.image), form.user_id)

            text_filename = 'media/' + str(form.image).rstrip('.jpg') + '.txt'
            form.text_file = text_filename
            print(str(form.text_file))
            form.save()
            with open(text_filename, 'r+') as file:
                new_text = file.read()

            return render(request, "pd/NewText.html", {
                'form': form,
                'new_text': new_text,
            })
    else:
        form = DocumentForm()
    return render(request, 'pd/FileUpload.html', {'form': form})

I want if user has not signed in and try to access the url fileupload\ then it not allow until he/she has not signed in.

Body:
Django is trying to redirect to the default login route, which is /accounts/login, see the documentation. And the view behind that route needs a template.

The best approach IMO, in this case, is to change the settings to point to your login URL.

# settings.py
LOGIN_URL = "/"


答:
You can add a class on click with ngClass like this

<ion-content padding>
  <ion-item lines="none">
    <ion-button
      [ngClass]="yesButtonTriggered ? 'greenButton': 'light'"
      (click)="yesButton()"
      class="btn-1"
      expand="full"
      color="light"
    >Yes</ion-button>
    <ion-button
      [ngClass]="noButtonTriggered ? 'redButton': 'light'"
      (click)="noButton()"
      class="btn-2"
      expand="full"
      color="light"
    >No</ion-button>
  </ion-item>
</ion-content>
```

<p>And in your TS</p>

<pre class="lang-js prettyprint-override"><code>  yesButtonTriggered = false;
  noButtonTriggered = false;

  yesButton() {
    // do your stuff
    this.yesButtonTriggered = true;
    this.noButtonTriggered = false;
  }

  noButton() {
    // do your stuff
    this.noButtonTriggered = true;
    this.yesButtonTriggered = false;
  }
</code>```

Title: Change background color of buttons onclick

Body:
I have two buttons called YES and NO whose color(i,e background-color) is light like this:

When the user click YES

YES button background color should change to green (i,e success) and NO should be in light color like this:

When the user click No

NO button background color should change to red (i,e danger) and Yes should be in light color like this:

DEMO

while surfing i saw this question. Here they are changing only one button color on click. But for my requirement both the button color should change on click.

CODE

HTML

<ion-content padding>
  <ion-item lines="none">
  <ion-button class="btn-1" expand="full" color="light" >Yes</ion-button>
   <ion-button class="btn-2" expand="full"  color="light" >No</ion-button>
  </ion-item>
</ion-content>

CSS

.btn-1{
width:45%;
float:left;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}
.btn-2{
width:45%;
float:right;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}

TS

 import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.css'],
})
export class HomePage {

}

Body:
You can add a class on click with ngClass like this

<ion-content padding>
  <ion-item lines="none">
    <ion-button
      [ngClass]="yesButtonTriggered ? 'greenButton': 'light'"
      (click)="yesButton()"
      class="btn-1"
      expand="full"
      color="light"
    >Yes</ion-button>
    <ion-button
      [ngClass]="noButtonTriggered ? 'redButton': 'light'"
      (click)="noButton()"
      class="btn-2"
      expand="full"
      color="light"
    >No</ion-button>
  </ion-item>
</ion-content>

And in your TS

  yesButtonTriggered = false;
  noButtonTriggered = false;

  yesButton() {
    // do your stuff
    this.yesButtonTriggered = true;
    this.noButtonTriggered = false;
  }

  noButton() {
    // do your stuff
    this.noButtonTriggered = true;
    this.yesButtonTriggered = false;
  }