问:
cannot implicitly convert type 'string' to 'ConsoleApp3.Program.Status'
I'm practising doing code, I'm a beginner, and for some reason it's not working.

I've searched for some solutions, but I have found nothing in this matter.

```<code>namespace ConsoleApp3
{
    class Program
    {
        public enum Status { single, taken };

        public class Person
        {
            public string name;
            public int age;

            public string status;

             public Person(string _name, int _age, Status _status)
            {
                _name = name;
                _age = age;
                _status = status;

            }
            public void Print()
            {
                Console.WriteLine("Name: " + name );
                Console.WriteLine("Age: " + age );
                Console.WriteLine("Status: " + status);
            }
        }
        static void Main(string[] args)
        {

            Person Jackk = new Person("Jack", 20, Status.single);
            Jackk.Print();

            }
        }
    }
}
</code>```

I expect it would write all the information about the person, but it outputs the stuff in the Print void, but it doesn't use any of the variables, it will just print for example- Age : 0, even though it's set to 20.

I've got some messages about this. It says about the _age, _name, etc. that the value assigned to them is never used. But why?

Sorry if it's obvious, I'm still a beginner.

(the error says: cannot implicitly convert type 'string' to 'ConsoleApp3.Program.Status'), but if I removed the status thing completely, it would still not assign the variables to the output.

答:
Issue 1:

In parameterized constructor of Person class you are assigning class variables  to the parameters which you are passing to the constructor.

You need to do it in opposite way,

```<code> Person Jackk = new Person("Jack", 20, Status.single);
</code>```

Values which you are passing while creating instance get stored in variables defined as a parameters in constructor that are (string _name, int _age, Status _status)

You need to change code in constructor like

```<code>public Person(string _name, int _age, Status _status)
   {
      this.name = _name; //name = "Jack";
      this.age = _age  // age =  20;
      this.status = _status //status =  Status.single;
   }
</code>```

Issue 2:

To print string value of enum you need convert enum value to string using .ToString() function

```<code> public void Print()
    {
         Console.WriteLine("Name: " + name );
         Console.WriteLine("Age: " + age );
         Console.WriteLine("Status: " + status.ToString());
                                            //^^^^^^^^^^^ this was missing
    }
</code>```

Issue 3:

You need to define status variable of type Status inside Person class,

```<code>public Status status;
</code>```

or if you want status with string data type then you need to use ToString() while assigning value to that variable

```<code>this.status = _status.ToString(); //status = "single";
</code>```

Body:
I'm practising doing code, I'm a beginner, and for some reason it's not working.

I've searched for some solutions, but I have found nothing in this matter.

namespace ConsoleApp3
{
    class Program
    {
        public enum Status { single, taken };

        public class Person
        {
            public string name;
            public int age;

            public string status;

             public Person(string _name, int _age, Status _status)
            {
                _name = name;
                _age = age;
                _status = status;

            }
            public void Print()
            {
                Console.WriteLine("Name: " + name );
                Console.WriteLine("Age: " + age );
                Console.WriteLine("Status: " + status);
            }
        }
        static void Main(string[] args)
        {

            Person Jackk = new Person("Jack", 20, Status.single);
            Jackk.Print();

            }
        }
    }
}

I expect it would write all the information about the person, but it outputs the stuff in the Print void, but it doesn't use any of the variables, it will just print for example- Age : 0, even though it's set to 20.

I've got some messages about this. It says about the _age, _name, etc. that the value assigned to them is never used. But why?

Sorry if it's obvious, I'm still a beginner.

(the error says: cannot implicitly convert type 'string' to 'ConsoleApp3.Program.Status'), but if I removed the status thing completely, it would still not assign the variables to the output.

Body:
Issue 1:

In parameterized constructor of Person class you are assigning class variables  to the parameters which you are passing to the constructor.

You need to do it in opposite way,

 Person Jackk = new Person("Jack", 20, Status.single);

Values which you are passing while creating instance get stored in variables defined as a parameters in constructor that are (string _name, int _age, Status _status)

You need to change code in constructor like

public Person(string _name, int _age, Status _status)
   {
      this.name = _name; //name = "Jack";
      this.age = _age  // age =  20;
      this.status = _status //status =  Status.single;
   }

Issue 2:

To print string value of enum you need convert enum value to string using .ToString() function

 public void Print()
    {
         Console.WriteLine("Name: " + name );
         Console.WriteLine("Age: " + age );
         Console.WriteLine("Status: " + status.ToString());
                                            //^^^^^^^^^^^ this was missing
    }

Issue 3:

You need to define status variable of type Status inside Person class,

public Status status;

or if you want status with string data type then you need to use ToString() while assigning value to that variable

this.status = _status.ToString(); //status = "single";


来源: stackexchange

问:
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.ArgumentNullException
I've been getting the error:

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.ArgumentNullException

When I try to call my webservice using the following code:

```<code>{
//Create an echoSync request - set the services.
ServiceNameType sourceService = new ServiceNameType {Service = "echoSync", OnBehalfOf = "Source"};
ServiceNameType destService = new ServiceNameType {Service = "echoSync", OnBehalfOf = "Destination"};

//Create the request.
SDD2RequestType request = new SDD2RequestType
                  {
                      AppId = "echoSync",
                      SourceService = sourceService,
                      DestService = destService,
                      RequestId = "1",
                      RequestBody = "Ping"
                  };

//Create the originator.
originator originator = new originator {id = "123456789"};

//Create the transport.
SDD2Transport transport = new SDD2Transport {originatorValue = originator};

//Send the request.
SDD2ResponseType response = null;
response = transport.SDD2TransportOp(request);

//Write out the response.
System.Console.WriteLine(response.ResponseBody.ToString());
}
</code>```

My webservice method is quite simple and it looks like this:

```<code>    [System.Web.Services.Protocols.SoapHeaderAttribute("originatorValue", Direction = System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
    [System.Web.Services.WebMethodAttribute()]
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://memberdirect.net/SDD2/Transport", RequestElementName = "SDD2Transport", RequestNamespace = "http://cucbc.com/sdd2/transport/", ResponseElementName = "SDD2TransportResponse", ResponseNamespace = "http://cucbc.com/sdd2/transport/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Default)]
    [return: System.Xml.Serialization.XmlElementAttribute("SDD2Response", Namespace = "http://cucbc.com/sdd2/")]
    public override SDD2ResponseType SDD2TransportOp(SDD2RequestType SDD2Request)
    {
        if (SDD2Request == null) throw new ArgumentNullException("SDD2Request");
        var response = new SDD2ResponseType();

        switch (SDD2Request.AppId)
        {
            case "echoSync":
                response.AppId = SDD2Request.AppId;
                response.ProcessingStatus = ProcessingStatusType.Complete;
                response.RequestId = SDD2Request.RequestId;
                response.ResponseBody = "Pong";
                break;
            default:
                throw new System.NotImplementedException();
                break;
        }

        return response;
    }
</code>```

When I make the call I know the request is not NULL but when it arrives at the webservice it is always received as null.  I generated the webservice from WSDL using the wsdl.exe utility and clearly I don't understand all the details of SOAP that I should.  Has anyone else run into this issue?

答:
I didn't have a chance to use Wireshark as Configurator suggested but I was able to resolve this issue by Updating Web Reference in the Solution Explorer.

I'm a bit chagrined at having found such a simple solution to this after having wrestled with it for over an hour but I hope that this post helps someone out there.

OwnerDisplayName: Daver

ContentLicense: CC BY-SA 3.0

Body:
I've been getting the error:

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.ArgumentNullException

When I try to call my webservice using the following code:

{
//Create an echoSync request - set the services.
ServiceNameType sourceService = new ServiceNameType {Service = "echoSync", OnBehalfOf = "Source"};
ServiceNameType destService = new ServiceNameType {Service = "echoSync", OnBehalfOf = "Destination"};

//Create the request.
SDD2RequestType request = new SDD2RequestType
                  {
                      AppId = "echoSync",
                      SourceService = sourceService,
                      DestService = destService,
                      RequestId = "1",
                      RequestBody = "Ping"
                  };

//Create the originator.
originator originator = new originator {id = "123456789"};

//Create the transport.
SDD2Transport transport = new SDD2Transport {originatorValue = originator};

//Send the request.
SDD2ResponseType response = null;
response = transport.SDD2TransportOp(request);

//Write out the response.
System.Console.WriteLine(response.ResponseBody.ToString());
}

My webservice method is quite simple and it looks like this:

    [System.Web.Services.Protocols.SoapHeaderAttribute("originatorValue", Direction = System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
    [System.Web.Services.WebMethodAttribute()]
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://memberdirect.net/SDD2/Transport", RequestElementName = "SDD2Transport", RequestNamespace = "http://cucbc.com/sdd2/transport/", ResponseElementName = "SDD2TransportResponse", ResponseNamespace = "http://cucbc.com/sdd2/transport/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Default)]
    [return: System.Xml.Serialization.XmlElementAttribute("SDD2Response", Namespace = "http://cucbc.com/sdd2/")]
    public override SDD2ResponseType SDD2TransportOp(SDD2RequestType SDD2Request)
    {
        if (SDD2Request == null) throw new ArgumentNullException("SDD2Request");
        var response = new SDD2ResponseType();

        switch (SDD2Request.AppId)
        {
            case "echoSync":
                response.AppId = SDD2Request.AppId;
                response.ProcessingStatus = ProcessingStatusType.Complete;
                response.RequestId = SDD2Request.RequestId;
                response.ResponseBody = "Pong";
                break;
            default:
                throw new System.NotImplementedException();
                break;
        }

        return response;
    }

When I make the call I know the request is not NULL but when it arrives at the webservice it is always received as null.  I generated the webservice from WSDL using the wsdl.exe utility and clearly I don't understand all the details of SOAP that I should.  Has anyone else run into this issue?

ContentLicense: CC BY-SA 2.5


问:
Is there a way to completely remove an inode when the Link count is 2?
Currently my data is organised in a volume which has a cache directory (where all the files are first created or transferred). After that there are suitable directories on the volume which in their subdirs, contain files hardlinked to files in the cache.
This is done so that the same inode (file) can be hardlinked multiple times in multiple directories.

Now when trying to clean up the volume, I recurively go through the dirs(not the cache) and based on certain criterion, unlink the files (which basically reduces the inode count of the cache entry by 1). Is there a way for me to delete the cache entry directly, when I am deleting the last hardlink (that is bringing down the count from 2 to 1). This way I would not have to manually parse through the whole cache directory to clear any inodes from it, which have a link count of just 1.

I have gone through unlink/remove functions, and could not find anything specific of use. Is there some purging algorithm that internally takes care of this, then I can try to implement that.

Any help on this would be highly appreciated. In anticipation of a prompt reply.

答: I saw this and a few other places which instruct you how to delete all hardlinks from shell (use find -samefile and call remove on each file). You could call it via system although that might be frowned on by some people).</p>


问:
Can I change the error message thrown for duplicate key in PostgreSQL?
I have a stored procedure which basically inserts into a table. When a primary key is duplicated, it throws

```<code>duplicate key value violates unique constraint
</code>```

error which I catch in my code and display in my UI.

Is there anyway I can modify this error content to something customized? I know I can use trigger and RAISE a customized message. I just want to know if there is an alternative.

答:
I'd write a function that inserts the row. If the table is called mytab:

```<code>CREATE FUNCTION insert_mytab(p_row mytab) RETURNS void
   LANGUAGE plpgsql AS
$$BEGIN
   INSERT INTO mytab SELECT (p_row).*;
EXCEPTION
   WHEN unique_violation THEN
      RAISE EXCEPTION 'don''t tickle me';
END;$$;
</code>```

I don't think there is a fundamentally different way.

ContentLicense: CC BY-SA 4.0

Body:
I have a stored procedure which basically inserts into a table. When a primary key is duplicated, it throws

duplicate key value violates unique constraint

error which I catch in my code and display in my UI.

Is there anyway I can modify this error content to something customized? I know I can use trigger and RAISE a customized message. I just want to know if there is an alternative.

Body:
I'd write a function that inserts the row. If the table is called mytab:

CREATE FUNCTION insert_mytab(p_row mytab) RETURNS void
   LANGUAGE plpgsql AS
$$BEGIN
   INSERT INTO mytab SELECT (p_row).*;
EXCEPTION
   WHEN unique_violation THEN
      RAISE EXCEPTION 'don''t tickle me';
END;$$;

I don't think there is a fundamentally different way.


问:
Understanding Component Communication using SubjectBehaviour
I am watching this video on RxJs Subjects.

https://www.youtube.com/watch?v=DvnzeCfYg0s.

When the form is submitted ,i understand that the subject's refreshneeded$
next method is called.

I am given to understand though that the chotchkies-list.component is rendered only once using its ngOninit method.

But in this particular case it looks like when the form is submitted
the subjects next method is called.

But how does calling the next method on refreshneeded$ subject in turn trigger the ngOninit of the chotchkies-list.component ?

Ahh yes and here is the github code

https://github.com/krimple/rxjs-playground

答:
If I understand your question correctly, then your question is about a very central concept in how Rxjs works.

When you subscribe to an Observable, like it is done in the ngOnInit, you are saying that you want this code to run every time a new value is emitted by this observable. This is a key concept of Rxjs and observables.

It is also the difference between imperative and reactive programming. When you program imperativly (the most common way), then the place in your code where an event happens need to know what functions to call next. But with observables we are programming reactively, here we can say that this code should react to some event, and the event itself does not need to know what function to call.


问:
Bigcommerce template is not applied on localhost
I uploaded a new template, let's call it my-template, using stencil tool. The template file is placed in folder pages/custom/page/my-template. I can select the template in the Template dropdown section on admin page, so I assumed the template is uploaded successfully.

The problem is that, when I preview this page, the template is applied, but on my local, the custom template is not applied (instead, it uses the default page template). Is there any step or any setting missing here? What can I do to work with my-template on localhost?

答:
When you're working locally, your .stencil file controls the mapping between custom templates and the pages they should be assigned to. Here's an example that would apply the custom my-template file to a webpage whose URL is /about-us/ :

```<code>{
  "normalStoreUrl": "http://mystore.mybigcommerce.com",
  "port": 3000,
  "clientId": "xxxxxxxxxxxxxxxxx",
  "accessToken": "xxxxxxxxxxxxxxxxxx",
  "customLayouts": {
    "brand": {},
    "category": {},
    "page": {
    "my-template.html": "/about-us/"
    },
    "product": {}
  }
}
</code>```

Note: After you edit your .stencil file, you'll want to re-start the CLI to see your changes applied

https://developer.bigcommerce.com/stencil-docs/template-files/custom-templates/authoring-testing-uploading-custom-templates#authoring-testing-uploading_local-mapping

Body:
When you're working locally, your .stencil file controls the mapping between custom templates and the pages they should be assigned to. Here's an example that would apply the custom my-template file to a webpage whose URL is /about-us/ :

{
  "normalStoreUrl": "http://mystore.mybigcommerce.com",
  "port": 3000,
  "clientId": "xxxxxxxxxxxxxxxxx",
  "accessToken": "xxxxxxxxxxxxxxxxxx",
  "customLayouts": {
    "brand": {},
    "category": {},
    "page": {
    "my-template.html": "/about-us/"
    },
    "product": {}
  }
}

Note: After you edit your .stencil file, you'll want to re-start the CLI to see your changes applied

https://developer.bigcommerce.com/stencil-docs/template-files/custom-templates/authoring-testing-uploading-custom-templates#authoring-testing-uploading_local-mapping


问:
Operator precedence for IBM DB2
What are the operator precedence rules for the DB2 RDBMS engine?

I am looking for explicit rules which mention actual operators instead of precedence relations between groups of operators.

I found this document http://www-01.ibm.com/support/knowledgecenter/SSEPEK_10.0.0/com.ibm.db2z10.doc.sqlref/src/tpc/db2z_precedenceofoperations.dita via googling, but I am looking for something that goes into more detail, e.g. precedence relations between AND, OR and NOT

答:
I used a case in my order by and it seemed to work

```<code>SELECT * FROM TABLE WHERE KEY IN (KEY1 , KEY2) ORDER BY
CASE
     WHEN KEY = KEY1 THEN 1
     ELSE 2
END
</code>```

I haven't check with more than 2 keys.

Title: Operator precedence for IBM DB2

Body:
I used a case in my order by and it seemed to work

SELECT * FROM TABLE WHERE KEY IN (KEY1 , KEY2) ORDER BY
CASE
     WHEN KEY = KEY1 THEN 1
     ELSE 2
END

I haven't check with more than 2 keys.


问:
How to add a checkbox control to a datatable?
How can i add a checkbox to a datatable and bind it to a datagrid?

```<code>DataTable ColumnList = new DataTable();
ColumnList.Columns.Add("Column Fields");

int j = 1, i = 0;
CheckBox colCheckbox = new CheckBox();
foreach (Columns col in ColumnNames)
{
    colCheckbox.Name = col.ColumnName;
    ColumnList.Rows.Add(colCheckbox); // This is getting displayed as System.Windows.Forms.CheckBox,CheckState=0
}
</code>```

Please help.

答:
You have to specify the type of the column.

```<code>ColumnList.Columns.Add("Column Fields", gettype(CheckBox));
</code>```

But why do you want to add a control to a DataTable? Why not just a string or an integer?

Body:
How can i add a checkbox to a datatable and bind it to a datagrid?

DataTable ColumnList = new DataTable();
ColumnList.Columns.Add("Column Fields");

int j = 1, i = 0;
CheckBox colCheckbox = new CheckBox();
foreach (Columns col in ColumnNames)
{
    colCheckbox.Name = col.ColumnName;
    ColumnList.Rows.Add(colCheckbox); // This is getting displayed as System.Windows.Forms.CheckBox,CheckState=0
}

Please help.

Body:
You have to specify the type of the column.

ColumnList.Columns.Add("Column Fields", gettype(CheckBox));

But why do you want to add a control to a DataTable? Why not just a string or an integer?


问:
Why when I format a double it returns me with a comma?
When I format a double number it returns me with a comma, but I need it to return with a period. By the way I'm with the IDE NetBeans

```<code>double importe = (catidad * precioUnit);
System.out.println("double : " + importe);

System.out.println("double : " + String.format("%.2f", importe));

System.out.format("double : %.2f", importe);
</code>```

returns:

```<code>run:
double : 5.699999999999999

double : 5,70

double : 5,70
</code>```

I want you to return me with a point

答:
that depends on the local formatting </p>

```<code>Locale.setDefault(Locale.US);
System.out.println(String.format(Locale.US, "%f", 3.141592));
</code>```

Body:
When I format a double number it returns me with a comma, but I need it to return with a period. By the way I'm with the IDE NetBeans

double importe = (catidad * precioUnit);
System.out.println("double : " + importe);

System.out.println("double : " + String.format("%.2f", importe));

System.out.format("double : %.2f", importe);

returns:

run:
double : 5.699999999999999

double : 5,70

double : 5,70

I want you to return me with a point

Body:
that depends on the local formatting

Locale.setDefault(Locale.US);
System.out.println(String.format(Locale.US, "%f", 3.141592));


问:
Can I optimize for median relative absolute error in `caret`?
I have a KNN model in caret and I'd like to optimize for median relative absolute error.

```<code>library(caret)
model <- train(
  close_price~ ., data = train.data, method = "knn",
  trControl = trainControl("cv", number = 10),
  preProcess = c("center", "scale"),
  metric = "MdRAE",
  tuneLength = 10
)
</code>```

I tried to use MdRAE and MDRAE and they both returned this error.

```<code>Warning message:
In train.default(x, y, weights = w, ...) :
  The metric "MdRAE" was not in the result set. RMSE will be used instead
</code>```

Is there a list of all the metrics available? I couldn't find it in the caret ebook.

答:
This metric is not directly implemented in caret but you can easily do it yourself:

```<code>mdrae_summary <- function(data, lev=NULL, model=NULL) {
    c(MdRAE=median(abs(data$pred - data$obs)/data$obs))
}

model <- train(
  close_price~ ., data = train.data, method = "knn",
  trControl = trainControl("cv", number = 10, summaryFunction = mdrae_summary),
  preProcess = c("center", "scale"),
  metric = "MdRAE",
  tuneLength = 10
)
</code>```

Body:
I have a KNN model in caret and I'd like to optimize for median relative absolute error.

library(caret)
model <- train(
  close_price~ ., data = train.data, method = "knn",
  trControl = trainControl("cv", number = 10),
  preProcess = c("center", "scale"),
  metric = "MdRAE",
  tuneLength = 10
)

I tried to use MdRAE and MDRAE and they both returned this error.

Warning message:
In train.default(x, y, weights = w, ...) :
  The metric "MdRAE" was not in the result set. RMSE will be used instead

Is there a list of all the metrics available? I couldn't find it in the caret ebook.

Body:
This metric is not directly implemented in caret but you can easily do it yourself:

mdrae_summary <- function(data, lev=NULL, model=NULL) {
    c(MdRAE=median(abs(data$pred - data$obs)/data$obs))
}

model <- train(
  close_price~ ., data = train.data, method = "knn",
  trControl = trainControl("cv", number = 10, summaryFunction = mdrae_summary),
  preProcess = c("center", "scale"),
  metric = "MdRAE",
  tuneLength = 10
)


问:
jQuery load function ignores Cache-Control max-age
I am using jQuery's load function to get an image (graph) from my server. The graph is received from a REST API protected with Basic Authentication. The image is in the current setup returned with header Cache-Control max-age=0. This is respected if I call the image url directly from the browser. But when using jQuery's load function, it is cached.

I don't want to get a new image every time, because it requires some heavy calculations on the server, and because the graphs shows real-time data, long time caching is unwanted. I will use max-age=30 or 60 later.

I know jQuery's ajax function has a cache option. But this option can only be set to true or false, and that's not what I'm looking for.

答:
The standard way to override getting a cached result is to append a random query string to the URL you're getting, as in:

```<code>$(this).attr('src', url + '?randomval=' + (new Date).getTime() );
</code>```

You can then set the server headers to allow the client to cache (e.g. Cache-Control: private - or whatever is appropriate for your application), and decide in your javascript code how often you want to change the "random" value appended to your URL to force the resource to reload.

Body:
The standard way to override getting a cached result is to append a random query string to the URL you're getting, as in:

$(this).attr('src', url + '?randomval=' + (new Date).getTime() );

You can then set the server headers to allow the client to cache (e.g. Cache-Control: private - or whatever is appropriate for your application), and decide in your javascript code how often you want to change the "random" value appended to your URL to force the resource to reload.


问:
Looping to organize and display custom posts by category using PHP and WordPress
I am developing a page that requires me to display a list of categories for a custom post type in an accordion-style dropdown. The category name will act as the accordion title, and the contents are to be the posts associated with each particular category. The image below summarizes what I would ultimately accomplish.

I've be able to successfully retrieve the category names and assign them to an accordion dropdown, but what is happening is that my code is adding new cells even though the two posts are associated with the similar category name.

Arrrrrg, I feel like i'm so close! Here's a snippet of what my code looks like so far.

```<code><div id="accordion" class="col-8" role="tablist" aria-multiselectable="true">
              <?php
                    $args = array(
                        'post_type' => 'our_work',
                        'posts_per_page' => -1,
                        'orderby' => 'category',
                        'hide_empty' => 0,
                    );
                    $loop = new WP_Query( $args );
                    while ( $loop->have_posts() ) : $loop->the_post();
                ?>
        <div class="card box-shadow">

            <div class="card-header" role="tab" id="<?php the_ID(); ?>">
                <h5 class="mb-0">
                    <a data-toggle="collapse" data-parent="#accordion" href="#collapse<?php the_ID(); ?>"
                        aria-expanded="false" aria-controls="collapseOne">
                        <?php
                          foreach((get_the_category()) as $category) {
                              echo $category->cat_name . ' ';
                          }
                        ?>
                    </a>
                </h5>
            </div>

            <div id="collapse<?php the_ID(); ?>" style="transition: all 0.5s ease 0s;" class="collapse nomnom"
                role="tabpanel" aria-labelledby="heading<?php the_ID(); ?>">
                <div class="card-block">
                    <h1><?php the_title(); ?></h1>
                    <p><?php the_Content(); ?></p>
                </div>
            </div>

        </div>
        <?php endwhile; wp_reset_query(); ?>
    </div>
</code>```

What I suspect is going on is that I don't have my loop set up properly and is adding a new cell as a result.

I am still fairly new to working with the 'WordPress loop', so any advice would be greatly appreciated!!!

答:
Edited to use echo instead. This should be cleaner and hopefully work (untested)</p>

```<code>  <?php
   $args = array(
      'post_type' => 'our_work',
      'posts_per_page' => -1,
      'orderby' => 'category',
      'hide_empty' => 0,
   );
  $loop = new WP_Query( $args );
  $cat = '';//set a variable to catch category
  $first = 0;
  echo '<div id="accordion" class="col-8" role="tablist" aria-multiselectable="true">';
  while ( $loop->have_posts() ) : $loop->the_post();
    $post_cat = '';
    foreach(( get_the_category() ) as $category) {
      $post_cat = $category->cat_name . ' ';
    }
    if($first == 0){
      $first = 1;
      $cat = $post_cat;
      echo '<div class="card box-shadow">';
      echo'<div class="card-header" role="tab" id="'.get_the_id().'">';
      echo'<h5 class="mb-0">';
      echo'<a data-toggle="collapse" data-parent="#accordion" href="#collapse'.get_the_id().'"aria-expanded="false" aria-controls="collapseOne">'.$post_cat.'</a>';
      echo'</h5>';
      echo'</div>';
      //start collapse pannel
      echo'<div id="collapse'.get_the_id().'" style="transition: all 0.5s ease 0s;" class="collapse nomnom" role="tabpanel" aria-labelledby="heading'.get_the_id().'">';
    }
    if($cat != $post_cat){
      $cat = $post_cat;
      echo'</div>';//close collapse
      echo'</div>';//close box shadow
      echo '<div class="card box-shadow">';
      echo'<div class="card-header" role="tab" id="'.get_the_id().'">';
      echo'<h5 class="mb-0">';
      echo'<a data-toggle="collapse" data-parent="#accordion" href="#collapse'.get_the_id().'"aria-expanded="false" aria-controls="collapseOne">'.$post_cat.'</a>';
      echo'</h5>';
      echo'</div>';
      //start collapse pannel
      echo'<div id="collapse'.get_the_id().'" style="transition: all 0.5s ease 0s;" class="collapse nomnom" role="tabpanel" aria-labelledby="heading'.get_the_id().'">';
    }
    echo'<div class="card-block">';
    echo'<h1>'.get_the_title().'</h1>';
    echo'<p>'.get_the_content().'</p>';
    echo'</div>';
    if (($loop->current_post +1) == ($loop->post_count)) {
      echo '</div>';//close collapse
      echo '</div>';//box shadow close
    }
  endwhile;
  wp_reset_query();
  echo '</div>';//close accordian close
    ?>
</code>```

Body:
I am developing a page that requires me to display a list of categories for a custom post type in an accordion-style dropdown. The category name will act as the accordion title, and the contents are to be the posts associated with each particular category. The image below summarizes what I would ultimately accomplish.

I've be able to successfully retrieve the category names and assign them to an accordion dropdown, but what is happening is that my code is adding new cells even though the two posts are associated with the similar category name.

Arrrrrg, I feel like i'm so close! Here's a snippet of what my code looks like so far.

              <?php
                    $args = array(
                        'post_type' => 'our_work',
                        'posts_per_page' => -1,
                        'orderby' => 'category',
                        'hide_empty' => 0,
                    );
                    $loop = new WP_Query( $args );
                    while ( $loop->have_posts() ) : $loop->the_post();
                ?>

            <div class="card-header" role="tab" id="<?php the_ID(); ?>">

                    <a data-toggle="collapse" data-parent="#accordion" href="#collapse<?php the_ID(); ?>"
                        aria-expanded="false" aria-controls="collapseOne">
                        <?php
                          foreach((get_the_category()) as $category) {
                              echo $category->cat_name . ' ';
                          }
                        ?>

            <div id="collapse<?php the_ID(); ?>" style="transition: all 0.5s ease 0s;" class="collapse nomnom"
                role="tabpanel" aria-labelledby="heading<?php the_ID(); ?>">

<?php the_title(); ?>

<?php the_Content(); ?>

        <?php endwhile; wp_reset_query(); ?>

What I suspect is going on is that I don't have my loop set up properly and is adding a new cell as a result.

I am still fairly new to working with the 'WordPress loop', so any advice would be greatly appreciated!!!

Body:
Edited to use echo instead. This should be cleaner and hopefully work (untested)

  <?php
   $args = array(
      'post_type' => 'our_work',
      'posts_per_page' => -1,
      'orderby' => 'category',
      'hide_empty' => 0,
   );
  $loop = new WP_Query( $args );
  $cat = '';//set a variable to catch category
  $first = 0;
  echo '<div id="accordion" class="col-8" role="tablist" aria-multiselectable="true">';
  while ( $loop->have_posts() ) : $loop->the_post();
    $post_cat = '';
    foreach(( get_the_category() ) as $category) {
      $post_cat = $category->cat_name . ' ';
    }
    if($first == 0){
      $first = 1;
      $cat = $post_cat;
      echo '<div class="card box-shadow">';
      echo'<div class="card-header" role="tab" id="'.get_the_id().'">';
      echo'<h5 class="mb-0">';
      echo'<a data-toggle="collapse" data-parent="#accordion" href="#collapse'.get_the_id().'"aria-expanded="false" aria-controls="collapseOne">'.$post_cat.'</a>';
      echo'</h5>';
      echo'</div>';
      //start collapse pannel
      echo'<div id="collapse'.get_the_id().'" style="transition: all 0.5s ease 0s;" class="collapse nomnom" role="tabpanel" aria-labelledby="heading'.get_the_id().'">';
    }
    if($cat != $post_cat){
      $cat = $post_cat;
      echo'</div>';//close collapse
      echo'</div>';//close box shadow
      echo '<div class="card box-shadow">';
      echo'<div class="card-header" role="tab" id="'.get_the_id().'">';
      echo'<h5 class="mb-0">';
      echo'<a data-toggle="collapse" data-parent="#accordion" href="#collapse'.get_the_id().'"aria-expanded="false" aria-controls="collapseOne">'.$post_cat.'</a>';
      echo'</h5>';
      echo'</div>';
      //start collapse pannel
      echo'<div id="collapse'.get_the_id().'" style="transition: all 0.5s ease 0s;" class="collapse nomnom" role="tabpanel" aria-labelledby="heading'.get_the_id().'">';
    }
    echo'<div class="card-block">';
    echo'<h1>'.get_the_title().'</h1>';
    echo'<p>'.get_the_content().'</p>';
    echo'</div>';
    if (($loop->current_post +1) == ($loop->post_count)) {
      echo '</div>';//close collapse
      echo '</div>';//box shadow close
    }
  endwhile;
  wp_reset_query();
  echo '</div>';//close accordian close
    ?>


问:
First letter capitalization for EditText
I'm working on a little personal todo list app and so far everything has been working quite well. There is one little quirk I'd like to figure out. Whenever I go to add a new item, I have a Dialog with an EditText view showing inside. When I select the EditText view, the keyboard comes up to enter text, as it should. In most applications, the default seems to be that the shift key is held for the first letter... although it does not do this for my view. There has to be a simple way to fix, but I've searched the reference repeatedly and cannot find it. I'm thinking there has to be an xml attribute for the reference loaded by the Adapter, but I can't find out what it is.</p>

答:
For Capitalisation in EditText you can choose the below two input types:

android:inputType="textCapSentences"

android:inputType="textCapWords"

textCapSentences

This will let the first letter of the first word as Capital in every sentence.

textCapWords
This will let the first letter of every word as Capital.

If you want both the attributes just use | sign with both the attributes

```<code>android:inputType="textCapSentences|textCapWords"
</code>```

Body:
For Capitalisation in EditText you can choose the below two input types:

android:inputType="textCapSentences"

android:inputType="textCapWords"

textCapSentences

This will let the first letter of the first word as Capital in every sentence.

textCapWords
This will let the first letter of every word as Capital.

If you want both the attributes just use | sign with both the attributes

android:inputType="textCapSentences|textCapWords"


问:
Find the prime DATE
2019-05-23 is a normal but great day. It is normal because there is nothing big happen to me, it is also very great since I find this story in my social network.

20190523 is a prime.

0190523 is a prime.(let's just allow this leading zero)

190523 is a prime.

...

23 is a prime.

3 is a prime.

So my question is : Are there any other date behaves the same properties?
And what I want is a very nice method so let's limit the search range as 2019-05-23 to 9999-12-31.

Hope you can enjoy this puzzle.

答:
So there was just a discussion about how to generate prime numbers using Sieve of Eratosthenes method.  So we can first run that and then loop over the dates and convert them into the series of numbers and check if they are primes.

```<code>data prime_dates ;
  array sieve[99991231] _temporary_ ;
  sieve[1]=1;
  do i=2 to int(sqrt(hbound(sieve)));
    if sieve[i]=. then do j=i**2 by i to hbound(sieve);
      sieve[j]=1;
    end;
  end;
  do date='23may2019'd to '31DEC9999'd ;
    string=put(date,yymmddn8.);
    prime=1;
    do pos=1 to 8 while(prime);
      prime=.=sieve[input(substr(string,pos),8.)];
    end;
    if prime then output;
  end;
  stop;
  drop i j pos prime;
  format date yymmdd10.;
run;
</code>```

This results in 409 similar date.  The next is in August of this year.  Here are the first 10.

```<code>Obs          date     string

  1    2019-05-23    20190523
  2    2019-08-23    20190823
  3    2030-03-17    20300317
  4    2036-03-17    20360317
  5    2040-03-07    20400307
  6    2040-08-23    20400823
  7    2048-01-07    20480107
  8    2060-03-17    20600317
  9    2066-06-17    20660617
 10    2070-01-03    20700103
</code>```

Note there is no need to add index 0 to the sieve since the 10th, 20th and 30th day of the month will fail at the 2 digit check as being not prime so index of 0 is never attempted.

I counted 1 as NOT prime.  If you count 1 as prime then you get an additional 185 dates, first one being the first day of year 2060.

Title: Find the prime DATE

Body:
So there was just a discussion about how to generate prime numbers using Sieve of Eratosthenes method.  So we can first run that and then loop over the dates and convert them into the series of numbers and check if they are primes.

data prime_dates ;
  array sieve[99991231] _temporary_ ;
  sieve[1]=1;
  do i=2 to int(sqrt(hbound(sieve)));
    if sieve[i]=. then do j=i**2 by i to hbound(sieve);
      sieve[j]=1;
    end;
  end;
  do date='23may2019'd to '31DEC9999'd ;
    string=put(date,yymmddn8.);
    prime=1;
    do pos=1 to 8 while(prime);
      prime=.=sieve[input(substr(string,pos),8.)];
    end;
    if prime then output;
  end;
  stop;
  drop i j pos prime;
  format date yymmdd10.;
run;

This results in 409 similar date.  The next is in August of this year.  Here are the first 10.

Obs          date     string

  1    2019-05-23    20190523
  2    2019-08-23    20190823
  3    2030-03-17    20300317
  4    2036-03-17    20360317
  5    2040-03-07    20400307
  6    2040-08-23    20400823
  7    2048-01-07    20480107
  8    2060-03-17    20600317
  9    2066-06-17    20660617
 10    2070-01-03    20700103

Note there is no need to add index 0 to the sieve since the 10th, 20th and 30th day of the month will fail at the 2 digit check as being not prime so index of 0 is never attempted.

I counted 1 as NOT prime.  If you count 1 as prime then you get an additional 185 dates, first one being the first day of year 2060.


问:
how to set custom client id in react-ga
i'm using react-ga in my app,every thing is ok but i want to change Client id of each device.this is how i initialize react-ga.

```<code>ReactGA.initialize('UA-11xxxxxx-x', {
    debug: true,
    titleCase: false,
    'cookieDomain': 'auto',
    gaOptions: {
        name: 'DyuserName',
        userId: 'DyuserId'
    }
});
</code>```

normally in js we do like this

how can i change client id in react-ga

答:
You also need to set the userId to DyuserId like below:

ReactGA.ga("set", "userId", "" + DyuserId);

Title: how to set custom client id in react-ga

Body:
i'm using react-ga in my app,every thing is ok but i want to change Client id of each device.this is how i initialize react-ga.

ReactGA.initialize('UA-11xxxxxx-x', {
    debug: true,
    titleCase: false,
    'cookieDomain': 'auto',
    gaOptions: {
        name: 'DyuserName',
        userId: 'DyuserId'
    }
});

normally in js we do like this

how can i change client id in react-ga


问:
How do I use LWJGL 2 in Intellij instead of LWJGL 3?
I'm making a Minecraft mod in Itellij that relies on org.lwjgl.input code. That library was removed from LWJGL 3, so I have to use LWJGL 2 instead. I added the correct LWJGL 2 jar files to my dependencies and libraries and no errors show in my code. However, when I compile, I get this error:

error: package org.lwjgl.input does not exist

import org.lwjgl.input.Keyboard;

I already tried rebuilding, cleaning, deleting the .idea folder, invalidating the cache, and deleting all of the LWJGL 3 libraries. Am I missing a step?

答: LWJGL3 is a major upgrade over (the now deprecated and unsupported) LWJGL2. Several higher level APIs such as the org.lwjgl.input package have been removed in favor of low-level bindings to native APIs that can be used by applications. Using LWJGL3 and LWJGL2 on the same classpath is not a proper solution to retrieve old behavior. (Since the input APIs are fairly tightly integrated into the windowing code and LWJGL2 and LWJGL3 are not designed to be used together, it is unlikely to work at all.) Instead, I highly recommend to update your mod to use an input API exposed either by Minecraft itself or by the modding framework you are using.


问:
Python load csv to postgres table columns, strict format
I have available this table in my postgres database.

```<code>+------------+------------+----------------+----------+-------------------------+
|  recvtime  | entitytype |    attrname    | attrtype |        attrvalue        |
+------------+------------+----------------+----------+-------------------------+
| 2019-05-27 | Noise      | measurand      | Number   | 51.7                    |
| 2019-05-27 | Noise      | sonometerClass | Text     | 1                       |
| 2019-05-27 | Noise      | name           | Text     | City Centre             |
| 2019-05-27 | Noise      | longitude      | Number   | -8.65915                |
| 2019-05-27 | Noise      | latitude       | Number   | 41.1591                 |
| 2019-05-27 | Noise      | dateObserved   | DateTime | 2016-05-24T18:38:15.00Z |
+------------+------------+----------------+----------+-------------------------+
</code>```

And then wish to read content of this csv file:

```<code>measurand,sonometerClass,name,longitude,latitude,dateObserved
90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z
59.3,0,City Campus,-8.594866,41.178031,2014-08-12T16:10:10.00Z
64.5,1,ABC Beach,-8.607085,41.15001,2015-10-11T16:10:10.00Z
</code>```

The goal is to read data from the file in a way that the attrname column always mainatains the file headers, whereas for each line, data is loaded to the attrvalue column So that:

For line1:

```<code>90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z
</code>```

I get the following scenario:

```<code>measurand = 90.4
sonometerClass = 1
name = Hospital de S. Joao
longitude = -8.603257
latitude = 41.183778
dateObserved = 2014-07-12T6:18:15.00Z
</code>```

Similarly, for line 2:

```<code>59.3,0,City Campus,-8.594866,41.178031,2014-08-12T16:10:10.00Z
</code>```

I get the following:

```<code>measurand = 59.3
sonometerClass = 0
name = Campus
longitude = -8.594866
latitude = 41.178031
dateObserved = 2014-07-12T6:18:15.00Z
</code>```

All other columns recvtime, entitytype, and attrtype remains as they are(repeated).

Python script:

```<code>import psycopg2
import sys

try:
    conn = psycopg2.connect(host="localhost", dbname="postgres", \
      user="postgres", password="password")
    print('Connecting to the Database...')
    cur = conn.cursor()
    with open('noise2.csv', 'r') as f:
        next(f)
        cur.copy_from(f, 'urbansense.basic_004_noise', sep=',')
    conn.commit()

except Exception as e:
    print('Error: {}'.format(str(e)))
    sys.exit(1)
</code>```

Error:

```<code>$python3 readcsv.py
Connecting to the Database...
Error: invalid input syntax for integer: "63.4"
CONTEXT:  COPY basic_004_noise, line 1, column recvtimets: "63.4"
</code>```

How do I achieve my goal please?

答:
```<code>import csv
csvfile = "your/path/to/csv/file.csv"
with open(csvfile) as cf:
  reader = csv.DictReader(cf, delimiter=',',quotechar='"')
  for row in reader:
     measurand = float(row["measurand"]) # float
     sonometerClass = int(row["sonometerClass"])  # int
     name = row["name"]  # str
     longitude = float(row["longitude"])  # float
     latitude = float(row["latitude"])  # float
     dateObserved = row["dateObserved"]  # str

     # your code for postgres database here

</code>```

Body:
I have available this table in my postgres database.

+------------+------------+----------------+----------+-------------------------+
|  recvtime  | entitytype |    attrname    | attrtype |        attrvalue        |
+------------+------------+----------------+----------+-------------------------+
| 2019-05-27 | Noise      | measurand      | Number   | 51.7                    |
| 2019-05-27 | Noise      | sonometerClass | Text     | 1                       |
| 2019-05-27 | Noise      | name           | Text     | City Centre             |
| 2019-05-27 | Noise      | longitude      | Number   | -8.65915                |
| 2019-05-27 | Noise      | latitude       | Number   | 41.1591                 |
| 2019-05-27 | Noise      | dateObserved   | DateTime | 2016-05-24T18:38:15.00Z |
+------------+------------+----------------+----------+-------------------------+

And then wish to read content of this csv file:

measurand,sonometerClass,name,longitude,latitude,dateObserved
90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z
59.3,0,City Campus,-8.594866,41.178031,2014-08-12T16:10:10.00Z
64.5,1,ABC Beach,-8.607085,41.15001,2015-10-11T16:10:10.00Z

The goal is to read data from the file in a way that the attrname column always mainatains the file headers, whereas for each line, data is loaded to the attrvalue column So that:

For line1:

90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z

I get the following scenario:

measurand = 90.4
sonometerClass = 1
name = Hospital de S. Joao
longitude = -8.603257
latitude = 41.183778
dateObserved = 2014-07-12T6:18:15.00Z

Similarly, for line 2:

59.3,0,City Campus,-8.594866,41.178031,2014-08-12T16:10:10.00Z

I get the following:

measurand = 59.3
sonometerClass = 0
name = Campus
longitude = -8.594866
latitude = 41.178031
dateObserved = 2014-07-12T6:18:15.00Z

All other columns recvtime, entitytype, and attrtype remains as they are(repeated).

Python script:

import psycopg2
import sys

try:
    conn = psycopg2.connect(host="localhost", dbname="postgres", \
      user="postgres", password="password")
    print('Connecting to the Database...')
    cur = conn.cursor()
    with open('noise2.csv', 'r') as f:
        next(f)
        cur.copy_from(f, 'urbansense.basic_004_noise', sep=',')
    conn.commit()

except Exception as e:
    print('Error: {}'.format(str(e)))
    sys.exit(1)

Error:

$python3 readcsv.py
Connecting to the Database...
Error: invalid input syntax for integer: "63.4"
CONTEXT:  COPY basic_004_noise, line 1, column recvtimets: "63.4"

How do I achieve my goal please?


问:
Get Times Listed for a Restaurant on a Page
How can I get the times from the following elements? I am using Selenium Webdriver and coding in C#. Both elements have the same class name?

[![From Inspect][1]][1]

On this page,
https://www.yelp.com/biz/teds-montana-grill-aurora-aurora?osq=Teds+Montana+Grill

I need to gather the times displayed next to 'Today'
[![Today][2]][2]

to perform the following.
``

driver.FindElement(By.ClassName("nowrap"))...

This does not have getText as a method?

```<code>

  [1]: https://i.stack.imgur.com/tHwT2.png
  [2]: https://i.stack.imgur.com/EQtxZ.png

</code>```

答:
This is of course very brittle to any changes yelp makes to their HTML but you can just execute javascript:

```<code>document.getElementsByClassName("biz-hours")[0].getElementsByClassName("u-space-r-half")[0].innerText
</code>```

Example js execute with the C# driver Execute JavaScript using Selenium WebDriver in C# .

Body:
How can I get the times from the following elements? I am using Selenium Webdriver and coding in C#. Both elements have the same class name?

[![From Inspect][1]][1]

On this page,
https://www.yelp.com/biz/teds-montana-grill-aurora-aurora?osq=Teds+Montana+Grill

I need to gather the times displayed next to 'Today'
[![Today][2]][2]

to perform the following.
``

driver.FindElement(By.ClassName("nowrap"))...

This does not have getText as a method?

  [1]: https://i.stack.imgur.com/tHwT2.png
  [2]: https://i.stack.imgur.com/EQtxZ.png

Body:
This is of course very brittle to any changes yelp makes to their HTML but you can just execute javascript:

document.getElementsByClassName("biz-hours")[0].getElementsByClassName("u-space-r-half")[0].innerText

Example js execute with the C# driver Execute JavaScript using Selenium WebDriver in C# .


问:
How to convert XML to JSON with react
I have an API that provides me XML data, and i want to convert that XML data from the API into JSON. Can anyone help me wiht that problem?

I'm using Expo to creat a app. I tried to use nodemoduls, but when i tried that I alwas get an error "It failed because React Native does not include the Node standard library" The code belwo dosen't work

```<code>import { View, Text, ActivityIndicator } from 'react-native'
import { fetch } from "fetch";
const furl = 'https://skimap.org/Regions/view/346.xml';
const xmlToJson = require('xml-to-json-stream');
const parser = xmlToJson({attributeMode: true});

export default class RegionList extends PureComponent {

    state = { regions: [] };
    async componentWillMount() {
        fetch(furl).then(response => parser.xmlToJson(response, (err,json)=>{
            if(err){
                console.log(err);
            }
        }))
        .then( (response) => this.setState({regions: response}));

    }
</code>```

答:
Try this:</p>
```<code>import {Xml2Json} from 'react-native-xml-to-json';

fetch(furl).then(response =>
    Xml2Json.toJson(response, data => {
        console.log("Data = ", data);
    }).then( (response) => this.setState({regions: data})
);
</code>```

Title: How to convert XML to JSON with react

Body:
I have an API that provides me XML data, and i want to convert that XML data from the API into JSON. Can anyone help me wiht that problem?

I'm using Expo to creat a app. I tried to use nodemoduls, but when i tried that I alwas get an error "It failed because React Native does not include the Node standard library" The code belwo dosen't work

import { View, Text, ActivityIndicator } from 'react-native'
import { fetch } from "fetch";
const furl = 'https://skimap.org/Regions/view/346.xml';
const xmlToJson = require('xml-to-json-stream');
const parser = xmlToJson({attributeMode: true});

export default class RegionList extends PureComponent {

    state = { regions: [] };
    async componentWillMount() {
        fetch(furl).then(response => parser.xmlToJson(response, (err,json)=>{
            if(err){
                console.log(err);
            }
        }))
        .then( (response) => this.setState({regions: response}));

    }

Body:
Try this:

import {Xml2Json} from 'react-native-xml-to-json';

fetch(furl).then(response =>
    Xml2Json.toJson(response, data => {
        console.log("Data = ", data);
    }).then( (response) => this.setState({regions: data})
);


问:
Azure Functions (C#): get time zone ids (NodaTime)
I have an Azure Function that is time triggered. The Azure Function starts at every occasion when it is somewhere 00:00 am (local time). What I would like to achieve is to find the time zone strings (e.g. Europe/London) for the time zones where it is currently 00:00 am when the Azure Function is running.

I.e., I provide an UTC value and it provides me all time zone ids where it is currently 00:00 am local time.

How can I achieve that using NodaTime?

答:
My first approach (prototype) looks as follows:

```<code>using System;
using System.Collections.Generic;
using NodaTime;

namespace TimeZones
{
    class Program
    {
        static void Main(string[] args)
        {
            Instant utcDateTime = Instant.FromDateTimeUtc(DateTime.UtcNow);
            Console.WriteLine(utcDateTime);
            List<string> zoneIds = GetTimeZonesWithCondition(utcDateTime, 0, 0);

            Console.ReadLine();
        }

        static List<string> GetTimeZonesWithCondition(Instant utcDateTime, int hourComparison, int minuteComparison)
        {
            List<string> zoneIdsCheck = new List<string>();
            IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;

            foreach (var id in timeZoneProvider.Ids)
            {
                var zone = timeZoneProvider[id];
                var zoneDateTime = utcDateTime.InZone(zone);

                int hourZone = zoneDateTime.Hour;
                int minuteZone = zoneDateTime.Minute;

                if (hourZone == hourComparison && minuteZone == minuteComparison)
                {
                    zoneIdsCheck.Add(zone.ToString());
                    Console.WriteLine($"{zone} / {zoneDateTime}");
                }
            }

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

If someone has a better solution please let me know.

Body:
My first approach (prototype) looks as follows:

using System;
using System.Collections.Generic;
using NodaTime;

namespace TimeZones
{
    class Program
    {
        static void Main(string[] args)
        {
            Instant utcDateTime = Instant.FromDateTimeUtc(DateTime.UtcNow);
            Console.WriteLine(utcDateTime);
            List<string> zoneIds = GetTimeZonesWithCondition(utcDateTime, 0, 0);

            Console.ReadLine();
        }

        static List<string> GetTimeZonesWithCondition(Instant utcDateTime, int hourComparison, int minuteComparison)
        {
            List<string> zoneIdsCheck = new List<string>();
            IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;

            foreach (var id in timeZoneProvider.Ids)
            {
                var zone = timeZoneProvider[id];
                var zoneDateTime = utcDateTime.InZone(zone);

                int hourZone = zoneDateTime.Hour;
                int minuteZone = zoneDateTime.Minute;

                if (hourZone == hourComparison && minuteZone == minuteComparison)
                {
                    zoneIdsCheck.Add(zone.ToString());
                    Console.WriteLine($"{zone} / {zoneDateTime}");
                }
            }

            return zoneIdsCheck;
        }
    }
}

If someone has a better solution please let me know.


问:
.Count not supported when doing a find on child collection complex object field value
I have a find query that when from this

```<code>!CurrentUser.SentMatchRequest.Contains(OtherProfile.userId)
</code>```

To this

```<code>CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).Count==0
</code>```

However, the query fails by stating .count is not supported.
Before the collection used to be a simple string array and now it changed to a complex object

```<code>public class info
{
 public string Id {get;set;}
 public DateTime TimeStamp {get;set;}
}
</code>```

答: You can use (Count with () will iterate one more time over your collection) .Count() == 0; or Count() == 0;  instead but is realy better to use .Any(x => x.Id.Equals(OtherProfile.userId));</p>

Body:
I have a find query that when from this

!CurrentUser.SentMatchRequest.Contains(OtherProfile.userId)

To this

CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).Count==0

However, the query fails by stating .count is not supported.
Before the collection used to be a simple string array and now it changed to a complex object

public class info
{
 public string Id {get;set;}
 public DateTime TimeStamp {get;set;}
}


问:
font-awesome icon in display of combobox extjs 6
I tried several ways to set an icon, in the displayfield, when an item of the combo is selected with not luck, this is the fiddle for anyone to want try to help with this. very much appreciated any light.

fiddle example

答:
Perhaps my solution is similar to a hack, but it works in 6.7.0 and is a bit simpler.
Tested in Chrome. Theme - Material. For another theme will require minor improvements.

Sencha Fiddle live example

```<code>Ext.application({
name: 'Fiddle',

launch: function () {

    var store = new Ext.data.Store({
        fields: [{
            name: 'class',
            convert: function (value, model) {
                if (value && model) {
                    var name = value
                        .replace(/(-o-)|(-o$)/g, '-outlined-')
                        .replace(/-/g, ' ')
                        .slice(3)
                        .trim();
                    model.data.name = name.charAt(0).toUpperCase() + name.slice(1);
                    return value;
                }
            }
        }, {
            name: 'name'
        }],
        data: [{
            class: 'fa-address-book'
        }, {
            class: 'fa-address-book-o'
        }, {
            class: 'fa-address-card'
        }]
    });

    var form = Ext.create('Ext.form.Panel', {
        fullscreen: true,
        referenceHolder: true,
        items: [{
            xtype: 'combobox',
            id: 'iconcombo',
            queryMode: 'local',
            editable: false,
            width: 300,
            valueField: 'class',
            displayField: 'name',
            store: store,
            itemTpl: '<div><i class="fa {class}"></i> {name}</div>',
            afterRender: () => {
                var component = Ext.getCmp('iconcombo');
                var element = document.createElement('div');
                element.className = 'x-input-el';
                element.addEventListener('click', () => component.expand());
                component.inputElement.parent().dom.prepend(element);
                component.inputElement.hide();
                component.addListener(
                    'change', (me, newValue, oldValue) => {
                        component.updateInputValue.call(me, newValue, oldValue);
                    },
                    component
                );
                var method = component.updateInputValue;
                component.updateInputValue = (value, oldValue) => {
                    method.call(component, value, oldValue);
                    var selection = component.getSelection();
                    if (selection) {
                        element.innerHTML =
                            '<div><i class="fa ' + selection.get('class') + '"></i> ' + selection.get('name') + '</div>';
                    }
                };
            }
        }, {
            xtype: 'button',
            text: 'getValue',
            margin: '30 0 0 0',
            handler: function (component) {
                var combo = Ext.getCmp('iconcombo');
                alert(combo.getValue());
            }
        }]
    });
    form.show();

}
</code>```

});

Body:
Perhaps my solution is similar to a hack, but it works in 6.7.0 and is a bit simpler.
Tested in Chrome. Theme - Material. For another theme will require minor improvements.

Sencha Fiddle live example

Ext.application({
name: 'Fiddle',

launch: function () {

    var store = new Ext.data.Store({
        fields: [{
            name: 'class',
            convert: function (value, model) {
                if (value && model) {
                    var name = value
                        .replace(/(-o-)|(-o$)/g, '-outlined-')
                        .replace(/-/g, ' ')
                        .slice(3)
                        .trim();
                    model.data.name = name.charAt(0).toUpperCase() + name.slice(1);
                    return value;
                }
            }
        }, {
            name: 'name'
        }],
        data: [{
            class: 'fa-address-book'
        }, {
            class: 'fa-address-book-o'
        }, {
            class: 'fa-address-card'
        }]
    });

    var form = Ext.create('Ext.form.Panel', {
        fullscreen: true,
        referenceHolder: true,
        items: [{
            xtype: 'combobox',
            id: 'iconcombo',
            queryMode: 'local',
            editable: false,
            width: 300,
            valueField: 'class',
            displayField: 'name',
            store: store,
            itemTpl: '<div><i class="fa {class}"></i> {name}</div>',
            afterRender: () => {
                var component = Ext.getCmp('iconcombo');
                var element = document.createElement('div');
                element.className = 'x-input-el';
                element.addEventListener('click', () => component.expand());
                component.inputElement.parent().dom.prepend(element);
                component.inputElement.hide();
                component.addListener(
                    'change', (me, newValue, oldValue) => {
                        component.updateInputValue.call(me, newValue, oldValue);
                    },
                    component
                );
                var method = component.updateInputValue;
                component.updateInputValue = (value, oldValue) => {
                    method.call(component, value, oldValue);
                    var selection = component.getSelection();
                    if (selection) {
                        element.innerHTML =
                            '<div><i class="fa ' + selection.get('class') + '"></i> ' + selection.get('name') + '</div>';
                    }
                };
            }
        }, {
            xtype: 'button',
            text: 'getValue',
            margin: '30 0 0 0',
            handler: function (component) {
                var combo = Ext.getCmp('iconcombo');
                alert(combo.getValue());
            }
        }]
    });
    form.show();

}

});


问:
MySQL root password reset -bash: syntax error near unexpected token `('
I am just starting to learn MySQL, im running 5.7.20 on Mac os 10.12 when i tried to use the following command in Terminal to reset password

```<code>mysql> UPDATE mysql.user SET authentication_string = PASSWORD('password')
</code>```

i am keep getting

-bash: syntax error near unexpected token `('

Can anyone assist me with that error message? i have tried many different website no one seems to have an answer to that.

```<code>Last login: Tue May 28 02:07:04 on ttys001
192-168-1-5:~ Betty$ mysql> UPDATE mysql.user SET authentication_string = PASSWORD('password')
-bash: syntax error near unexpected token `('
</code>```

答:
If you want to run mysql command from within bash you may want to use -e option as in:

```<code>mysql -uusername -ppassword -e "UPDATE mysql.user SET authentication_string = PASSWORD('password')"
</code>```

Body:
I am just starting to learn MySQL, im running 5.7.20 on Mac os 10.12 when i tried to use the following command in Terminal to reset password

mysql> UPDATE mysql.user SET authentication_string = PASSWORD('password')

i am keep getting

-bash: syntax error near unexpected token `('

Can anyone assist me with that error message? i have tried many different website no one seems to have an answer to that.

Last login: Tue May 28 02:07:04 on ttys001
192-168-1-5:~ Betty$ mysql> UPDATE mysql.user SET authentication_string = PASSWORD('password')
-bash: syntax error near unexpected token `('

Body:
If you want to run mysql command from within bash you may want to use -e option as in:

mysql -uusername -ppassword -e "UPDATE mysql.user SET authentication_string = PASSWORD('password')"


问:
How to get a Firestore document size?
From Firestore docs, we get that the maximum size for a Firestore document is:

Maximum size for a document 1 MiB (1,048,576 bytes)

QUESTION

How can I know the current size of a single doc, to check if I'm approaching
that 1mb limit?

Example:

```<code>var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
        // IS THERE A PROPERTY THAT CAN DISPLAY THE DOCUMENT FILE SIZE?
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});
</code>```

答:
I was looking in the Firebase reference expecting the metadata would have an attribute, but it doesn't. You can check it here.

So my next approach would be to figure the weight of the object as an approximation. The sizeOf library seems to have a reasonable API for it.

So it would be something like:

```<code>sizeof.sizeof(doc.data());
</code>```

I wouldn't use the document snapshot, because it contains metadata, like if there are pending saves. On another hand overestimating could be better in some cases.

[UPDATE] Thanks to Doug Stevenson for the wonderful insight

So I was curious how much the difference would actually be, so with my clunky js I made a dirty comparison, you can see the demo here

Considering this object:

```<code> {
  "boolean": true,
  "number": 1,
  "text": "example"
  }
</code>```

And discounting the id this is the result:

```<code>| Method  | Bytes |
|---------|-------|
| FireDoc | 37    |
| sizeOf  | 64    |
</code>```

So sizeOf library could be a good predictor if we want to overestimate (assuming calculations are fine and will behave more or less equal for more complex entities). But as explained in the comment, it is a rough estimation.

Title: How to get a Firestore document size?

Body:
From Firestore docs, we get that the maximum size for a Firestore document is:

Maximum size for a document 1 MiB (1,048,576 bytes)

QUESTION

How can I know the current size of a single doc, to check if I'm approaching
that 1mb limit?

Example:

var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
        // IS THERE A PROPERTY THAT CAN DISPLAY THE DOCUMENT FILE SIZE?
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

Body:
I was looking in the Firebase reference expecting the metadata would have an attribute, but it doesn't. You can check it here.

So my next approach would be to figure the weight of the object as an approximation. The sizeOf library seems to have a reasonable API for it.

So it would be something like:

sizeof.sizeof(doc.data());

I wouldn't use the document snapshot, because it contains metadata, like if there are pending saves. On another hand overestimating could be better in some cases.

[UPDATE] Thanks to Doug Stevenson for the wonderful insight

So I was curious how much the difference would actually be, so with my clunky js I made a dirty comparison, you can see the demo here

Considering this object:

 {
  "boolean": true,
  "number": 1,
  "text": "example"
  }

And discounting the id this is the result:

| Method  | Bytes |
|---------|-------|
| FireDoc | 37    |
| sizeOf  | 64    |

So sizeOf library could be a good predictor if we want to overestimate (assuming calculations are fine and will behave more or less equal for more complex entities). But as explained in the comment, it is a rough estimation.


问:
C#: "not responding" window when program is doing some background processing
In my C# project I have a form that is displayed which shows a progress bar.

Some processing is then done which involves communication over the internet.

While this processing is occurring the form says "Not Responding" when run in Win 7, in XP the form just goes white.

Either way, it is not acceptable.

Do I need to use threads to solve this problem?

What are some of the basics of threads that I would need to use in this scenario?

答:
From your description I'll assume that all your work is currently being done on a single thread, the main thread which is also used for your GUI.

The progress bar can only update when that main thread gets a chance to check its state and apply any expected changes.

Therefore it is important that your processing work does not occupy the main thread for extended periods of time.

There are two main approaches to handling this:

Stepping the processing activity.
Break down the processing step into a number of serial tasks - each short in nature.
Progressively call each of these serial tasks in the OnIdle event on your main thread.

Using a background thread.
See other answers giving more detail on how this would work.

The stepping approach can be useful if you want to avoid the sublties of thread synchronisation.  The threading approach is probably better but only essential if it is impossible to guarantee serial short steps.


问:
Set pipe as the delimiter for Select2
I have one multiple select dropdown, and I want to set pipe (|) as the delimiter.

For example, when a user selects multiple options (like Option1, Option2 and Option3) then it should separate (delimit) the values like this:

Option1|Option2|Option3

Below is my code:

```<code>$("#granttype").select2({ allowClear: true, tags: true, tokenSeparators: ['|'] });
</code>```

I wrote this in the $document.ready() function.

答:
For who still looking this,

This is script that working for me :

```<code>$(element).select2({
  tags: [],
  separator: "|"
});
</code>```

The "tags: []," must be included, otherwise it give errors

Hope it help

Title: Set pipe as the delimiter for Select2

Body:
I have one multiple select dropdown, and I want to set pipe (|) as the delimiter.

For example, when a user selects multiple options (like Option1, Option2 and Option3) then it should separate (delimit) the values like this:

Option1|Option2|Option3

Below is my code:

$("#granttype").select2({ allowClear: true, tags: true, tokenSeparators: ['|'] });

I wrote this in the $document.ready() function.

Body:
For who still looking this,

This is script that working for me :

$(element).select2({
  tags: [],
  separator: "|"
});

The "tags: []," must be included, otherwise it give errors

Hope it help


问:
Mysql connection refuse in docker
So i am creating a new symfony 4 project but i cant get mysql to connect to my docker mysql.   what part am i doing wrong?

Ive tried change mysql versions, composing it down and updating different mysql root and password and is not connecting.

here is my docker-compose.yml for mysql.

```<code>mysql:
        image: mysql:8
        container_name: sf4_mysql
        volumes:
            - .docker/data/db:/var/lib/mysql
        command:
            - "--default-authentication-plugin=mysql_native_password"
            - "--lower_case_table_names=1"
        environment:
            MYSQL_ROOT_PASSWORD: root
            MYSQL_DATABASE: sf4
            MYSQL_USER: sf4
            MYSQL_PASSWORD: sf4
</code>```

Here is mysql Url in my .env
    DATABASE_URL=mysql://sf4:sf4@sf4_mysql:3306/sf4

every-time i do ./bin/console doctrine:database:create, connection is refused.

just trying to create a database.

controller

```<code>class HospitalAdminController extends AbstractController
{
    /**
     * @Route("/admin/hospital/new")
     */
    public function new(EntityManagerInterface $em)
    {
        $hospital = new Hospital();
        $hospital->setName('Example Hospital')
            ->setPhone(8175831483)
            ->setAddress('123 Avenue');

        $em->persist($hospital);
        $em->flush();

        return new Response(sprintf(
            'Hiya! New Hospital id: #%d phone:%s address%s',
            $hospital->getId(),
            $hospital->getPhone(),
            $hospital->getAddress()

        ));

}
</code>```

答:
You need to expose mysql port. default is 3306.
see port publishing

and more examples specific to mysql-8 on docker

For checking if mysql is running it is good to run inside terminal its client so you minimize potential error source to the database itself not including potential errors in php.

Title: Mysql connection refuse in docker

Body:
So i am creating a new symfony 4 project but i cant get mysql to connect to my docker mysql.   what part am i doing wrong?

Ive tried change mysql versions, composing it down and updating different mysql root and password and is not connecting.

here is my docker-compose.yml for mysql.

mysql:
        image: mysql:8
        container_name: sf4_mysql
        volumes:
            - .docker/data/db:/var/lib/mysql
        command:
            - "--default-authentication-plugin=mysql_native_password"
            - "--lower_case_table_names=1"
        environment:
            MYSQL_ROOT_PASSWORD: root
            MYSQL_DATABASE: sf4
            MYSQL_USER: sf4
            MYSQL_PASSWORD: sf4

Here is mysql Url in my .env
    DATABASE_URL=mysql://sf4:sf4@sf4_mysql:3306/sf4

every-time i do ./bin/console doctrine:database:create, connection is refused.

just trying to create a database.

controller

class HospitalAdminController extends AbstractController
{
    /**
     * @Route("/admin/hospital/new")
     */
    public function new(EntityManagerInterface $em)
    {
        $hospital = new Hospital();
        $hospital->setName('Example Hospital')
            ->setPhone(8175831483)
            ->setAddress('123 Avenue');

        $em->persist($hospital);
        $em->flush();

        return new Response(sprintf(
            'Hiya! New Hospital id: #%d phone:%s address%s',
            $hospital->getId(),
            $hospital->getPhone(),
            $hospital->getAddress()

        ));

}


问:
Find Longest Prefix That is Also a Suffix in String - Javascript
Link to codewars challenge

I need to return the length of the longest prefix that is also a suffix of a string in Javascript.

As far as I understand, the prefixes in "abcd" are:

['a', 'ab', 'abc']

And the suffixes in "abcd" are:

[ 'bcd', 'cd', 'd' ]

So the length of the longest prefix that is also a suffix in "abcd" in this case is 0, because there are no prefixes that are also suffixes in "abcd".

So far I've been able to figure out how to get the suffixes into an array for comparison, but not the prefixes.

```<code>function returnLongestPrefixAndSuffix(string) {

  let prefixes = [];
  let suffixes = [];

  for (let i = 0; i < string.length -1; i++) {
    prefixes.push(string.slice(i));
  }

  for (let i = 1; i < string.length; i++) {
    suffixes.push(string.slice(i));
  }

  return prefixes + " " + suffixes;

}

console.log(returnLongestPrefixAndSuffix("abcd"));
</code>```

I'm not grasping the concept of how to start at the beginning of a string and add a larger element to the array each time by one character, excluding the element that would include the last one.

Please follow my current logic if possible.

EDIT: My code now looks like this:

```<code>function solve(string) {

    let prefixes = [];
    let suffixes = [];
    let includedList = [];

    for (let i = 1; i < string.length; i++) {
      prefixes.push(string.slice(0, i));
    }

    for (let i = 1; i < string.length; i++) {
      suffixes.push(string.slice(-i));
    }

    console.log(prefixes);
    console.log(suffixes);

    for (let i = 0; i < prefixes.length; i++) {
        let element = prefixes[i];
        if (suffixes.includes(element) === true) {
            includedList.push(element);
        }
    }

    console.log(includedList);
    if (includedList.length === 0) {
        return 0;
    }
    else {
        let overlap = prefixes.filter(value => suffixes.includes(value));
        console.log(overlap);
        let longest = includedList.sort(function (a, b) { return b.length - a.length; })[0];
        return longest.length;
    }
}

console.log(solve("abcdabc"));
</code>```

And this is passing 10049 test but failing 163 tests on codewars. I still do not know what to do with the overlap variable or how to exclude overlaps from the includedList array.

答:
```<code>function solve(string) {

    for (let i = Math.floor(string.length / 2); i > 0; i--) {

        let prefix = string.slice(0, i);
        let suffix = string.slice(-i);

        if (prefix == suffix) {
            return i;
        }
    }
    return 0;
}

console.log(solve("abcdabc"));
</code>```

To account for the overlap, initialize your for-loop like this:

let i = Math.floor(string.length / 2)

That will initialize the for-loop at the half-way point in your string, so that you can count down and compare whether or not the prefix == the suffix, starting with the longest.

You could return prefix.length, but that will be the same thing as i.

Also, be sure to return 0 outside of the for-loop. Because if you try:

```<code>if (prefix != suffix) {
    return 0;
   }
</code>```

inside of the for-loop, it will stop counting right there.

Body:
Link to codewars challenge

I need to return the length of the longest prefix that is also a suffix of a string in Javascript.

As far as I understand, the prefixes in "abcd" are:

['a', 'ab', 'abc']

And the suffixes in "abcd" are:

[ 'bcd', 'cd', 'd' ]

So the length of the longest prefix that is also a suffix in "abcd" in this case is 0, because there are no prefixes that are also suffixes in "abcd".

So far I've been able to figure out how to get the suffixes into an array for comparison, but not the prefixes.

function returnLongestPrefixAndSuffix(string) {

  let prefixes = [];
  let suffixes = [];

  for (let i = 0; i < string.length -1; i++) {
    prefixes.push(string.slice(i));
  }

  for (let i = 1; i < string.length; i++) {
    suffixes.push(string.slice(i));
  }

  return prefixes + " " + suffixes;

}

console.log(returnLongestPrefixAndSuffix("abcd"));

I'm not grasping the concept of how to start at the beginning of a string and add a larger element to the array each time by one character, excluding the element that would include the last one.

Please follow my current logic if possible.

EDIT: My code now looks like this:

function solve(string) {

    let prefixes = [];
    let suffixes = [];
    let includedList = [];

    for (let i = 1; i < string.length; i++) {
      prefixes.push(string.slice(0, i));
    }

    for (let i = 1; i < string.length; i++) {
      suffixes.push(string.slice(-i));
    }

    console.log(prefixes);
    console.log(suffixes);

    for (let i = 0; i < prefixes.length; i++) {
        let element = prefixes[i];
        if (suffixes.includes(element) === true) {
            includedList.push(element);
        }
    }

    console.log(includedList);
    if (includedList.length === 0) {
        return 0;
    }
    else {
        let overlap = prefixes.filter(value => suffixes.includes(value));
        console.log(overlap);
        let longest = includedList.sort(function (a, b) { return b.length - a.length; })[0];
        return longest.length;
    }
}

console.log(solve("abcdabc"));

And this is passing 10049 test but failing 163 tests on codewars. I still do not know what to do with the overlap variable or how to exclude overlaps from the includedList array.

Body:
function solve(string) {

    for (let i = Math.floor(string.length / 2); i > 0; i--) {

        let prefix = string.slice(0, i);
        let suffix = string.slice(-i);

        if (prefix == suffix) {
            return i;
        }
    }
    return 0;
}

console.log(solve("abcdabc"));

To account for the overlap, initialize your for-loop like this:

let i = Math.floor(string.length / 2)

That will initialize the for-loop at the half-way point in your string, so that you can count down and compare whether or not the prefix == the suffix, starting with the longest.

You could return prefix.length, but that will be the same thing as i.

Also, be sure to return 0 outside of the for-loop. Because if you try:

if (prefix != suffix) {
    return 0;
   }

inside of the for-loop, it will stop counting right there.


问:
How do i prevent mouse and touch events from trigger for DisplayObjects below a backdrop
I have several display objects in createjs and event using easeljs i want to prevent from mouse and touch event passing through them.

i want like a easy one liner like .mouseEnabled or .mouseChildren is there something will will prevent any other interaction for the objcts below this. i can try adding all events to a backdrop movieclip which tint background color and prevent default and stopPropogation will that help?

so how to i prevent from any type of interaction taking place in canvas just by placing a displayobject that's like wall which will not allow the other displayobjects from getting click, mouseover or touch events.

答:
You can add obj.mouseEnabled= obj.mouseChildren = false; to any you don't want to receive events.

If you just want to block events with a child on top, simply add a mouse handler to it.

```<code>cover.on("click", function(){});
</code>```

You don't need stopPropagation, since that will only prevent events from bubbling in the current hierarchy (ie, surfacing an event to its direct parent). Events do not "pass through" objects that have mouse handlers on them.

Hope that helps!

Body:
You can add obj.mouseEnabled= obj.mouseChildren = false; to any you don't want to receive events.

If you just want to block events with a child on top, simply add a mouse handler to it.

cover.on("click", function(){});

You don't need stopPropagation, since that will only prevent events from bubbling in the current hierarchy (ie, surfacing an event to its direct parent). Events do not "pass through" objects that have mouse handlers on them.

Hope that helps!


问:
Array not returning an answer in For loop
I have an array that takes in values from a single row of a spreadsheet (1 row, 185 columns). I then want to loop through the array, looking for a match between the values in the array, and values in a particular cell.

However, every time I run the code, it says it finds a match, but does not return a value to the cell.

The relevant lines of the code are:

```<code>
Dim qCountry()

Worksheets("Data").Activate

    qCountry = Range("A1:GC1").Value
</code>```

```<code>    For i = 1 To 185
          If Cells(aRow, bCol) <> vbNullString Then
              Exit For
          ElseIf InStr(1, Cells(aRow, 4), "*" & qCountry(i) & "*") = 1 Then
              Cells(aRow, bCol) = qCountry(i)
          End If
    Next i
</code>```

A screenshot of my array:

答:
Just define qCountry as a normal Variant variable, like this:

```<code>Dim qCountry as Variant
</code>```

This will get rid of one extra dimension, but you still have a multi-dimension array.

If you want to deal with an array of single dimension, you can use the Application.Transpose() Function:

```<code>qCountry = Application.Transpose(Range("A1:GC1").Value)
</code>```

But since you have data in a row, you need to do it twice:

```<code>qCountry = Application.Transpose(Application.Transpose(Range("A1:GC1").Value))
</code>```

At this point your code will work:

```<code>Dim qCountry
Worksheets("Data").Activate
qCountry = Application.Transpose(Application.Transpose(Range("A1:GC1").Value))

For i = 1 To 185
      If Cells(aRow, bCol) <> vbNullString Then
          Exit For
      ElseIf InStr(1, Cells(aRow, 4), "*" & qCountry(i) & "*") = 1 Then
          Cells(aRow, bCol) = qCountry(i)
      End If
Next i
</code>```

Hope this helps.

Body:
I have an array that takes in values from a single row of a spreadsheet (1 row, 185 columns). I then want to loop through the array, looking for a match between the values in the array, and values in a particular cell.

However, every time I run the code, it says it finds a match, but does not return a value to the cell.

The relevant lines of the code are:

Dim qCountry()

Worksheets("Data").Activate

    qCountry = Range("A1:GC1").Value

    For i = 1 To 185
          If Cells(aRow, bCol) <> vbNullString Then
              Exit For
          ElseIf InStr(1, Cells(aRow, 4), "*" & qCountry(i) & "*") = 1 Then
              Cells(aRow, bCol) = qCountry(i)
          End If
    Next i

A screenshot of my array:

Body:
Just define qCountry as a normal Variant variable, like this:

Dim qCountry as Variant

This will get rid of one extra dimension, but you still have a multi-dimension array.

If you want to deal with an array of single dimension, you can use the Application.Transpose() Function:

qCountry = Application.Transpose(Range("A1:GC1").Value)

But since you have data in a row, you need to do it twice:

qCountry = Application.Transpose(Application.Transpose(Range("A1:GC1").Value))

At this point your code will work:

Dim qCountry
Worksheets("Data").Activate
qCountry = Application.Transpose(Application.Transpose(Range("A1:GC1").Value))

For i = 1 To 185
      If Cells(aRow, bCol) <> vbNullString Then
          Exit For
      ElseIf InStr(1, Cells(aRow, 4), "*" & qCountry(i) & "*") = 1 Then
          Cells(aRow, bCol) = qCountry(i)
      End If
Next i

Hope this helps.


问:
Postgres memory calculation effective_cache_size
I am verifying some of the configuration in my production Postgres instance. Our DB server has 32 GB RAM. From pg_settings, I see that effective_cache_size is set to:

```<code>postgres=> select name, setting, unit from pg_settings where name like 'effective_cache_size';
         name         | setting | unit
----------------------+---------+------
 effective_cache_size | 7851762 | 8kB
(1 row)
</code>```

As per my understanding, this value accounts to 7851762 X 8 KB = 62.8 GB. If my calculation is right, we are basically telling the optimizer that we have 62 GB for this parameter whereas we have only 32 GB of physical RAM.

Please correct me if I am calculating this parameter wrong. I always get confused with calculating parameter allocations for units with 8 KB.

答:
7851762 times 8 kB is approximately 60 GB.

I would configure the setting to 30 GB if the machine is dedicated to the PostgreSQL database.

This parameter tells PostgreSQL how much memory there is available for caching its files. If the value is high, PostgreSQL will estimate nested loop joins with an index scan on the inner side cheaper, because it assumes that the index will probably be cached.

Body:
I am verifying some of the configuration in my production Postgres instance. Our DB server has 32 GB RAM. From pg_settings, I see that effective_cache_size is set to:

postgres=> select name, setting, unit from pg_settings where name like 'effective_cache_size';
         name         | setting | unit
----------------------+---------+------
 effective_cache_size | 7851762 | 8kB
(1 row)

As per my understanding, this value accounts to 7851762 X 8 KB = 62.8 GB. If my calculation is right, we are basically telling the optimizer that we have 62 GB for this parameter whereas we have only 32 GB of physical RAM.

Please correct me if I am calculating this parameter wrong. I always get confused with calculating parameter allocations for units with 8 KB.


问:
How can i execute one by one statement after delaying some time in iphone?
I have a problem in iPhone programing.

In my app i want to execute one by one statement after delaying some time.

Example:

```<code>Label1.text =@"2";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"3";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"8";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"6";
</code>```

答:
you can use something like this - </p>

```<code>[self performSelector:@selector(yourMethod:) withObject:someObjectInstance afterDelay:2.0];
</code>```

Body:
I have a problem in iPhone programing.

In my app i want to execute one by one statement after delaying some time.

Example:

Label1.text =@"2";

Then after delaying some time i want execute:

Label2.text =@"3";

Then after delaying some time i want execute:

Label2.text =@"8";

Then after delaying some time i want execute:

Label2.text =@"6";

Body:
you can use something like this -

[self performSelector:@selector(yourMethod:) withObject:someObjectInstance afterDelay:2.0];


问:
DataLoading event is never fired
I am trying to set a DashboardObjectDataSource to my dashboard and I would like to catch the DataLoading event to specify the datas depending on the dashboard selected. My problem is that DataLoading event is never fired.

I have tried subscribing to the event like this :

```<code>public DataSourceInMemoryStorage CreateDataSourceStorage()
    {
        DataSourceInMemoryStorage dataSourceStorage = new DataSourceInMemoryStorage();

        DashboardObjectDataSource data = new DashboardObjectDataSource();
        data.DataSource = typeof(Data);
        data.Name = "Object Data Source";
        dataSourceStorage.RegisterDataSource("dataSourceObject", data.SaveToXml());
}

public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddMvc()
            .AddDefaultDashboardController(configurator => {
                configurator.SetDashboardStorage(new DataBaseEditaleDashboardStorage(Configuration.GetConnectionString("DashboardStorageConnection")));
                configurator.SetDataSourceStorage(CreateDataSourceStorage());
                configurator.AllowExecutingCustomSql = true;
            });

        services.AddDevExpressControls(settings => settings.Resources = ResourcesType.ThirdParty | ResourcesType.DevExtreme);

        DashboardConfigurator.PassCredentials = false;

        DashboardConfigurator.Default.DataLoading += Default_DataLoading;
    }

private static void Default_DataLoading(object sender, DataLoadingWebEventArgs e)
    {
        if (e.DataSourceName == "Object Data Source")
        {
            e.Data = Data.GetData();
        }
    }

public class Data
{
    public static DataTable GetData()
    {
        DataTable dt = new DataTable();

        string query = "select TOP 1000 * from MyTable";

        SqlConnection conn = new SqlConnection("MyConnectionString");
        SqlCommand cmd = new SqlCommand(query, conn);
        conn.Open();

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        conn.Close();
        da.Dispose();

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

But I have never been able to enter in the Default_DataLoading method. I do not get any error, the dashboard is showing but without any datas.

答:
It appears that the DashboardConfigurator.Default instance is causing the issue. Instead, define the DataLoading event handler in the AddDefaultDashboardController method:

```<code>configurator.SetDataSourceStorage(CreateDataSourceStorage());
configurator.AllowExecutingCustomSql = true;
configurator.DataLoading += (s, e) => {
    if (e.DataSourceName == "Object Data Source")
    {
        e.Data = Data.GetData();
    }
};
</code>```

In addition, please check if your dashboard layout contains data source with the name specified in the DataLoading event handler ("Object Data Source"). If your dashboard does not have a data source, you will need to create one using the Create a New Data Source option in Web Designer.

Just in case: the sample Web Dashboard application created using the DevExpress Template Gallery (see Create an ASP.NET MVC Dashboard Application) includes the Object Data Source registration that fills dashboard items with data once you add a corresponding data source in design mode.

Title: DataLoading event is never fired

Body:
I am trying to set a DashboardObjectDataSource to my dashboard and I would like to catch the DataLoading event to specify the datas depending on the dashboard selected. My problem is that DataLoading event is never fired.

I have tried subscribing to the event like this :

public DataSourceInMemoryStorage CreateDataSourceStorage()
    {
        DataSourceInMemoryStorage dataSourceStorage = new DataSourceInMemoryStorage();

        DashboardObjectDataSource data = new DashboardObjectDataSource();
        data.DataSource = typeof(Data);
        data.Name = "Object Data Source";
        dataSourceStorage.RegisterDataSource("dataSourceObject", data.SaveToXml());
}

public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddMvc()
            .AddDefaultDashboardController(configurator => {
                configurator.SetDashboardStorage(new DataBaseEditaleDashboardStorage(Configuration.GetConnectionString("DashboardStorageConnection")));
                configurator.SetDataSourceStorage(CreateDataSourceStorage());
                configurator.AllowExecutingCustomSql = true;
            });

        services.AddDevExpressControls(settings => settings.Resources = ResourcesType.ThirdParty | ResourcesType.DevExtreme);

        DashboardConfigurator.PassCredentials = false;

        DashboardConfigurator.Default.DataLoading += Default_DataLoading;
    }

private static void Default_DataLoading(object sender, DataLoadingWebEventArgs e)
    {
        if (e.DataSourceName == "Object Data Source")
        {
            e.Data = Data.GetData();
        }
    }

public class Data
{
    public static DataTable GetData()
    {
        DataTable dt = new DataTable();

        string query = "select TOP 1000 * from MyTable";

        SqlConnection conn = new SqlConnection("MyConnectionString");
        SqlCommand cmd = new SqlCommand(query, conn);
        conn.Open();

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        conn.Close();
        da.Dispose();

        return dt;
    }
}

But I have never been able to enter in the Default_DataLoading method. I do not get any error, the dashboard is showing but without any datas.

Body:
It appears that the DashboardConfigurator.Default instance is causing the issue. Instead, define the DataLoading event handler in the AddDefaultDashboardController method:

configurator.SetDataSourceStorage(CreateDataSourceStorage());
configurator.AllowExecutingCustomSql = true;
configurator.DataLoading += (s, e) => {
    if (e.DataSourceName == "Object Data Source")
    {
        e.Data = Data.GetData();
    }
};

In addition, please check if your dashboard layout contains data source with the name specified in the DataLoading event handler ("Object Data Source"). If your dashboard does not have a data source, you will need to create one using the Create a New Data Source option in Web Designer.

Just in case: the sample Web Dashboard application created using the DevExpress Template Gallery (see Create an ASP.NET MVC Dashboard Application) includes the Object Data Source registration that fills dashboard items with data once you add a corresponding data source in design mode.