问:
how to select row from one of three tables based on fourth table that holds order of those entries from all three tables
so I have three tables with content and one that holds row order of those three tables

here are the tables

```<code>table content_order
id | content_type | content id
1 | content1 | 1
2 | content1 | 2
3 | content3 | 1
4 | content2 | 1

table content1
id | some_text
1 | aaaa
2 | bbb

table content2
id | some_text
1 | text yyyy

table content3
id | some_text
1 | text bbbb
</code>```

so how do I get this?

```<code>content_type | some_text | content_id
content1 | aaaa | 1 |
content2 | bbb | 2 |
content3 | yyyy | 1 |
content2 | bbbb | 1 |
</code>```

答:
Try this:</p>

```<code>SELECT content_type, some_text, id as content_id
FROM (
               SELECT 'content1' as content_type, content1.Id, content1.some_text
     UNION ALL SELECT 'content2', content2.Id, content2.some_text
     UNION ALL SELECT 'content3', content3.Id, content3.some_text) contents
JOIN content_order
  ON content_order.content_type = contents.content_type
 AND content_order.content_Id = contents.Id
ORDER BY content_order.id
</code>```

Body:
so I have three tables with content and one that holds row order of those three tables

here are the tables

table content_order
id | content_type | content id
1 | content1 | 1
2 | content1 | 2
3 | content3 | 1
4 | content2 | 1

table content1
id | some_text
1 | aaaa
2 | bbb

table content2
id | some_text
1 | text yyyy

table content3
id | some_text
1 | text bbbb

so how do I get this?

content_type | some_text | content_id
content1 | aaaa | 1 |
content2 | bbb | 2 |
content3 | yyyy | 1 |
content2 | bbbb | 1 |

Body:
Try this:

SELECT content_type, some_text, id as content_id
FROM (
               SELECT 'content1' as content_type, content1.Id, content1.some_text
     UNION ALL SELECT 'content2', content2.Id, content2.some_text
     UNION ALL SELECT 'content3', content3.Id, content3.some_text) contents
JOIN content_order
  ON content_order.content_type = contents.content_type
 AND content_order.content_Id = contents.Id
ORDER BY content_order.id


来源: stackexchange

问:
Accepting a List from Javascript Ajax Post to C# Method
I would like to know how to pass a list of valid Targets into the method PassThings() from Javascript to C#.
For Example something like this coming from a Javascript $.ajax post.

```<code>{
    "OverheadID": "31l",
    "ValuationClassID": 1,
    "InventoryElementID": 1,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "TargetDescription": null
  },
  {
    "OverheadID": "31l",
    "ValuationClassID": 1,
    "InventoryElementID": 2,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "TargetDescription": null
  },
  {
    "OverheadID": "31l",
    "ValuationClassID": 1,
    "InventoryElementID": 3,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "LopTargetDescription": null
  },
  {
    "OverheadID": "31l",
    "ValuationClassID": 2,
    "InventoryElementID": 1,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "TargetDescription": null
  }
</code>```

I have been unable to get any kind of list to work from my Javascript $.ajax post to the C# method PassThings().

I only have been able to hard code the variable OneOfNine which represents a single valid Target in JSON format.

This was to confirm that the Javascript will send a valid syntax and my JsonConvert.DeserializeObject<Target>(OneOfNine) would function.

```<code>public class Target{
    public virtual string OverheadID { get; set; } //not a true Fkey
    public int ValuationClassID { get; set; } //not a true Fkey
    public int InventoryElementID { get; set; } //not a true Fkey
    public decimal? Target_A_LC { get; set; } //LOP Target A Local Currency
    public decimal? Target_A_QTY { get; set; } //LOP Target A Qty
    public decimal? Target_B_LC { get; set; } //Target B Local Currency
    public decimal? Target_B_QTY { get; set; } //LOP Target B Qty
    public string TargetDescription { get; set; } //optional text reference
}

public IActionResult PassThings()
{

    var OneOfNine = "{ \"OverheadID\": \"ASASAS\", \"ValuationClassID\": 2, \"InventoryElementID\": 3, \"Target_A_LC\": 0, \"Target_A_QTY\": 0, \"Target_B_LC\": 0, \"Target_B_QTY\": 0, \"TargetDescription\": \"na\" }";
    var deserial = JsonConvert.DeserializeObject<Target>(OneOfNine);

    var resource =
    new Target
    {
        OverheadID = deserial.OverheadID,
        ValuationClassID = deserial.ValuationClassID,
        InventoryElementID = deserial.InventoryElementID,
        Target_A_LC = deserial.Target_A_LC,
        Target_A_QTY = deserial.Target_A_QTY,
        Target_B_LC = deserial.Target_B_LC,
        Target_B_QTY = deserial.Target_B_QTY,
        TargetDescription = deserial.TargetDescription
    };

    return Ok(resource);
}
</code>```

I tried setup like this

```<code>public IActionResult PassThings([FromBody]List<Target> things)
</code>```

And my Javascript code in this format.

```<code>$.ajax({
    type: 'POST',
    //contentType: 'application/json; charset=utf-8',
    accepts: 'application/json', //mandatory activity
    contentType: 'application/json', //mandatory activity
    url: '/api/APILopTargets/PassThings',
    data: JSON.stringify(things)
});
</code>```

答:
If you would like url to be/api/APILopTargets/PassThings, the ApiController needs to be configured like

```<code>[Route("api/[controller]")]
[ApiController]
public class APILopTargetsController : ControllerBase
{
    [HttpPost("PassThings")]//add the attribute
    public IActionResult PassThings([FromBody]List<Target> things)
    {...}
}
</code>```

JavaScript:

```<code>var things = [
      {
       "OverheadID": "31l",
       "ValuationClassID": 1,
       "InventoryElementID": 1,
       "Target_A_LC": 0,
       "Target_A_QTY": 0,
       "Target_B_LC": null,
       "Target_B_QTY": null,
       "TargetDescription": null
      },
      {...},
      ...
    ];

$.ajax({
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        url: '/api/APILopTargets/PassThings',
        data: JSON.stringify(things),
        success: function (result) {

        }
 });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to know how to pass a list of valid Targets into the method PassThings() from Javascript to C#.
For Example something like this coming from a Javascript $.ajax post.

{
    "OverheadID": "31l",
    "ValuationClassID": 1,
    "InventoryElementID": 1,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "TargetDescription": null
  },
  {
    "OverheadID": "31l",
    "ValuationClassID": 1,
    "InventoryElementID": 2,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "TargetDescription": null
  },
  {
    "OverheadID": "31l",
    "ValuationClassID": 1,
    "InventoryElementID": 3,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "LopTargetDescription": null
  },
  {
    "OverheadID": "31l",
    "ValuationClassID": 2,
    "InventoryElementID": 1,
    "Target_A_LC": 0,
    "Target_A_QTY": 0,
    "Target_B_LC": null,
    "Target_B_QTY": null,
    "TargetDescription": null
  }

I have been unable to get any kind of list to work from my Javascript $.ajax post to the C# method PassThings().

I only have been able to hard code the variable OneOfNine which represents a single valid Target in JSON format.

This was to confirm that the Javascript will send a valid syntax and my JsonConvert.DeserializeObject<Target>(OneOfNine) would function.

public class Target{
    public virtual string OverheadID { get; set; } //not a true Fkey
    public int ValuationClassID { get; set; } //not a true Fkey
    public int InventoryElementID { get; set; } //not a true Fkey
    public decimal? Target_A_LC { get; set; } //LOP Target A Local Currency
    public decimal? Target_A_QTY { get; set; } //LOP Target A Qty
    public decimal? Target_B_LC { get; set; } //Target B Local Currency
    public decimal? Target_B_QTY { get; set; } //LOP Target B Qty
    public string TargetDescription { get; set; } //optional text reference
}

public IActionResult PassThings()
{

    var OneOfNine = "{ \"OverheadID\": \"ASASAS\", \"ValuationClassID\": 2, \"InventoryElementID\": 3, \"Target_A_LC\": 0, \"Target_A_QTY\": 0, \"Target_B_LC\": 0, \"Target_B_QTY\": 0, \"TargetDescription\": \"na\" }";
    var deserial = JsonConvert.DeserializeObject<Target>(OneOfNine);

    var resource =
    new Target
    {
        OverheadID = deserial.OverheadID,
        ValuationClassID = deserial.ValuationClassID,
        InventoryElementID = deserial.InventoryElementID,
        Target_A_LC = deserial.Target_A_LC,
        Target_A_QTY = deserial.Target_A_QTY,
        Target_B_LC = deserial.Target_B_LC,
        Target_B_QTY = deserial.Target_B_QTY,
        TargetDescription = deserial.TargetDescription
    };

    return Ok(resource);
}

I tried setup like this

public IActionResult PassThings([FromBody]List<Target> things)

And my Javascript code in this format.

$.ajax({
    type: 'POST',
    //contentType: 'application/json; charset=utf-8',
    accepts: 'application/json', //mandatory activity
    contentType: 'application/json', //mandatory activity
    url: '/api/APILopTargets/PassThings',
    data: JSON.stringify(things)
});

Body:
If you would like url to be/api/APILopTargets/PassThings, the ApiController needs to be configured like

[Route("api/[controller]")]
[ApiController]
public class APILopTargetsController : ControllerBase
{
    [HttpPost("PassThings")]//add the attribute
    public IActionResult PassThings([FromBody]List<Target> things)
    {...}
}

JavaScript:

var things = [
      {
       "OverheadID": "31l",
       "ValuationClassID": 1,
       "InventoryElementID": 1,
       "Target_A_LC": 0,
       "Target_A_QTY": 0,
       "Target_B_LC": null,
       "Target_B_QTY": null,
       "TargetDescription": null
      },
      {...},
      ...
    ];

$.ajax({
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        url: '/api/APILopTargets/PassThings',
        data: JSON.stringify(things),
        success: function (result) {

        }
 });


问:
CommandLineRunner functionality in Spring MVC application
We have a Spring MVC project with multiple Maven modules. We package it into an EAR and deploy it to a WildFly server.

I am trying to do a single time job on project start up. Thus, I thought about the CommandLineRunner interface, the project would compile and run but the commandLineRunner run method wouldn't run.

I guess it's because we are using an MVC Spring project and not a SpringBoot one with its own embedded server.
Can you suggest any ways to implement such a concept in Spring MVC ?

Thanks.

答:
You can do something like that:

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class StartupExec implements {

  @EventListener(ContextRefreshedEvent.class)
  public void contextRefreshedEvent() {
    // do whatever you need here
  }
}
```

This is from this answer.

Body:
You can do something like that:

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class StartupExec implements {

  @EventListener(ContextRefreshedEvent.class)
  public void contextRefreshedEvent() {
    // do whatever you need here
  }
}

This is from this answer.


问:
Node JS Express Route Restrict issue
I'm trying to retrieve audio/image file from db.

```<code>app.use(restrictMiddleware());
</code>```

Tho, because of the Route Restrict: It doesn't work.
The question is, is there any other way to retrieve audio/image file from db so that it won't conflict with Authentication Route Restriction?

```<code>self.get = function (req, res) {
  let params = [
    req.params.record_id,
  ];
  db.query(`SELECT * ...`, params).then((data) => {
    console.log('result: ', data.rows.length);
    res.contentType('audio/mpeg');
    res.send(data.rows[0].audiofile);
  }).catch((err) => {
    res.status(500).end("Error:" + err);
  });

};
</code>```

答:
Various ways of tackling this:

Simplest way is to declare the route before you call app.use(restrictMiddleware())

Cleanest way is probably go move all the secure routes into their own Router and only apply the restrictMiddleware to that, that way you can add non-secure routes easily

Alternatively, you could check for a specific URL / Header etc in the restrictMiddleware and skip when appropriate (not the nicest, but would do the job)

Title: Node JS Express Route Restrict issue

Body:
I'm trying to retrieve audio/image file from db.

app.use(restrictMiddleware());

Tho, because of the Route Restrict: It doesn't work.
The question is, is there any other way to retrieve audio/image file from db so that it won't conflict with Authentication Route Restriction?

self.get = function (req, res) {
  let params = [
    req.params.record_id,
  ];
  db.query(`SELECT * ...`, params).then((data) => {
    console.log('result: ', data.rows.length);
    res.contentType('audio/mpeg');
    res.send(data.rows[0].audiofile);
  }).catch((err) => {
    res.status(500).end("Error:" + err);
  });

};


问:
What is the proper way to seed a 3 node cluster?
A little background if it helps, I'm preparing a 3 node cluster (all in the same rackspace). I want 3 nodes for optimal consistency and resilience in the smallest footprint and I am not concerned with replicating the cluster to another region. </p>

<p>One question I have is regarding seed nodes. I know that it is not a good idea to make every node in your cluster a seed, but in the case of 3 nodes, should I just go ahead and do that? Or should I just make a subset of the three nodes seed nodes? Confused as to how pick how many or which ones (all the machines are identical so which ones probably isn't an issue). </p>

答:
Internode communications (gossip)The seed node designation has no purpose other than bootstrapping the gossip process for new nodes joining the cluster. Seed nodes are not a single point of failure, nor do they have any other special purpose in cluster operations beyond the bootstrapping of nodes.

Making every node a seed node is not recommended because of increased maintenance and reduced gossip performance. Gossip optimization is not critical, but it is recommended to use a small seed list.

So the best practice is setting 1 seed node for a 3 node cluster.

ContentLicense: CC BY-SA 3.0

Body:
A little background if it helps, I'm preparing a 3 node cluster (all in the same rackspace). I want 3 nodes for optimal consistency and resilience in the smallest footprint and I am not concerned with replicating the cluster to another region.

One question I have is regarding seed nodes. I know that it is not a good idea to make every node in your cluster a seed, but in the case of 3 nodes, should I just go ahead and do that? Or should I just make a subset of the three nodes seed nodes? Confused as to how pick how many or which ones (all the machines are identical so which ones probably isn't an issue).


问:
docker build with pip install overwrites existing packages
This is my Dockerfile:

```<code>FROM docker_with_pre_installed_packages:1.0
ADD requirements.txt .
RUN pip install -r requirements.txt
ADD app app
WORKDIR /
</code>```

docker_with_pre_installed_packages has:

```<code>/usr/local/lib/python2.7/site-packages/my_packages/db
/usr/local/lib/python2.7/site-packages/my_packages/config
/usr/local/lib/python2.7/site-packages/my_packages/logging
</code>```

requirements.txt:

```<code>my_package.redis-db
my_package.common.utils
</code>```

after running

```<code>docker build -t test:1.0 .
docker run -it test:1.0 bash
cd /usr/local/lib/python2.7/site-packages/my_packages/
ls
__init__.py redis_db common
</code>```

pip freeze still shows the old packages
and I can still see the dist-info directory
but when trying to run python and import something from the pre installed packages I getting:

```<code>ImportError: No module named my_package.config
</code>```

Thanks!

答:
I suggest checking what exactly has changed in your docker container due to executing

```<code>pip install -r requirements.txt
</code>```

I would

1) build docker container from lines before pip install

```<code>FROM docker_with_pre_installed_packages:1.0
ADD requirements.txt .
CMD /bin/bash
</code>```

2) run the docker and execute manually pip install -r requirements.txt

Then outside docker (but having it still running) I would see what a difference the above command caused in my container by executing

3) docker ps to see container_id (e.g. 397cd1c9939f)

4) docker diff 397cd1c9939f to see the difference

Hope it helps.

Body:
This is my Dockerfile:

FROM docker_with_pre_installed_packages:1.0
ADD requirements.txt .
RUN pip install -r requirements.txt
ADD app app
WORKDIR /

docker_with_pre_installed_packages has:

/usr/local/lib/python2.7/site-packages/my_packages/db
/usr/local/lib/python2.7/site-packages/my_packages/config
/usr/local/lib/python2.7/site-packages/my_packages/logging

requirements.txt:

my_package.redis-db
my_package.common.utils

after running

docker build -t test:1.0 .
docker run -it test:1.0 bash
cd /usr/local/lib/python2.7/site-packages/my_packages/
ls
__init__.py redis_db common

pip freeze still shows the old packages
and I can still see the dist-info directory
but when trying to run python and import something from the pre installed packages I getting:

ImportError: No module named my_package.config

Thanks!

Body:
I suggest checking what exactly has changed in your docker container due to executing

pip install -r requirements.txt

I would

1) build docker container from lines before pip install

FROM docker_with_pre_installed_packages:1.0
ADD requirements.txt .
CMD /bin/bash

2) run the docker and execute manually pip install -r requirements.txt

Then outside docker (but having it still running) I would see what a difference the above command caused in my container by executing

3) docker ps to see container_id (e.g. 397cd1c9939f)

4) docker diff 397cd1c9939f to see the difference

Hope it helps.


问:
SYSDATE minus some date variable returns a different value
I'm using Oracle 11g and having a problem in finding the difference of days between two dates - (Sysdate) and some date variable. The difference then would be multiplied to another number. Below are the two methods I have tried but kept returning a negative value.

The newly assigned return_date variable has a correct value.

Thanks in advance for the help!

```<code>UPDATE borrowed_books
    SET penalty_fine = (TO_DATE(sysdate, 'dd-mm-yyyy') - TO_DATE(return_date, 'dd-mm-yyyy')) * 20,
        return_date = SYSDATE
        WHERE patron_id = patID AND
              transaction_id = transID;
</code>```

```<code>UPDATE borrowed_books
       SET penalty_fine = (sysdate - return_date) * 20,
           return_date = SYSDATE
           WHERE patron_id = patID AND
                 transaction_id = transID;
</code>```

答:
You can use a subquery like i used below.</p>

```<code>CREATE TABLE BORROWED_BOOKS
AS
SELECT 5 PENALTY_FINE,TO_DATE('19000101','YYYYMMDD') RETURN_DATE,1
PATRON_ID,78 TRANSACTION_ID FROM DUAL
UNION ALL
SELECT 4 PENALTY_FINE,TO_DATE('19000101','YYYYMMDD') RETURN_DATE,2
PATRON_ID,79 TRANSACTION_ID FROM DUAL
UNION ALL
SELECT 3 PENALTY_FINE,TO_DATE('19000101','YYYYMMDD') RETURN_DATE,3
PATRON_ID,80 TRANSACTION_ID FROM DUAL

UPDATE BORROWED_BOOKS
   SET PENALTY_FINE =
        (SELECT (SYSDATE - RETURN_DATE)* 20
           FROM BORROWED_BOOKS
          WHERE PATRON_ID = 1 AND TRANSACTION_ID = 78)
      ,
   RETURN_DATE = SYSDATE
 WHERE PATRON_ID = 1 AND TRANSACTION_ID = 78;

COMMIT;
</code>```

Body:
I'm using Oracle 11g and having a problem in finding the difference of days between two dates - (Sysdate) and some date variable. The difference then would be multiplied to another number. Below are the two methods I have tried but kept returning a negative value.

The newly assigned return_date variable has a correct value.

Thanks in advance for the help!

UPDATE borrowed_books
    SET penalty_fine = (TO_DATE(sysdate, 'dd-mm-yyyy') - TO_DATE(return_date, 'dd-mm-yyyy')) * 20,
        return_date = SYSDATE
        WHERE patron_id = patID AND
              transaction_id = transID;

UPDATE borrowed_books
       SET penalty_fine = (sysdate - return_date) * 20,
           return_date = SYSDATE
           WHERE patron_id = patID AND
                 transaction_id = transID;

Body:
You can use a subquery like i used below.

CREATE TABLE BORROWED_BOOKS
AS
SELECT 5 PENALTY_FINE,TO_DATE('19000101','YYYYMMDD') RETURN_DATE,1
PATRON_ID,78 TRANSACTION_ID FROM DUAL
UNION ALL
SELECT 4 PENALTY_FINE,TO_DATE('19000101','YYYYMMDD') RETURN_DATE,2
PATRON_ID,79 TRANSACTION_ID FROM DUAL
UNION ALL
SELECT 3 PENALTY_FINE,TO_DATE('19000101','YYYYMMDD') RETURN_DATE,3
PATRON_ID,80 TRANSACTION_ID FROM DUAL

UPDATE BORROWED_BOOKS
   SET PENALTY_FINE =
        (SELECT (SYSDATE - RETURN_DATE)* 20
           FROM BORROWED_BOOKS
          WHERE PATRON_ID = 1 AND TRANSACTION_ID = 78)
      ,
   RETURN_DATE = SYSDATE
 WHERE PATRON_ID = 1 AND TRANSACTION_ID = 78;

COMMIT;


问:
Fill blank values with data from following columns
Having a dataframe like this:

```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"))
</code>```

How is it possible to detect if in the text1 column a row is blank and fill the blank with a value exist in text2, text3 or text4 column and leave from this NA after the process

Example of expected output

```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","another","another","all"), text2 = c("more","","add",""), text3 = c("final","and","where",""))
</code>```

答:
In base R you could do:</p>

```<code>txt <- do.call(paste,c(sep = ',',`is.na<-`(df,df=="")))
df1 <- read.csv(text = sub("((?:,NA)+)(,\\w+)","\\2\\1",txt),
               header = FALSE,
               col.names = names(df),
               stringsAsFactors = FALSE)

df1[is.na(df1)] <- ""
df1
  id   text1 text2 text3
1  1     sth  more final
2  2 another         and
3  3 another   add where
4  4     all
</code>```

Body:
Having a dataframe like this:

data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"))

How is it possible to detect if in the text1 column a row is blank and fill the blank with a value exist in text2, text3 or text4 column and leave from this NA after the process

Example of expected output

data.frame(id = c(1,2,3,4), text1 = c("sth","another","another","all"), text2 = c("more","","add",""), text3 = c("final","and","where",""))

Body:
In base R you could do:

txt <- do.call(paste,c(sep = ',',`is.na<-`(df,df=="")))
df1 <- read.csv(text = sub("((?:,NA)+)(,\\w+)","\\2\\1",txt),
               header = FALSE,
               col.names = names(df),
               stringsAsFactors = FALSE)

df1[is.na(df1)] <- ""
df1
  id   text1 text2 text3
1  1     sth  more final
2  2 another         and
3  3 another   add where
4  4     all


问:
How do I request a refresh token using OIDC
I am trying to implement refresh tokens with OIDC and OAuth2 and am having trouble understanding the workflow.  From what I do understand, using the Authorization Code flow, what gets the refresh token in the response from the /token endpoint is the presence of the offline_access scope in the /authorize request.

My question is how does the request to the token endpoint know that it should return a refresh token for that user logging in, if the offline_access scope is only sent to the /authorize endpoint or should that scope also be present in the token request?  Or is this a case where the refresh token should be generated and stored during the /authorize workflow, before the code is returned and then just looked up in the /token workflow to be returned there?

Specifically following this workflow:

答:
Scopes are sent during the Authorize request and from the Authorization Server's viewpoint the following actions are performed:

code is returned to the caller

code is cached with a short time to live (eg 1 minute)

scopes are cached

in some flows other details such as a PKCE verifier are also cached

Next the client makes an Authorization Code Grant request to exchange the code for tokens and the Authorization Server performs these actions:

Looks up the code

Applies PKCE verification checks

Checks the redirect URI matches that of the original request

Looks up cached scopes

Looks up details from the OAuth client configuration, such as the refresh token lifetime

Generates tokens based on the above data

Deletes the cache entry, so that the same code cannot be processed again

Returns tokens to the caller

It is useful as an application developer to have an understanding of the key points of the AS behaviour, as above, though I expect I'm missing an important point or two. My main focus tends to be integrating flows in my UIs and APIs.

Of course when it comes to the Authorization Server, we should always use a certified 3rd party implementation, such as a low cost cloud or free open source solution.


问:
How to allow only lower case as input arguments in Bash
I want to allow only lower case in my input. I've tried [a-z], [a-z^A-Z] and also [:lower:]. But it doesn't help.

All the expressions are going to else loop only if the whole string in uppercase.

Example:

If 1. Demo --- It says syntax valid
   2. demo --- It says syntax valid
   3. DEMO --- It says syntax invalid

But I need the syntax invalid even if the input is similar to example 1.

```<code>#!/bin/bash
client_name=$1

if [[ "$client_name" =~ [:lower:] ]]
        then
        echo " CLIENT Name Syntax is Valid"
        else
        echo -e "CLIENT Name Syntax is Invalid"
        exit 01
fi
</code>```

Any suggestion would be much appreciated. Thanks

答:
Or just make them lowercased</p>

```<code>$ test="ASDFasdaSDaDASDasdczXVSD"
$ echo ${test,,}
asdfasdasdadasdasdczxvsd
</code>```

Body:
I want to allow only lower case in my input. I've tried [a-z], [a-z^A-Z] and also [:lower:]. But it doesn't help.

All the expressions are going to else loop only if the whole string in uppercase.

Example:

If 1. Demo --- It says syntax valid
   2. demo --- It says syntax valid
   3. DEMO --- It says syntax invalid

But I need the syntax invalid even if the input is similar to example 1.

#!/bin/bash
client_name=$1

if [[ "$client_name" =~ [:lower:] ]]
        then
        echo " CLIENT Name Syntax is Valid"
        else
        echo -e "CLIENT Name Syntax is Invalid"
        exit 01
fi

Any suggestion would be much appreciated. Thanks

Body:
Or just make them lowercased

$ test="ASDFasdaSDaDASDasdczXVSD"
$ echo ${test,,}
asdfasdasdadasdasdczxvsd


问:
Using variable in FROM clause pl/sql
```<code>SET SERVEROUTPUT ON
DECLARE
table_name varchar2(80) := 'dual';
BEGIN
SELECT * FROM table_name WHERE dummy = 'X';
END;
</code>```

<p>The above code throws error. I want to use a variable in the from clause. </p>

答:
For a dynamic query you can use EXECUTE IMMEDIATE.

```<code>DECLARE
    table_name   VARCHAR2 (80) := 'dual';
    v_query      VARCHAR2 (200);
BEGIN
    v_query := 'SELECT   *
                FROM   ' || table_name || '
                WHERE   dummy = ''X''';

     EXECUTE IMMEDIATE v_query;
END;
</code>```

Title: Using variable in FROM clause pl/sql

Body:
SET SERVEROUTPUT ON
DECLARE
table_name varchar2(80) := 'dual';
BEGIN
SELECT * FROM table_name WHERE dummy = 'X';
END;

The above code throws error. I want to use a variable in the from clause.

Body:
For a dynamic query you can use EXECUTE IMMEDIATE.

DECLARE
    table_name   VARCHAR2 (80) := 'dual';
    v_query      VARCHAR2 (200);
BEGIN
    v_query := 'SELECT   *
                FROM   ' || table_name || '
                WHERE   dummy = ''X''';

     EXECUTE IMMEDIATE v_query;
END;


问:
Add rows before pasting data in a new sheet (between specific cells)
I have a sheet with data and I want to copy its data to another sheet. That's simple, but the problem is, I have to copy that selection to a range between two cells that is set, so if I add another row with data in the first sheet then when the macro runs, the data will overwrite the cells below the limit. How do I make it that if I add a row in the first sheet, before the macro pastes the data in the other sheet another row or a number of rows will be created to avoid the limit below being overwritten?
For example, if the number of rows between two cells is 5 and the range I need to paste is 7, then, prior to pasting the data, the macro creates two more rows.

Thank you

答:
Calculate the difference and add rows if required</p>

```<code>Option Explicit
Sub CopyInsert()

    Dim rngSource As Range
    Set rngSource = Selection ' range to copy from

    Const SHEET_TARGET = "Sheet2"
    Const RNG_TARGET = "C12:C16"

    Dim wb As Workbook, wsTarget As Worksheet
    Dim rngTarget As Range, n As Long

    Set wb = ThisWorkbook
    Set wsTarget = wb.Sheets(SHEET_TARGET)
    Set rngTarget = wsTarget.Range(RNG_TARGET)

    ' insert new ones
    n = rngSource.Rows.Count - rngTarget.Rows.Count
    If n > 0 Then
        rngTarget.Rows("2:" & n + 1).EntireRow.Insert
    End If

    rngSource.Copy rngTarget.Cells(1, 1)

End Sub
</code>```

Body:
Calculate the difference and add rows if required

Option Explicit
Sub CopyInsert()

    Dim rngSource As Range
    Set rngSource = Selection ' range to copy from

    Const SHEET_TARGET = "Sheet2"
    Const RNG_TARGET = "C12:C16"

    Dim wb As Workbook, wsTarget As Worksheet
    Dim rngTarget As Range, n As Long

    Set wb = ThisWorkbook
    Set wsTarget = wb.Sheets(SHEET_TARGET)
    Set rngTarget = wsTarget.Range(RNG_TARGET)

    ' insert new ones
    n = rngSource.Rows.Count - rngTarget.Rows.Count
    If n > 0 Then
        rngTarget.Rows("2:" & n + 1).EntireRow.Insert
    End If

    rngSource.Copy rngTarget.Cells(1, 1)

End Sub


问:
How to allocate memory of triple pointer in a C function
I am new to C and have a case where I want to read in a simple text file with one word per row and I want to save this into an array.  However, I want to declare a double pointer in function main and then pass that by reference to another function to allocate the memory and populate the double pointer.  I can't seem to get it to work without throwing segmentation faults.  Any advice would be much appreciated.

Here is what I've tried:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
test.txt = content between the "---"
---
first
second
third
fourth
fifth
sixth
seventh
---
*/

void allocmem (char ***tptr) {

    FILE *infile = fopen("test.txt", "r");
    int bufferLength = 5;
    char *buffer = malloc(sizeof(char) * bufferLength);

    int c, i, row, rows;
    c = i = row = 0;
    rows = 7;

/*
    I want to allocate an array of char strings to store the list from test.txt in
    I have tried different variants here
*/

    tptr = malloc(sizeof(char**) * rows);
    for (int r = 0; r < rows; r++) {
        *tptr[r] = malloc(sizeof(char*) * bufferLength);
    }

/*
    // another attempt
    *tptr = malloc(sizeof(char*) * rows);
    for (int r = 0; r < rows; r++) {
        *tptr[r] = malloc(sizeof(char) * bufferLength);
    }
*/

    while ((c = getc(infile)) != EOF) {

        if (c == '\n') {
            buffer[++i] = '\0';
            printf("buffer: %s\n", buffer);

            // I am also a little unsure how to append my buffer to the pointer array here too
            strcpy(*tptr[row++], buffer);
            memset(buffer, '\0', bufferLength);
            i = 0;
        } else {
            buffer[i++] = c;
        }

    }

    fclose(infile);

}

int main () {

    // double pointer to hold array value from test.txt in
    char **dptr;

    // allocate memory and read test.txt and store each row into the array
    allocmem(&dptr);

/*
    print each element of dptr here yielding the expected results of:

    first
    second
    third
    fourth
    fifth
    sixth
    seventh
*/

    return 0;
}
</code>```

答:
While the example linked was quite a bit more involved than what you require here, the principles are the same. When you declare a function void and eliminate the ability to return a pointer to a newly allocated block of memory, you will need to pass the address of the pointer you need to allocate storage for.

Why the address of?

When you initially allocate, or reallocate, the address for the block of memory will change. If you simply pass a pointer to your function to allocate, the function receives a copy of the original pointer with its own, and very different address. In C all parameters are passed by value and the function receives a copy. Any changes made to the copy in your function are lost on the function return.

However, if you pass the address of the variable (one additional level of pointer indirection), the function receives a copy of the pointer to your variable, but that pointer holds the address of the original pointer. So now you can make changes and assign the new block of memory to the dereferenced pointer in your function, which assigns the new beginning address for the block of memory to the original pointer and the changes will be seen back in the calling function.

In your case, you want to read an unknown number of strings from a file and add them your allocated collection of strings within a void function. Were you to simply allocate/reallocate in main(), you could simply declare a char **ptrs; (a double-pointer), and then allocate/reallocate the number of pointers you have with each string read from your file, allocate storage for the string, and assign the address for the block to your newly allocated pointer, and then copy the string to your pointer -- and repeat until you run out of strings.

The only thing that changes when allocating and copying in a void function is you will pass the address of char **ptrs; to the function adding one-level of pointer indirection (so the function parameter type will be char ***, and then within the function you must remove that one additional level of indirection to operate on the pointer. You will also need to pass the address of a variable holding the current number of pointers allocated -- so you know how many you need to realloc() within the function.

Putting it altogether, your function can be written as:

```<code>/* allocate pointer for *strings, allocate/copy s to (*strings)[*nptr] */
void allocmem (char ***strings, size_t *nptrs, const char *s)
{
    size_t len = strlen (s);    /* determine length of s */
    /* reallocate *string to a temporary pointer, adding 1 pointer */
    void *tmp = realloc (*strings, (*nptrs + 1) * sizeof **strings);

    if (!tmp) { /* validate EVERY allocation/reallocation */
        perror ("realloc-allocptr-strings");
        exit (EXIT_FAILURE);
    }
    *strings = tmp;     /* assign newly allocated block of pointers to *strings */

    (*strings)[*nptrs] = malloc (len + 1);      /* allocate storage for s */
    if (!(*strings)[*nptrs]) {  /* ditto */
        perror ("malloc-(*strings)[*nptrs]");
        exit (EXIT_FAILURE);
    }
    memcpy ((*strings)[*nptrs], s, len + 1);    /* copy s to allocated storage */

    *nptrs += 1;    /* increment pointer count after successful allocation/copy */
}
</code>```

(note: on allocation failure, the program simply exits -- but for actual code, you would need some way to know whether both allocations occurred and the string was copied. Saving a before/after count of nptrs can give part of the picture, but can't tell you which allocation failed -- if the realloc() failed, then since you used a tmp pointer to realloc(), your pointers and strings as they existed before the function call are preserved and are still reachable though the original pointer)

(note2: the parenthesis around *strings in (*strings)[*nptrs] are required because in C Operator Precedence, [..] has higher precedence than the dereference operator '*')

Putting an example together to read your file and store the string is your allocated collection of pointers and strings, you could do:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */

/* allocate pointer for *strings, allocate/copy s to (*strings)[*nptr] */
void allocmem (char ***strings, size_t *nptrs, const char *s)
{
    size_t len = strlen (s);    /* determine length of s */
    /* reallocate *string to a temporary pointer, adding 1 pointer */
    void *tmp = realloc (*strings, (*nptrs + 1) * sizeof **strings);

    if (!tmp) { /* validate EVERY allocation/reallocation */
        perror ("realloc-allocptr-strings");
        exit (EXIT_FAILURE);
    }
    *strings = tmp;     /* assign newly allocated block of pointers to *strings */

    (*strings)[*nptrs] = malloc (len + 1);      /* allocate storage for s */
    if (!(*strings)[*nptrs]) {  /* ditto */
        perror ("malloc-(*strings)[*nptrs]");
        exit (EXIT_FAILURE);
    }
    memcpy ((*strings)[*nptrs], s, len + 1);    /* copy s to allocated storage */

    *nptrs += 1;    /* increment pointer count after successful allocation/copy */
}

int main (int argc, char **argv) {

    char buf[MAXC],         /* temp storage for each line read from file */
         **strings = NULL;  /* must initialize pointer NULL */
    size_t nptrs = 0;       /* number of pointers allocated */
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) {         /* read each line into buf */
        buf[strcspn (buf, "\n")] = 0;       /* trim \n from end of buf */
        allocmem (&strings, &nptrs, buf);   /* add string to strings */
    }
    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);

    for (size_t i = 0; i < nptrs; i++) {    /* output all stored strings */
        printf ("strings[%zu] : %s\n", i, strings[i]);
        free (strings[i]);      /* free storage for string */
    }
    free (strings);             /* free pointers */
}
</code>```

Example Use/Output

```<code>$ ./bin/3starstrings dat/test1-7.txt
strings[0] : first
strings[1] : second
strings[2] : third
strings[3] : fourth
strings[4] : fifth
strings[5] : sixth
strings[6] : seventh
</code>```

Memory Use/Error Check

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to ensure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

```<code>$ valgrind ./bin/3starstrings dat/test1-7.txt
==23799== Memcheck, a memory error detector
==23799== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==23799== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==23799== Command: ./bin/3starstrings dat/test1-7.txt
==23799==
strings[0] : first
strings[1] : second
strings[2] : third
strings[3] : fourth
strings[4] : fifth
strings[5] : sixth
strings[6] : seventh
==23799==
==23799== HEAP SUMMARY:
==23799==     in use at exit: 0 bytes in 0 blocks
==23799==   total heap usage: 17 allocs, 17 frees, 5,942 bytes allocated
==23799==
==23799== All heap blocks were freed -- no leaks are possible
==23799==
==23799== For counts of detected and suppressed errors, rerun with: -v
==23799== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

Always confirm that you have freed all memory you have allocated and that there are no memory errors.

Look things over and let me know if you have further questions (and remember, being called a 3-Star Programmer isn't a compliment -- return a pointer from your function instead :)

Body:
I am new to C and have a case where I want to read in a simple text file with one word per row and I want to save this into an array.  However, I want to declare a double pointer in function main and then pass that by reference to another function to allocate the memory and populate the double pointer.  I can't seem to get it to work without throwing segmentation faults.  Any advice would be much appreciated.

Here is what I've tried:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
test.txt = content between the "---"
---
first
second
third
fourth
fifth
sixth
seventh
---
*/

void allocmem (char ***tptr) {

    FILE *infile = fopen("test.txt", "r");
    int bufferLength = 5;
    char *buffer = malloc(sizeof(char) * bufferLength);

    int c, i, row, rows;
    c = i = row = 0;
    rows = 7;

/*
    I want to allocate an array of char strings to store the list from test.txt in
    I have tried different variants here
*/

    tptr = malloc(sizeof(char**) * rows);
    for (int r = 0; r < rows; r++) {
        *tptr[r] = malloc(sizeof(char*) * bufferLength);
    }

/*
    // another attempt
    *tptr = malloc(sizeof(char*) * rows);
    for (int r = 0; r < rows; r++) {
        *tptr[r] = malloc(sizeof(char) * bufferLength);
    }
*/

    while ((c = getc(infile)) != EOF) {

        if (c == '\n') {
            buffer[++i] = '\0';
            printf("buffer: %s\n", buffer);

            // I am also a little unsure how to append my buffer to the pointer array here too
            strcpy(*tptr[row++], buffer);
            memset(buffer, '\0', bufferLength);
            i = 0;
        } else {
            buffer[i++] = c;
        }

    }

    fclose(infile);

}

int main () {

    // double pointer to hold array value from test.txt in
    char **dptr;

    // allocate memory and read test.txt and store each row into the array
    allocmem(&dptr);

/*
    print each element of dptr here yielding the expected results of:

    first
    second
    third
    fourth
    fifth
    sixth
    seventh
*/

    return 0;
}

Body:
While the example linked was quite a bit more involved than what you require here, the principles are the same. When you declare a function void and eliminate the ability to return a pointer to a newly allocated block of memory, you will need to pass the address of the pointer you need to allocate storage for.

Why the address of?

When you initially allocate, or reallocate, the address for the block of memory will change. If you simply pass a pointer to your function to allocate, the function receives a copy of the original pointer with its own, and very different address. In C all parameters are passed by value and the function receives a copy. Any changes made to the copy in your function are lost on the function return.

However, if you pass the address of the variable (one additional level of pointer indirection), the function receives a copy of the pointer to your variable, but that pointer holds the address of the original pointer. So now you can make changes and assign the new block of memory to the dereferenced pointer in your function, which assigns the new beginning address for the block of memory to the original pointer and the changes will be seen back in the calling function.

In your case, you want to read an unknown number of strings from a file and add them your allocated collection of strings within a void function. Were you to simply allocate/reallocate in main(), you could simply declare a char **ptrs; (a double-pointer), and then allocate/reallocate the number of pointers you have with each string read from your file, allocate storage for the string, and assign the address for the block to your newly allocated pointer, and then copy the string to your pointer -- and repeat until you run out of strings.

The only thing that changes when allocating and copying in a void function is you will pass the address of char **ptrs; to the function adding one-level of pointer indirection (so the function parameter type will be char ***, and then within the function you must remove that one additional level of indirection to operate on the pointer. You will also need to pass the address of a variable holding the current number of pointers allocated -- so you know how many you need to realloc() within the function.

Putting it altogether, your function can be written as:

/* allocate pointer for *strings, allocate/copy s to (*strings)[*nptr] */
void allocmem (char ***strings, size_t *nptrs, const char *s)
{
    size_t len = strlen (s);    /* determine length of s */
    /* reallocate *string to a temporary pointer, adding 1 pointer */
    void *tmp = realloc (*strings, (*nptrs + 1) * sizeof **strings);

    if (!tmp) { /* validate EVERY allocation/reallocation */
        perror ("realloc-allocptr-strings");
        exit (EXIT_FAILURE);
    }
    *strings = tmp;     /* assign newly allocated block of pointers to *strings */

    (*strings)[*nptrs] = malloc (len + 1);      /* allocate storage for s */
    if (!(*strings)[*nptrs]) {  /* ditto */
        perror ("malloc-(*strings)[*nptrs]");
        exit (EXIT_FAILURE);
    }
    memcpy ((*strings)[*nptrs], s, len + 1);    /* copy s to allocated storage */

    *nptrs += 1;    /* increment pointer count after successful allocation/copy */
}

(note: on allocation failure, the program simply exits -- but for actual code, you would need some way to know whether both allocations occurred and the string was copied. Saving a before/after count of nptrs can give part of the picture, but can't tell you which allocation failed -- if the realloc() failed, then since you used a tmp pointer to realloc(), your pointers and strings as they existed before the function call are preserved and are still reachable though the original pointer)

(note2: the parenthesis around *strings in (*strings)[*nptrs] are required because in C Operator Precedence, [..] has higher precedence than the dereference operator '*')

Putting an example together to read your file and store the string is your allocated collection of pointers and strings, you could do:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */

/* allocate pointer for *strings, allocate/copy s to (*strings)[*nptr] */
void allocmem (char ***strings, size_t *nptrs, const char *s)
{
    size_t len = strlen (s);    /* determine length of s */
    /* reallocate *string to a temporary pointer, adding 1 pointer */
    void *tmp = realloc (*strings, (*nptrs + 1) * sizeof **strings);

    if (!tmp) { /* validate EVERY allocation/reallocation */
        perror ("realloc-allocptr-strings");
        exit (EXIT_FAILURE);
    }
    *strings = tmp;     /* assign newly allocated block of pointers to *strings */

    (*strings)[*nptrs] = malloc (len + 1);      /* allocate storage for s */
    if (!(*strings)[*nptrs]) {  /* ditto */
        perror ("malloc-(*strings)[*nptrs]");
        exit (EXIT_FAILURE);
    }
    memcpy ((*strings)[*nptrs], s, len + 1);    /* copy s to allocated storage */

    *nptrs += 1;    /* increment pointer count after successful allocation/copy */
}

int main (int argc, char **argv) {

    char buf[MAXC],         /* temp storage for each line read from file */
         **strings = NULL;  /* must initialize pointer NULL */
    size_t nptrs = 0;       /* number of pointers allocated */
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) {         /* read each line into buf */
        buf[strcspn (buf, "\n")] = 0;       /* trim \n from end of buf */
        allocmem (&strings, &nptrs, buf);   /* add string to strings */
    }
    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);

    for (size_t i = 0; i < nptrs; i++) {    /* output all stored strings */
        printf ("strings[%zu] : %s\n", i, strings[i]);
        free (strings[i]);      /* free storage for string */
    }
    free (strings);             /* free pointers */
}

Example Use/Output

$ ./bin/3starstrings dat/test1-7.txt
strings[0] : first
strings[1] : second
strings[2] : third
strings[3] : fourth
strings[4] : fifth
strings[5] : sixth
strings[6] : seventh

Memory Use/Error Check

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to ensure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

$ valgrind ./bin/3starstrings dat/test1-7.txt
==23799== Memcheck, a memory error detector
==23799== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==23799== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==23799== Command: ./bin/3starstrings dat/test1-7.txt
==23799==
strings[0] : first
strings[1] : second
strings[2] : third
strings[3] : fourth
strings[4] : fifth
strings[5] : sixth
strings[6] : seventh
==23799==
==23799== HEAP SUMMARY:
==23799==     in use at exit: 0 bytes in 0 blocks
==23799==   total heap usage: 17 allocs, 17 frees, 5,942 bytes allocated
==23799==
==23799== All heap blocks were freed -- no leaks are possible
==23799==
==23799== For counts of detected and suppressed errors, rerun with: -v
==23799== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always confirm that you have freed all memory you have allocated and that there are no memory errors.

Look things over and let me know if you have further questions (and remember, being called a 3-Star Programmer isn't a compliment -- return a pointer from your function instead :)


问:
Move a button in the screen
I have an UIButton and I want to move that button by touching and swiping it in the screen. When I release the touch it will be in the current position. Explain clearly, please.

答:
If you are scripting for iOS 3.2 and above, consider using UIPanGestureRecognizer.

Simply attach an instance of it like this,

```<code>...
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
panGesture.maximumNumberOfTouches = 1;
panGesture.minimumNumberOfTouches = 1;

[self.button addGestureRecognizer:panGesture];
[panGesture release];
...
</code>```

and define handlePan: like this,

```<code>- (void)handlePan:(UIPanGestureRecognizer *)panGesture {
    CGRect buttonFrame = self.button.frame;
    CGPoint translation = [panGesture translationInView:panGesture.view];

    buttonFrame.origin.x += translation.x;
    buttonFrame.origin.y += translation.y;

    [panGesture setTranslation:CGPointMake(0, 0) inView:panGesture.view];
    self.button.frame = buttonFrame;
}
</code>```

Title: Move a button in the screen

Body:
If you are scripting for iOS 3.2 and above, consider using UIPanGestureRecognizer.

Simply attach an instance of it like this,

...
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
panGesture.maximumNumberOfTouches = 1;
panGesture.minimumNumberOfTouches = 1;

[self.button addGestureRecognizer:panGesture];
[panGesture release];
...

and define handlePan: like this,

- (void)handlePan:(UIPanGestureRecognizer *)panGesture {
    CGRect buttonFrame = self.button.frame;
    CGPoint translation = [panGesture translationInView:panGesture.view];

    buttonFrame.origin.x += translation.x;
    buttonFrame.origin.y += translation.y;

    [panGesture setTranslation:CGPointMake(0, 0) inView:panGesture.view];
    self.button.frame = buttonFrame;
}


问:
ValueError: could not convert string to float: '' in Python 3
I'm coding a little bot in Python and I'm having a problem. It seems to be a common problem, but I've never seen it asked in the same situation I'm in.

Ok so here is the code posing problem:

```<code>old_values = float((removeprc(browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text)))
</code>```

browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text) is a selenium tool used to get a value of a website. as you will see later, the element retrieved is a number which should work with float()
"remove prc" is a little function I created to remove the % of a number, here it is:

```<code>def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)

    return string
</code>```

It's probably not the best way to do it, but it works when I test it alone.

anyway, here is what I get when I run my entire code

```<code>loading page ...
page loaded
acquiring values ...
values acquired
running eth trade
-0.37
Traceback (most recent call last):
  File "C:\Users\pc adam\Documents\EISTI\algoprog\perso\python\fichiers\btc\ETHtradingbotV1.py", line 138, in <module>
    profit = float(browser.find_element_by_xpath('/html/body/div[3]/section[16]/section[2]/section[2]/section[2]/div/div[1]/table/tbody/tr/td[15]/span').text)
ValueError: could not convert string to float: ''
</code>```

the first 5 lines are useless. on the 6th line, I printed what i am trying to get the float()
of. As you can see, it should work and ... It does ! sometimes.

that's the weirdest thing about this, it works perfectly half the time!
I've read on the internet that this can happen if you try to float() things that are not numbers or that have weird shit in them, like spaces. As you can see, I think it's not the case here.

When I try to isolate the problem by running a simplified version of the program like this :

```<code>a = "-0.06%"
def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)
    return string

b = float(removeprc(a))
print(b)
</code>```

it outputs -0.06 and works perfectly ???

So I'm really stuck here. It should work, but it doesn't. Even worst, it works sometimes, for no reason. And when I isolate the problem, it works fine.

Any help would be extremely appreciated!

Oh and if you want to see the entire code, it's here: https://github.com/Madaxuorel/proj-ethTB/blob/master/ETHtradingbotV1.py

答:
This error message...

```<code>ValueError: could not convert string to float: ''
</code>```

...implies that the Python interpreter was unable to convert a string to float.

You were close enough. text method would return a string and to strip off the %, instead of string.split('%') you want list = string.split('%')[0].

An example:

```<code>my_percentage = "99%"
my_string_num = my_percentage.split("%")[0]
print(my_string_num)
</code>```

prints:

```<code>99
</code>```

Further, find_element_by_xpath() will identify only a single element, and using text you would get a single string, so string = " ".join(list) seems redundant.

So effectively, to strip the %, convert the string to float and print, your effective line of code will be:

```<code>print(float(browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text.split("%")[0]))
</code>```

Update

You are still seeing the error as the element with the required text haven't rendered within the DOM when the line of code is invoked. As a solution you need to induce WebDriverWait for the visibility_of_element_located() and you can use the following  Locator Strategy:

```<code>print(float(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='draggableNavRightResizable']/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span"))).text.split("%")[0]))
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
I'm coding a little bot in Python and I'm having a problem. It seems to be a common problem, but I've never seen it asked in the same situation I'm in.

Ok so here is the code posing problem:

old_values = float((removeprc(browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text)))

browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text) is a selenium tool used to get a value of a website. as you will see later, the element retrieved is a number which should work with float()
"remove prc" is a little function I created to remove the % of a number, here it is:

def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)

    return string

It's probably not the best way to do it, but it works when I test it alone.

anyway, here is what I get when I run my entire code

loading page ...
page loaded
acquiring values ...
values acquired
running eth trade
-0.37
Traceback (most recent call last):
  File "C:\Users\pc adam\Documents\EISTI\algoprog\perso\python\fichiers\btc\ETHtradingbotV1.py", line 138, in <module>
    profit = float(browser.find_element_by_xpath('/html/body/div[3]/section[16]/section[2]/section[2]/section[2]/div/div[1]/table/tbody/tr/td[15]/span').text)
ValueError: could not convert string to float: ''

the first 5 lines are useless. on the 6th line, I printed what i am trying to get the float()
of. As you can see, it should work and ... It does ! sometimes.

that's the weirdest thing about this, it works perfectly half the time!
I've read on the internet that this can happen if you try to float() things that are not numbers or that have weird shit in them, like spaces. As you can see, I think it's not the case here.

When I try to isolate the problem by running a simplified version of the program like this :

a = "-0.06%"
def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)
    return string

b = float(removeprc(a))
print(b)

it outputs -0.06 and works perfectly ???

So I'm really stuck here. It should work, but it doesn't. Even worst, it works sometimes, for no reason. And when I isolate the problem, it works fine.

Any help would be extremely appreciated!

Oh and if you want to see the entire code, it's here: https://github.com/Madaxuorel/proj-ethTB/blob/master/ETHtradingbotV1.py

Body:
This error message...

ValueError: could not convert string to float: ''

...implies that the Python interpreter was unable to convert a string to float.

You were close enough. text method would return a string and to strip off the %, instead of string.split('%') you want list = string.split('%')[0].

An example:

my_percentage = "99%"
my_string_num = my_percentage.split("%")[0]
print(my_string_num)

prints:

99

Further, find_element_by_xpath() will identify only a single element, and using text you would get a single string, so string = " ".join(list) seems redundant.

So effectively, to strip the %, convert the string to float and print, your effective line of code will be:

print(float(browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text.split("%")[0]))

Update

You are still seeing the error as the element with the required text haven't rendered within the DOM when the line of code is invoked. As a solution you need to induce WebDriverWait for the visibility_of_element_located() and you can use the following  Locator Strategy:

print(float(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='draggableNavRightResizable']/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span"))).text.split("%")[0]))

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
Access constructor's properties inside constructor
I have the following constructor function.

function Tablo() {
    this.kayit_id = 0;
    this.rapor_instanse = 'rapor';
    this.kosul_durum = null;
    this.tablo_nesne = null;
    this.tablo_getir = function() {
        this.tablo_nesne = new Handsontable(
            document.getElementById(this.rapor_instanse), {
                afterGetColHeader: this.arama_filtre_element_ekle,
                beforeOnCellMouseDown: this.doNotSelectColumn,
                columnSorting: true,
                rowHeaders: true,
                currentRowClassName: 'currentRow',
                wordWrap: false,
                licenseKey: 'non-commercial-and-evaluation',
                manualColumnResize: true,
                manualRowResize: true,
                afterSelectionEnd: function(r, c, r2, c2) {
                    let suppliedarrayobject = this.tablo_nesne.getSourceDataAtRow(
                        this.tablo_nesne.toPhysicalRow(r)
                    );
                    this.kayit_id = suppliedarrayobject.kayit_id;
                }
            }
        );
    };
}
```

I need to access and modify the property tablo_nesne within the afterSelectionEnd function. However, the this keyword points to the wrong context. How do I fix this issue?

答:
The idiomatic solution in ES6 would be to use an arrow function.

function Tablo() {
    this.kayit_id = 0;
    this.rapor_instanse = 'rapor';
    this.kosul_durum = null;
    this.tablo_nesne = null;
    this.tablo_getir = function() {
        this.tablo_nesne = new Handsontable(
            document.getElementById(this.rapor_instanse), {
                afterGetColHeader: this.arama_filtre_element_ekle,
                beforeOnCellMouseDown: this.doNotSelectColumn,
                columnSorting: true,
                rowHeaders: true,
                currentRowClassName: 'currentRow',
                wordWrap: false,
                licenseKey: 'non-commercial-and-evaluation',
                manualColumnResize: true,
                manualRowResize: true,
                afterSelectionEnd: (r, c, r2, c2) => { // This is an arrow function.
                    let suppliedarrayobject = this.tablo_nesne.getSourceDataAtRow(
                        this.tablo_nesne.toPhysicalRow(r)
                    );
                    this.kayit_id = suppliedarrayobject.kayit_id;
                }
            }
        );
    };
}
```

The this keyword within an arrow function is bound lexically. Hence, it'll point to the correct context.

Body:
I have the following constructor function.

function Tablo() {
    this.kayit_id = 0;
    this.rapor_instanse = 'rapor';
    this.kosul_durum = null;
    this.tablo_nesne = null;
    this.tablo_getir = function() {
        this.tablo_nesne = new Handsontable(
            document.getElementById(this.rapor_instanse), {
                afterGetColHeader: this.arama_filtre_element_ekle,
                beforeOnCellMouseDown: this.doNotSelectColumn,
                columnSorting: true,
                rowHeaders: true,
                currentRowClassName: 'currentRow',
                wordWrap: false,
                licenseKey: 'non-commercial-and-evaluation',
                manualColumnResize: true,
                manualRowResize: true,
                afterSelectionEnd: function(r, c, r2, c2) {
                    let suppliedarrayobject = this.tablo_nesne.getSourceDataAtRow(
                        this.tablo_nesne.toPhysicalRow(r)
                    );
                    this.kayit_id = suppliedarrayobject.kayit_id;
                }
            }
        );
    };
}

I need to access and modify the property tablo_nesne within the afterSelectionEnd function. However, the this keyword points to the wrong context. How do I fix this issue?

Body:
The idiomatic solution in ES6 would be to use an arrow function.

function Tablo() {
    this.kayit_id = 0;
    this.rapor_instanse = 'rapor';
    this.kosul_durum = null;
    this.tablo_nesne = null;
    this.tablo_getir = function() {
        this.tablo_nesne = new Handsontable(
            document.getElementById(this.rapor_instanse), {
                afterGetColHeader: this.arama_filtre_element_ekle,
                beforeOnCellMouseDown: this.doNotSelectColumn,
                columnSorting: true,
                rowHeaders: true,
                currentRowClassName: 'currentRow',
                wordWrap: false,
                licenseKey: 'non-commercial-and-evaluation',
                manualColumnResize: true,
                manualRowResize: true,
                afterSelectionEnd: (r, c, r2, c2) => { // This is an arrow function.
                    let suppliedarrayobject = this.tablo_nesne.getSourceDataAtRow(
                        this.tablo_nesne.toPhysicalRow(r)
                    );
                    this.kayit_id = suppliedarrayobject.kayit_id;
                }
            }
        );
    };
}

The this keyword within an arrow function is bound lexically. Hence, it'll point to the correct context.


问:
PHP Woocommerce get product brand name
I create plugin and want to get brand name from woocommerce.
In fist time i post product no.1 the plugin it's work and get product brand as i wish but when i create product post no.2 and no.3 from brand name get from product no.1

whats wrong ?

```<code>if ( class_exists( 'WooCommerce' ) ) {
        $kode = $product->get_sku();
        $terms = wp_get_post_terms( $product_id, 'brand', array('orderby'=>'name'));

        $brands = get_terms( 'brand', array(
        'orderby'       => 'name'
        //,'product__in'  => $product->id
        // orderby arguments ('name', 'slug','term_group', 'term_id', 'id', 'description')
        ) );

        foreach ( $brands as $key => $brand ) :
            $brand_name = $brand->name;
        endforeach;

        $merk = $brand_name;

        //this i want to print the brand name
        echo "<strong>STOCK ".$merk." ".$kode."</strong><br/>";

    } else {
      echo "please active your WooCommerce plugin.";
    }
</code>```

答:
Instead of taxonomy "brand" it should be "pa_brand".</p>

```<code>$term_names = wp_get_post_terms( $product_id, 'pa_brand', array('orderby'=>'name', 'fields' => 'names'));
</code>```

Title: PHP Woocommerce get product brand name

Body:
I create plugin and want to get brand name from woocommerce.
In fist time i post product no.1 the plugin it's work and get product brand as i wish but when i create product post no.2 and no.3 from brand name get from product no.1

whats wrong ?

if ( class_exists( 'WooCommerce' ) ) {
        $kode = $product->get_sku();
        $terms = wp_get_post_terms( $product_id, 'brand', array('orderby'=>'name'));

        $brands = get_terms( 'brand', array(
        'orderby'       => 'name'
        //,'product__in'  => $product->id
        // orderby arguments ('name', 'slug','term_group', 'term_id', 'id', 'description')
        ) );

        foreach ( $brands as $key => $brand ) :
            $brand_name = $brand->name;
        endforeach;

        $merk = $brand_name;

        //this i want to print the brand name
        echo "STOCK ".$merk." ".$kode."
";

    } else {
      echo "please active your WooCommerce plugin.";
    }

Body:
Instead of taxonomy "brand" it should be "pa_brand".

$term_names = wp_get_post_terms( $product_id, 'pa_brand', array('orderby'=>'name', 'fields' => 'names'));


问:
How to fetch parent ids recursively from json strings
```<code>{
  "id": "1",
  "name": "root",
  "children": [
    {
      "id": "1.1",
      "name": "Child 1",
      "children": [
        {
          "id": "1.1.1",
          "name": "Child 1-1",
          "children": [
            {
              "id": "1-1-1",
              "name": "Child 1-1-1",
              "children": [

              ]
            }
          ]
        },
        {
          "id": "1.1.2",
          "name": "Child 1-2",
          "children": [

          ]
        },
        {
          "id": "1.1.3",
          "name": "Child 1-3",
          "children": [

          ]
        }
      ]
    },
    {
      "id": "1.2",
      "name": "Child 2",
      "children": [
        {
          "id": "1.2.1",
          "name": "Child 2-2",
          "children": [

          ]
        }
      ]
    }
  ]
}
</code>```

This is the JSON string as the response. Had to fetch for the parent elements recursively all the parents id.

For instance, input is 1.2.1 then it returns [1.2]
 input is 1.1.3 then it returns [1.1, 1]

How can I achieve this?

答:
You would have to parse the complete object to recursively inject the parent ids in child objects. Something like this will do the thing.

```<code>function injectParents(data, parents) {
    if(!parents) {
        parents = [];
    }
    parents.push(data.id);
    data.children.map(child=>{
        child.parents = parents;
        if(child.children && child.children.length>0) {
            child = injectParents(child, Array.from(parents));
        }
        return child;
        });
    return data;
}
</code>```

Then you would normally call it like

```<code>const injectedResponse = injectParents(response, null);
</code>```

Body:
{
  "id": "1",
  "name": "root",
  "children": [
    {
      "id": "1.1",
      "name": "Child 1",
      "children": [
        {
          "id": "1.1.1",
          "name": "Child 1-1",
          "children": [
            {
              "id": "1-1-1",
              "name": "Child 1-1-1",
              "children": [

              ]
            }
          ]
        },
        {
          "id": "1.1.2",
          "name": "Child 1-2",
          "children": [

          ]
        },
        {
          "id": "1.1.3",
          "name": "Child 1-3",
          "children": [

          ]
        }
      ]
    },
    {
      "id": "1.2",
      "name": "Child 2",
      "children": [
        {
          "id": "1.2.1",
          "name": "Child 2-2",
          "children": [

          ]
        }
      ]
    }
  ]
}

This is the JSON string as the response. Had to fetch for the parent elements recursively all the parents id.

For instance, input is 1.2.1 then it returns [1.2]
 input is 1.1.3 then it returns [1.1, 1]

How can I achieve this?

Body:
You would have to parse the complete object to recursively inject the parent ids in child objects. Something like this will do the thing.

function injectParents(data, parents) {
    if(!parents) {
        parents = [];
    }
    parents.push(data.id);
    data.children.map(child=>{
        child.parents = parents;
        if(child.children && child.children.length>0) {
            child = injectParents(child, Array.from(parents));
        }
        return child;
        });
    return data;
}

Then you would normally call it like

const injectedResponse = injectParents(response, null);


问:
How can I do dataframe subtraction?
I have the following dataframe:
Col1 is the payment.

```<code>Col1     Value
Item1    100
Item2    200
Item3    300
</code>```

and Col2 is the Project cost

```<code>Col2        Value
Project1    200
Project2    300
Project3    400
</code>```

I basically want to match Col1 with the project in Col2.

How can I get the following dataframe?

```<code>Col2         Value    Col1
Project1     100      Item1
Project1     100      Item2
Project2     100      Item2
Project2     200      Item3
Project3     100      Item3
Project3     300
</code>```

Is there anything I can do in the pandas to get this result?
Thanks a lot

答:
here, you can find logic, comments are added for explaination:

```<code># making list of project requirement and item value to iterate
item_cost = list(zip(payment['Col1'], payment['value']))
requirment = list(zip(project_cost['Col2'], project_cost['value']))

d = {}
for project, cost in requirment:
    item_used = []
    try:
        while cost > 0:
            if item_cost[0][1] <= cost: # if item is having less cost than requirement
                cost -= item_cost[0][1] # making requirement less by item cost
                item_used.append((item_cost[0][1], item_cost[0][0]))
                item_cost = item_cost[1:] # removing item from item_cost once used
            else:
                item_cost[0] = ((item_cost[0][0], item_cost[0][1] - cost))
                item_used.append((cost, item_cost[0][0]))
                cost = 0
    except: # when item list will be finished exception will be called
        item_used.append((cost,np.nan))
    d[project] = item_used
# d is dict having project as key and item used
project_cost['Col1'] = project_cost['Col2'].map(d)
pr_cost = project_cost.explode("Col1")
pr_cost['value'] = pr_cost['Col1'].apply(lambda x:x[0])
pr_cost['Col1'] = pr_cost['Col1'].apply(lambda x:x[1])
</code>```

sample output

As per your new data, we need to just change the column name to above code:

```<code>item_cost = list(zip(payment['Payment'], payment['Value']))
requirment = list(zip(project_cost['Project'], project_cost['Cost']))
d = {}
for project, cost in requirment:
    item_used = []
    try:
        while cost > 0:
            if item_cost[0][1] <= cost: # if item is having less cost than requirement
                cost -= item_cost[0][1] # making requirement less by item cost
                item_used.append((item_cost[0][1], item_cost[0][0]))
                item_cost = item_cost[1:] # removing item from item_cost once used
            else:
                item_cost[0] = ((item_cost[0][0], item_cost[0][1] - cost))
                item_used.append((cost, item_cost[0][0]))
                cost = 0
    except: # when item list will be finished exception will be called
        item_used.append((cost,np.nan))
    d[project] = item_used
project_cost['bank_val'] = project_cost['Project'].map(d)
pr_cost = project_cost.explode("bank_val")
pr_cost['value'] = pr_cost['bank_val'].apply(lambda x:x[0])
pr_cost['bank'] = pr_cost['bank_val'].apply(lambda x:x[1])
print(pr_cost.drop(columns = ['bank_val', 'Cost']))
</code>```

output:

Title: How can I do dataframe subtraction?

Body:
I have the following dataframe:
Col1 is the payment.

Col1     Value
Item1    100
Item2    200
Item3    300

and Col2 is the Project cost

Col2        Value
Project1    200
Project2    300
Project3    400

I basically want to match Col1 with the project in Col2.

How can I get the following dataframe?

Col2         Value    Col1
Project1     100      Item1
Project1     100      Item2
Project2     100      Item2
Project2     200      Item3
Project3     100      Item3
Project3     300

Is there anything I can do in the pandas to get this result?
Thanks a lot

Body:
here, you can find logic, comments are added for explaination:

# making list of project requirement and item value to iterate
item_cost = list(zip(payment['Col1'], payment['value']))
requirment = list(zip(project_cost['Col2'], project_cost['value']))

d = {}
for project, cost in requirment:
    item_used = []
    try:
        while cost > 0:
            if item_cost[0][1] <= cost: # if item is having less cost than requirement
                cost -= item_cost[0][1] # making requirement less by item cost
                item_used.append((item_cost[0][1], item_cost[0][0]))
                item_cost = item_cost[1:] # removing item from item_cost once used
            else:
                item_cost[0] = ((item_cost[0][0], item_cost[0][1] - cost))
                item_used.append((cost, item_cost[0][0]))
                cost = 0
    except: # when item list will be finished exception will be called
        item_used.append((cost,np.nan))
    d[project] = item_used
# d is dict having project as key and item used
project_cost['Col1'] = project_cost['Col2'].map(d)
pr_cost = project_cost.explode("Col1")
pr_cost['value'] = pr_cost['Col1'].apply(lambda x:x[0])
pr_cost['Col1'] = pr_cost['Col1'].apply(lambda x:x[1])

sample output

As per your new data, we need to just change the column name to above code:

item_cost = list(zip(payment['Payment'], payment['Value']))
requirment = list(zip(project_cost['Project'], project_cost['Cost']))
d = {}
for project, cost in requirment:
    item_used = []
    try:
        while cost > 0:
            if item_cost[0][1] <= cost: # if item is having less cost than requirement
                cost -= item_cost[0][1] # making requirement less by item cost
                item_used.append((item_cost[0][1], item_cost[0][0]))
                item_cost = item_cost[1:] # removing item from item_cost once used
            else:
                item_cost[0] = ((item_cost[0][0], item_cost[0][1] - cost))
                item_used.append((cost, item_cost[0][0]))
                cost = 0
    except: # when item list will be finished exception will be called
        item_used.append((cost,np.nan))
    d[project] = item_used
project_cost['bank_val'] = project_cost['Project'].map(d)
pr_cost = project_cost.explode("bank_val")
pr_cost['value'] = pr_cost['bank_val'].apply(lambda x:x[0])
pr_cost['bank'] = pr_cost['bank_val'].apply(lambda x:x[1])
print(pr_cost.drop(columns = ['bank_val', 'Cost']))

output:


答:
```<code>UPDATE client_service_details
SET list_index = service_id -1
</code>```

this should work

Title: MySQL query using update or select statement

Body:
We have a table as follows:

CREATE TABLE client_service_details(
  id bigint(20) NOT NULL AUTO_INCREMENT,
`client_details_id` bigint(20) NOT NULL,
`service_id` bigint(20) NOT NULL,
`list_index`  int(10)  NOT NULL default 0 ,
 PRIMARY KEY (`id`)
)ENGINE=InnoDB ;

+----+-------------------+------------+------------+
| id | client_details_id | service_id | list_index |
+----+-------------------+------------+------------+
|  1 |               101 |          1 |          0 |
|  2 |               101 |          2 |          0 |
|  3 |               101 |          3 |          0 |
|  4 |               102 |          1 |          0 |
|  5 |               102 |          2 |          0 |
|  6 |               102 |          3 |          0 |
|  7 |               102 |          4 |          0 |
|  8 |               103 |          1 |          0 |
|  9 |               103 |          2 |          0 |
+----+-------------------+------------+------------+
9 rows in set (0.00 sec)

WE want to update the column (list_index) based on the client_details_id, servce_id.
Or if we we get the select statement as give below the it is okay

The output should be as follows:

+----+-------------------+------------+------------+
| id | client_details_id | service_id | list_index |
+----+-------------------+------------+------------+
|  1 |               101 |          1 |          0 |
|  2 |               101 |          2 |          1 |
|  3 |               101 |          3 |          2 |
|  4 |               102 |          1 |          0 |
|  5 |               102 |          2 |          1 |
|  6 |               102 |          3 |          2 |
|  7 |               102 |          4 |          3 |
|  8 |               103 |          1 |          0 |
|  9 |               103 |          2 |          1 |
+----+-------------------+------------+------------+

Body:
UPDATE client_service_details
SET list_index = service_id -1

this should work


问:
Is there a C equivalent to Rust's NonNull<T>::dangling() pointer instantiation?
If it exists, it should satisfy the following properties:

Has the type void *

Does not require the instantiation of a "dummy object" to act as the address

It is guaranteed to not compare equal to NULL

Can be constructed without invoking undefined behavior

Works with standards-conforming compiler without needing non-standard extensions

At first I thought I could do something like (NULL + 1) or (void *)1, but these appear to be problematic. The former uses pointer arithmetic on NULL which I believe is undefined behavior. The second relies on the fact that NULL does not have physical address 1. (i.e. it is entirely possible that (void *)0 == (void *)1)

答:
Any void pointer fulfils all your requirements.

As long as you know for sure which addresses that are valid and taken on the specific system, you could create such a pointer manually:

```<code>void* dangling = (void*)0x12345678; // an address which you know for sure isn't taken
</code>```

This is fully standard compliant. The outcome is implementation-defined, since things like allocated valid addresses and alignment are system-specific.

As for what good this will do you, I have no idea. Null pointers are what should be used when a pointer isn't set to point at an allocated address.

At first I thought I could do something like (NULL + 1) or (void *)1, but these appear to be problematic. The former uses pointer arithmetic on NULL which I believe is undefined behavior.

You are mixing up null pointers with the null pointer constant NULL. NULL can expand to 0 or (void*)0.

If you do arithmetic 0 + 1 you simply get an integer constant expression 1. Which can be converted to a pointer if you want, same impl.defined behavior as above and indeed equivalent to (void*)1.

If you do arithmetic (void*)0 + 1 then the code won't compile since you can't do arithmetic on void pointers. And it is UB if you do pointer arithmetic on a pointer not pointing on an allocated array.

Body:
Any void pointer fulfils all your requirements.

As long as you know for sure which addresses that are valid and taken on the specific system, you could create such a pointer manually:

void* dangling = (void*)0x12345678; // an address which you know for sure isn't taken

This is fully standard compliant. The outcome is implementation-defined, since things like allocated valid addresses and alignment are system-specific.

As for what good this will do you, I have no idea. Null pointers are what should be used when a pointer isn't set to point at an allocated address.

At first I thought I could do something like (NULL + 1) or (void *)1, but these appear to be problematic. The former uses pointer arithmetic on NULL which I believe is undefined behavior.

You are mixing up null pointers with the null pointer constant NULL. NULL can expand to 0 or (void*)0.

If you do arithmetic 0 + 1 you simply get an integer constant expression 1. Which can be converted to a pointer if you want, same impl.defined behavior as above and indeed equivalent to (void*)1.

If you do arithmetic (void*)0 + 1 then the code won't compile since you can't do arithmetic on void pointers. And it is UB if you do pointer arithmetic on a pointer not pointing on an allocated array.


问:
Fast AND operation on bit arrays
What can be a faster algorithm for doing bitwise AND operation on large bit-arrays? I have implemented bit-array in C++ using a char array. For now, I am iterating over each byte and performing AND operation.

```<code>void ANDoperation(char* A, char* B){
  for (int i=0; i<(array_size/8 +1); i++ ){
    A[i] &= B[i];
  }
}
</code>```

For K arrays, I am executing this function iteratively K-1 times.

答:
If you would like to go for a more C++-ish way, I would suggest you using std::bitset in a following manner:

#include <iostream>
#include <bitset>

int main()  {
    std::bitset<3> v1(0b110);
    std::bitset<3> v2(0b011);

    v1 &= v2;

    std::cout << v1.to_string() << std::endl; // 010

    return 0;
}
```

<p>Demo</p>

<p>or as @AndrewBainbridge suggested:</p>

<pre class="lang-cpp prettyprint-override"><code>void and_operation(std::bitset<3000>& v1, std::bitset<3000> const& v2) {
    v1 &= v2;
}
</code>```

Title: Fast AND operation on bit arrays

Body:
What can be a faster algorithm for doing bitwise AND operation on large bit-arrays? I have implemented bit-array in C++ using a char array. For now, I am iterating over each byte and performing AND operation.

void ANDoperation(char* A, char* B){
  for (int i=0; i<(array_size/8 +1); i++ ){
    A[i] &= B[i];
  }
}

For K arrays, I am executing this function iteratively K-1 times.

Body:
If you would like to go for a more C++-ish way, I would suggest you using std::bitset in a following manner:

#include <iostream>
#include <bitset>

int main()  {
    std::bitset<3> v1(0b110);
    std::bitset<3> v2(0b011);

    v1 &= v2;

    std::cout << v1.to_string() << std::endl; // 010

    return 0;
}

<a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:2,endLineNumber:13,positionColumn:2,positionLineNumber:13,selectionStartColumn:2,selectionStartLineNumber:13,startColumn:2,startLineNumber:13),source:'%23include+%3Ciostream%3E%0A%23include+%3Cbitset%3E%0A%0Aint+main()++%7B%0A++++std::bitset%3C3%3E+v1(0b110)%3B%0A++++std::bitset%3C3%3E+v2(0b011)%3B%0A%0A++++v1+%26%3D+v2%3B%0A%0A++++std::cout+%3C%3C+v1.to_string()+%3C%3C+std::endl%3B%0A%0A++++return+0%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:52.637075718015666,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:g91,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:1,lang:c%2B%2B,libs:!(),options:'-std%3Dc%2B%2B14+-O3',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+gcc+9.1+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0')),k:37.5,l:'4',m:50,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:1,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%231+with+x86-64+gcc+9.1',t:'0')),header:(),l:'4',m:50,n:'0',o:'',s:0,t:'0')),k:47.362924281984334,l:'3',n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">Demo

or as @AndrewBainbridge suggested:

void and_operation(std::bitset<3000>& v1, std::bitset<3000> const& v2) {
    v1 &= v2;
}


问:
OnClickListener for Multiple ImageButton
I'm super new in Java! Pardon for this question although there are similar ones but I'm completely clueless on fixing my problem.

I'm trying to set an OnClickListener for each ImageButton to open a new activity.
The first ImageButton works but not for the subsequent ones, it is unclickable in AVD.

Would greatly appreciate some help on it!

```<code>public class CharacterSelect extends AppCompatActivity {

ImageButton arrowbtnright;
ImageButton contchibtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_character_select);

    arrowbtnright = (ImageButton) findViewById(R.id.arrowbtnright);
    contchibtn = (ImageButton) findViewById(R.id.contchibtn);

    arrowbtnright.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(CharacterSelect.this, CharacterSelect2.class));

            contchibtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(CharacterSelect.this, MiniChallenge1.class));
                }
            });
        }
    });
}
</code>```

答:
You are currently adding the listener of the second button, from inside the listener of the first button, this is probably not what you want to do .

Try putting both at the same level, i.e :

```<code>arrowbtnright.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View v) {
        startActivity(new Intent(CharacterSelect.this, CharacterSelect2.class));

    }
});

contchibtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View v) {
        startActivity(new Intent(CharacterSelect.this, MiniChallenge1.class));
    }
});
</code>```

Body:
I'm super new in Java! Pardon for this question although there are similar ones but I'm completely clueless on fixing my problem.

I'm trying to set an OnClickListener for each ImageButton to open a new activity.
The first ImageButton works but not for the subsequent ones, it is unclickable in AVD.

Would greatly appreciate some help on it!

public class CharacterSelect extends AppCompatActivity {

ImageButton arrowbtnright;
ImageButton contchibtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_character_select);

    arrowbtnright = (ImageButton) findViewById(R.id.arrowbtnright);
    contchibtn = (ImageButton) findViewById(R.id.contchibtn);

    arrowbtnright.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(CharacterSelect.this, CharacterSelect2.class));

            contchibtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(CharacterSelect.this, MiniChallenge1.class));
                }
            });
        }
    });
}

Body:
You are currently adding the listener of the second button, from inside the listener of the first button, this is probably not what you want to do .

Try putting both at the same level, i.e :

arrowbtnright.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View v) {
        startActivity(new Intent(CharacterSelect.this, CharacterSelect2.class));

    }
});

contchibtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View v) {
        startActivity(new Intent(CharacterSelect.this, MiniChallenge1.class));
    }
});


问:
How do I remove a subset of polygons from a Large SpatialPolygonsDataFrame using a string search, in R?
I have a spatial file in R, that contains all the area units for New Zealand. I have downloaded it in NZGD2000 format. In this file I have irrelevant geographic details, such as the Oceanic regions. I have managed to remove those from my data by simply removing those polygons with higher than a certain value.

```<code>library("dplyr")
library("rgdal")
library("rgeos")

NZAreas <- readOGR("[FILEPATH]/area-unit-2013.shp")
#remove the areas that are offshore
NZAreas@data$AU2013_V1_ <- as.numeric(as.character(NZAreas@data$AU2013_V1_))
NZAreas <- NZAreas[NZAreas@data$AU2013_V1_ < 614000,]
</code>```

I have the problem that the area units include inlets and inland water. I can't remove those in the same way as I removed the coastal units, as the area unit values are not continguous. The @data$$AU2013_V_1 contains the labels for the area units. All the area units I wish to remove have the label starting with "Inlet" or "Inland Water".

I can't work out how to remove these polygons from the data.
First I tried without the dataframe name in front of the @data:

```<code>NZAreas <- NZAreas[!grepl("Inlet", @data$AU2013_V_1),]
Error: unexpected '@' in "NZAreas <- NZAreas[!grepl("Inlet", @"
</code>```

and then I tried:

```<code>NZAreas <- NZAreas[!grepl("Inlet", NZAreas@data$AU2013_V_1),]
</code>```

That second code runs but does not remove the polygons; it does not seem to do anything to the Large SpatialPolygonDataFrame. I checked the dataframe I constructed off NZAreas and there are Inlet and Inland Water rows. How do I remove these polygons?

答:
This should work. It removed  49 areas containing "Inlet" in label and 15 areas having "Inland Water" in label.</p>

```<code>> dim(NZAreas)
[1] 2004    5
> NZAreas=NZAreas[!grepl("Inlet", NZAreas$AU2013_V_1),]
> dim(NZAreas)
[1] 1955    5
> NZAreas=NZAreas[!grepl("Inland Water", NZAreas$AU2013_V_1),]
> dim(NZAreas)
[1] 1940    5
>
</code>```

Body:
I have a spatial file in R, that contains all the area units for New Zealand. I have downloaded it in NZGD2000 format. In this file I have irrelevant geographic details, such as the Oceanic regions. I have managed to remove those from my data by simply removing those polygons with higher than a certain value.

library("dplyr")
library("rgdal")
library("rgeos")

NZAreas <- readOGR("[FILEPATH]/area-unit-2013.shp")
#remove the areas that are offshore
NZAreas@data$AU2013_V1_ <- as.numeric(as.character(NZAreas@data$AU2013_V1_))
NZAreas <- NZAreas[NZAreas@data$AU2013_V1_ < 614000,]

I have the problem that the area units include inlets and inland water. I can't remove those in the same way as I removed the coastal units, as the area unit values are not continguous. The @data$$AU2013_V_1 contains the labels for the area units. All the area units I wish to remove have the label starting with "Inlet" or "Inland Water".

I can't work out how to remove these polygons from the data.
First I tried without the dataframe name in front of the @data:

NZAreas <- NZAreas[!grepl("Inlet", @data$AU2013_V_1),]
Error: unexpected '@' in "NZAreas <- NZAreas[!grepl("Inlet", @"

and then I tried:

NZAreas <- NZAreas[!grepl("Inlet", NZAreas@data$AU2013_V_1),]

That second code runs but does not remove the polygons; it does not seem to do anything to the Large SpatialPolygonDataFrame. I checked the dataframe I constructed off NZAreas and there are Inlet and Inland Water rows. How do I remove these polygons?

Body:
This should work. It removed  49 areas containing "Inlet" in label and 15 areas having "Inland Water" in label.

> dim(NZAreas)
[1] 2004    5
> NZAreas=NZAreas[!grepl("Inlet", NZAreas$AU2013_V_1),]
> dim(NZAreas)
[1] 1955    5
> NZAreas=NZAreas[!grepl("Inland Water", NZAreas$AU2013_V_1),]
> dim(NZAreas)
[1] 1940    5
>


问:
How convert DateTime to string
I get from server response in DateTime like this :

2019-04-24T16:25:02.557Z

and I would like only in String:

2019-04-23

How can I do this?

my code:

```<code>let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let d = job.postedAt
if let date = dateFormatter.date(from: d) {
    let k = dateFormatterPrint.string(from: date)
    destinationVC.createdJob = k
} else {
    print("There was an error decoding the string")
}
</code>```

答:
Try,

```<code>let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyy-MM-dd"
let d = "2019-04-24T16:25:02.557Z"
if let date = dateFormatter.date(from: d) {
    let k = dateFormatterPrint.string(from: date)

    print(k)
} else {
    print("There was an error decoding the string")
}
</code>```

Your dateFormatter.dateFormat should be yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and your dateFormatterPrint.dateFormat should be yyyy-MM-dd.

Title: How convert DateTime to string

Body:
I get from server response in DateTime like this :

2019-04-24T16:25:02.557Z

and I would like only in String:

2019-04-23

How can I do this?

my code:

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let d = job.postedAt
if let date = dateFormatter.date(from: d) {
    let k = dateFormatterPrint.string(from: date)
    destinationVC.createdJob = k
} else {
    print("There was an error decoding the string")
}

Body:
Try,

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyy-MM-dd"
let d = "2019-04-24T16:25:02.557Z"
if let date = dateFormatter.date(from: d) {
    let k = dateFormatterPrint.string(from: date)

    print(k)
} else {
    print("There was an error decoding the string")
}

Your dateFormatter.dateFormat should be yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and your dateFormatterPrint.dateFormat should be yyyy-MM-dd.


问:
Regex: match multiple times between tags
I have following string:

```<code>def index.html index.html default <span class='fp-default'>#default</span> def <span class='fp-default'>#default ddsad def</span>#default<span class='fp-user' default>#user</span>#default
</code>```

And I want to match all occurrences of given substring (e.g. def) that is between tags.

So far I managed to create following regexp, but it didn't work properly (matches only one occurrence between tags):

```<code>(?:(?<=>)|^)([^<]*?(def)[^<]*?)*(?:(?=<)|$)
</code>```

Online regex tester: https://regex101.com/r/oc3ptR/6

Any ideas? Tx!

答:
You may try this:

```<code>def(?=[^<>]*?<\/)
</code>```

Explanation:

def matches def

(?=[^<>]*<\/) Positive look ahead that is looking for a </ i.e.
end tag without matching < and > before it [^<>]*?

Example

Body:
I have following string:

def index.html index.html default #default def #default ddsad def#default#user#default

And I want to match all occurrences of given substring (e.g. def) that is between tags.

So far I managed to create following regexp, but it didn't work properly (matches only one occurrence between tags):

(?:(?<=>)|^)([^<]*?(def)[^<]*?)*(?:(?=<)|$)

Online regex tester: https://regex101.com/r/oc3ptR/6

Any ideas? Tx!

Body:
You may try this:

def(?=[^<>]*?<\/)

Explanation:

def matches def

(?=[^<>]*<\/) Positive look ahead that is looking for a </ i.e.
end tag without matching < and > before it [^<>]*?

Example